Programs & Examples On #Cellid

A Cell ID (CID) is a generally unique number used to identify each Base transceiver station (BTS) or sector of a BTS within a Location area code (LAC) if not within a GSM network.

UICollectionView - dynamic cell height?

Seems like it's quite a popular question, so I will try to make my humble contribution.


The code below is Swift 4 solution for no-storyboard setup. It utilizes some approaches from previous answers, therefore it prevents Auto Layout warning caused on device rotation.

I am sorry if code samples are a bit long. I want to provide an "easy-to-use" solution fully hosted by StackOverflow. If you have any suggestions to the post - please, share the idea and I will update it accordingly.

The setup:

Two classes: ViewController.swift and MultilineLabelCell.swift - Cell containing single UILabel.

MultilineLabelCell.swift

import UIKit

class MultilineLabelCell: UICollectionViewCell {
    static let reuseId = "MultilineLabelCellReuseId"

    private let label: UILabel = UILabel(frame: .zero)

    override init(frame: CGRect) {
        super.init(frame: frame)

        layer.borderColor = UIColor.red.cgColor
        layer.borderWidth = 1.0

        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping

        let labelInset = UIEdgeInsets(top: 10, left: 10, bottom: -10, right: -10)
        contentView.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor, constant: labelInset.top).isActive = true
        label.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor, constant: labelInset.left).isActive = true
        label.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor, constant: labelInset.right).isActive = true
        label.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor, constant: labelInset.bottom).isActive = true

        label.layer.borderColor = UIColor.black.cgColor
        label.layer.borderWidth = 1.0
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("Storyboards are quicker, easier, more seductive. Not stronger then Code.")
    }

    func configure(text: String?) {
        label.text = text
    }

    override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
        label.preferredMaxLayoutWidth = layoutAttributes.size.width - contentView.layoutMargins.left - contentView.layoutMargins.left
        layoutAttributes.bounds.size.height = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        return layoutAttributes
    }
}

ViewController.swift

import UIKit

let samuelQuotes = [
    "Samuel says", 
    "Add different length strings here for better testing"
]

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    private(set) var collectionView: UICollectionView

    // Initializers
    init() {
        // Create new `UICollectionView` and set `UICollectionViewFlowLayout` as its layout
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        // Create new `UICollectionView` and set `UICollectionViewFlowLayout` as its layout
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
        super.init(coder: aDecoder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "Dynamic size sample"

        // Register Cells
        collectionView.register(MultilineLabelCell.self, forCellWithReuseIdentifier: MultilineLabelCell.reuseId)

        // Add `coolectionView` to display hierarchy and setup its appearance
        view.addSubview(collectionView)
        collectionView.backgroundColor = .white
        collectionView.contentInsetAdjustmentBehavior = .always
        collectionView.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

        // Setup Autolayout constraints
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
        collectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
        collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
        collectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true

        // Setup `dataSource` and `delegate`
        collectionView.dataSource = self
        collectionView.delegate = self

        (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = UICollectionViewFlowLayout.automaticSize
        (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).sectionInsetReference = .fromLayoutMargins
    }

    // MARK: - UICollectionViewDataSource -
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MultilineLabelCell.reuseId, for: indexPath) as! MultilineLabelCell
        cell.configure(text: samuelQuotes[indexPath.row])
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return samuelQuotes.count
    }

    // MARK: - UICollectionViewDelegateFlowLayout -
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let sectionInset = (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset
        let referenceHeight: CGFloat = 100 // Approximate height of your cell
        let referenceWidth = collectionView.safeAreaLayoutGuide.layoutFrame.width
            - sectionInset.left
            - sectionInset.right
            - collectionView.contentInset.left
            - collectionView.contentInset.right
        return CGSize(width: referenceWidth, height: referenceHeight)
    }
}

To run this sample create new Xcode project, create corresponding files and replace AppDelegate contents with the following code:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var navigationController: UINavigationController?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)

        if let window = window {
            let vc = ViewController()
            navigationController = UINavigationController(rootViewController: vc)
            window.rootViewController = navigationController
            window.makeKeyAndVisible()
        }

        return true
    }
}

How to Correctly handle Weak Self in Swift Blocks with Arguments

**EDITED for Swift 4.2:

As @Koen commented, swift 4.2 allows:

guard let self = self else {
   return // Could not get a strong reference for self :`(
}

// Now self is a strong reference
self.doSomething()

P.S.: Since I am having some up-votes, I would like to recommend the reading about escaping closures.

EDITED: As @tim-vermeulen has commented, Chris Lattner said on Fri Jan 22 19:51:29 CST 2016, this trick should not be used on self, so please don't use it. Check the non escaping closures info and the capture list answer from @gbk.**

For those who use [weak self] in capture list, note that self could be nil, so the first thing I do is check that with a guard statement

guard let `self` = self else {
   return
}
self.doSomething()

If you are wondering what the quote marks are around self is a pro trick to use self inside the closure without needing to change the name to this, weakSelf or whatever.

UICollectionView current visible cell index

The method [collectionView visibleCells] give you all visibleCells array you want. Use it when you want to get

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    for (UICollectionViewCell *cell in [self.mainImageCollection visibleCells]) {
        NSIndexPath *indexPath = [self.mainImageCollection indexPathForCell:cell];
        NSLog(@"%@",indexPath);
    }
}

Update to Swift 5:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    for cell in yourCollectionView.visibleCells {
        let indexPath = yourCollectionView.indexPath(for: cell)
        print(indexPath)
    }
}

UITableView with fixed section headers

Swift 3.0

Create a ViewController with the UITableViewDelegate and UITableViewDataSource protocols. Then create a tableView inside it, declaring its style to be UITableViewStyle.grouped. This will fix the headers.

lazy var tableView: UITableView = {
    let view = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.grouped)
    view.delegate = self
    view.dataSource = self
    view.separatorStyle = .none
    return view
}()

Creating a UITableView Programmatically

#import "ViewController.h"

@interface ViewController ()

{

    NSMutableArray *name;

}

@end


- (void)viewDidLoad 

{

    [super viewDidLoad];
    name=[[NSMutableArray alloc]init];
    [name addObject:@"ronak"];
    [name addObject:@"vibha"];
    [name addObject:@"shivani"];
    [name addObject:@"nidhi"];
    [name addObject:@"firdosh"];
    [name addObject:@"himani"];

    _tableview_outlet.delegate = self;
    _tableview_outlet.dataSource = self;

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

return [name count];

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *simpleTableIdentifier = @"cell";

    UITableViewCell *cell = [tableView       dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    cell.textLabel.text = [name objectAtIndex:indexPath.row];
    return cell;
}

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

Although this question is fairly old, there is another possibility: If you are using Storyboards, you simply have to set the CellIdentifier in the Storyboard.

So if your CellIdentifier is "Cell", just set the "Identifier" property: enter image description here

Make sure to clean your build after doing so. XCode sometimes has some issues with Storyboard updates

Xcode error - Thread 1: signal SIGABRT

SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.

How do you load custom UITableViewCells from Xib files?

In Swift 4.2 and Xcode 10

I have three XIB cell files

in ViewDidLoad register your XIB files like this...

This is first approach

tableView.register(UINib.init(nibName: "XIBCell", bundle: nil), forCellReuseIdentifier: "cell1")
tableView.register(UINib.init(nibName: "XIBCell2", bundle: nil), forCellReuseIdentifier: "cell2")
//tableView.register(UINib.init(nibName: "XIBCell3", bundle: nil), forCellReuseIdentifier: "cell3")

Second approach directly register XIB files in cellForRowAt indexPath:

This is my tableview delegate functions

//MARK: - Tableview delegates
override func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return 6
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //This is first approach
    if indexPath.row == 0 {//Load first XIB cell
        let placeCell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! XIBCell
        return placeCell
    //Second approach
    } else if indexPath.row == 5 {//Load XIB cell3
        var cell = tableView.dequeueReusableCell(withIdentifier:"cell3") as? XIBCell3
        if cell == nil{
            let arrNib:Array = Bundle.main.loadNibNamed("XIBCell3",owner: self, options: nil)!
            cell = arrNib.first as? XIBCell3
        }

        //ADD action to XIB cell button
        cell?.btn.tag = indexPath.row//Add tag to button
        cell?.btn.addTarget(self, action: #selector(self.bookbtn1(_:)), for: .touchUpInside);//selector

        return cell!
    //This is first approach
    } else {//Load XIB cell2
        let placeCell = tableView.dequeueReusableCell(withIdentifier: "cell2") as! XIBCell2

        return placeCell
    }

}

How to print third column to last column?

Jonathan Feinberg's answer prints each field on a separate line. You could use printf to rebuild the record for output on the same line, but you can also just move the fields a jump to the left.

awk '{for (i=1; i<=NF-2; i++) $i = $(i+2); NF-=2; print}' logfile

Most efficient way to append arrays in C#?

You can't append to an actual array - the size of an array is fixed at creation time. Instead, use a List<T> which can grow as it needs to.

Alternatively, keep a list of arrays, and concatenate them all only when you've grabbed everything.

See Eric Lippert's blog post on arrays for more detail and insight than I could realistically provide :)

JavaScript variable number of arguments to function

It is preferable to use rest parameter syntax as Ramast pointed out.

function (a, b, ...args) {}

I just want to add some nice property of the ...args argument

  1. It is an array, and not an object like arguments. This allows you to apply functions like map or sort directly.
  2. It does not include all parameters but only the one passed from it on. E.g. function (a, b, ...args) in this case args contains argument 3 to arguments.length

SSIS how to set connection string dynamically from a config file

Some options:

  1. You can use the Execute Package Utility to change your datasource, before running the package.

  2. You can run your package using DTEXEC, and change your connection by passing in a /CONNECTION parameter. Probably save it as a batch so next time you don't need to type the whole thing and just change the datasource as required.

  3. You can use the SSIS XML package configuration file. Here is a walk through.

  4. You can save your configrations in a database table.

How to set background color of an Activity to white programmatically?

I prefer coloring by theme

<style name="CustomTheme" parent="android:Theme.Light">
    <item name="android:windowBackground">@color/custom_theme_color</item>
    <item name="android:colorBackground">@color/custom_theme_color</item>
</style>

Open a Web Page in a Windows Batch FIle

hh.exe (help pages renderer) is capable of opening some simple webpages:

hh http://www.nissan.com

This will work even if browsing is blocked through:

HKEY_CURRENT_USER\Software\Policies\Microsoft\Internet Explorer

Constructors in Go

There are no default constructors in Go, but you can declare methods for any type. You could make it a habit to declare a method called "Init". Not sure if how this relates to best practices, but it helps keep names short without loosing clarity.

package main

import "fmt"

type Thing struct {
    Name string
    Num int
}

func (t *Thing) Init(name string, num int) {
    t.Name = name
    t.Num = num
}

func main() {
    t := new(Thing)
    t.Init("Hello", 5)
    fmt.Printf("%s: %d\n", t.Name, t.Num)
}

The result is:

Hello: 5

Python regular expressions return true/false

Ignacio Vazquez-Abrams is correct. But to elaborate, re.match() will return either None, which evaluates to False, or a match object, which will always be True as he said. Only if you want information about the part(s) that matched your regular expression do you need to check out the contents of the match object.

How do I get the value of text input field using JavaScript?

If you are using jQuery then by using plugin formInteract, you just need to do this:

// Just keep the HTML as it is.

<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>

At bottom of the page just include this plugin file and write this code:

// Initialize one time at the bottom of the page.
var search= $("#searchTxt).formInteract();

search.getAjax("http://www.myurl.com/search/", function(rsp){
    // Now do whatever you want to with your response
});

Or if using a parameterized URL then use this:

$.get("http://www.myurl.com/search/"+search.get().searchTxt, {}, function(rsp){
    // Now do work with your response;
})

Here is the link to project https://bitbucket.org/ranjeet1985/forminteract

You can use this plugin for many purposes like getting the value of a form, putting values into a form, validation of forms and many more. You can see some example of code in the index.html file of the project.

Of course I am the author of this project and all are welcome to make it better.

Split string by single spaces

If you are averse to boost, you can use regular old operator>>, along with std::noskipws:

EDIT: updates after testing.

#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <sstream>

void split(const std::string& str, std::vector<std::string>& v) {
  std::stringstream ss(str);
  ss >> std::noskipws;
  std::string field;
  char ws_delim;
  while(1) {
    if( ss >> field )
      v.push_back(field);
    else if (ss.eof())
      break;
    else
      v.push_back(std::string());
    ss.clear();
    ss >> ws_delim;
  }
}

int main() {
  std::vector<std::string> v;
  split("hello world  how are   you", v);
  std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "-"));
  std::cout << "\n";
}

http://ideone.com/62McC

How do you find the sum of all the numbers in an array in Java?

In Java 8

Code:

   int[] array = new int[]{1,2,3,4,5};
   int sum = IntStream.of(array).reduce( 0,(a, b) -> a + b);
   System.out.println("The summation of array is " + sum);

  System.out.println("Another way to find summation :" + IntStream.of(array).sum());

Output:

The summation of array is 15
Another way to find summation :15

Explanation:

In Java 8, you can use reduction concept to do your addition.

Read all about Reduction

HttpClient 4.0.1 - how to release connection?

If the response is not to be consumed, then the request can be aborted using the code below:

// Low level resources should be released before initiating a new request
HttpEntity entity = response.getEntity();

if (entity != null) {
    // Do not need the rest
    httpPost.abort();
}

Reference: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e143

Apache HttpClient Version: 4.1.3

How to check if a variable is an integer or a string?

Depending on your definition of shortly, you could use one of the following options:

ssh_exchange_identification: Connection closed by remote host under Git bash

if hostname does not work, try IP address.

This is going on right now so I have to say. I try to ssh with my host name and it does not work

ssh [email protected]

this gives the error "ssh_exchange_identification: Connection closed by remote host"

this USED to work one hour back.

BUT, and here is the interesting part, the IP address works!

ssh [email protected]

(of course the actual IP address is different)

Go figure!

jquery select element by xpath

If you are debugging or similar - In chrome developer tools, you can simply use

$x('/html/.//div[@id="text"]')

Difference of keywords 'typename' and 'class' in templates?

For naming template parameters, typename and class are equivalent. §14.1.2:

There is no semantic difference between class and typename in a template-parameter.

typename however is possible in another context when using templates - to hint at the compiler that you are referring to a dependent type. §14.6.2:

A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename.

Example:

typename some_template<T>::some_type

Without typename the compiler can't tell in general whether you are referring to a type or not.

html cellpadding the left side of a cell

I would suggest using inline CSS styling.

<table border="1" style="padding-right: 10px;">
<tr>
<td>Content</td>
</tr>
</table>

or

<table border="1">
<tr style="padding-right: 10px;">
<td>Content</td>
</tr>
</table>

or

<table border="1">
<tr>
<td style="padding-right: 10px;">Content</td>
</tr>
</table>

I don't quite follow what you need, but this is what I would do, assuming I understand you needs.

cvc-elt.1: Cannot find the declaration of element 'MyElement'

After making the change suggested above by Martin, I was still getting the same error. I had to make an additional change to my parsing code. I was parsing the XML file via a DocumentBuilder as shown in the oracle docs: https://docs.oracle.com/javase/7/docs/api/javax/xml/validation/package-summary.html

// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

The problem was that DocumentBuilder is not namespace aware by default. The following additional change resolved the issue:

// parse an XML document into a DOM tree
DocumentBuilderFactory dmfactory = DocumentBuilderFactory.newInstance();
dmfactory.setNamespaceAware(true);

DocumentBuilder parser = dmfactory.newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

How to see full absolute path of a symlink

You can use awk with a system call readlink to get the equivalent of an ls output with full symlink paths. For example:

ls | awk '{printf("%s ->", $1); system("readlink -f " $1)}'

Will display e.g.

thin_repair ->/home/user/workspace/boot/usr/bin/pdata_tools
thin_restore ->/home/user/workspace/boot/usr/bin/pdata_tools
thin_rmap ->/home/user/workspace/boot/usr/bin/pdata_tools
thin_trim ->/home/user/workspace/boot/usr/bin/pdata_tools
touch ->/home/user/workspace/boot/usr/bin/busybox
true ->/home/user/workspace/boot/usr/bin/busybox

Number of days between past date and current date in Google spreadsheet

DAYS360 does not calculate what you want, i.e. the number of days passed between the two dates. Use simple subtraction (-) or MINUS(). I made an updated copy of @DrCord’s sample spreadsheet to illustrate this.

Are you SURE you want DAYS360? That is a specialized function used in the financial sector to simplify calculations for bonds. It assumes a 360 day year, with 12 months of 30 days each. If you really want actual days, you'll lose 6 days each year. [source]

JQuery confirm dialog

Have you tried using the official JQueryUI implementation (not jQuery only) : ?

Create a new database with MySQL Workbench

Those who are new to MySQL & Mac users; Note that, Connection is different than Database.

Steps to create a database.

Step 1: Create connection and click to go inside

Step 1

Step 2: Click on database icon

Step 2

Step 3: Name your database schema

Step 3

Step 4: Apply query

Step 4

Step 5: Your DB created, enjoy...

Step 5

What is the difference between pip and conda?

Not to confuse you further, but you can also use pip within your conda environment, which validates the general vs. python specific managers comments above.

conda install -n testenv pip
source activate testenv
pip <pip command>

you can also add pip to default packages of any environment so it is present each time so you don't have to follow the above snippet.

Sending POST data without form

If you don't want your data to be seen by the user, use a PHP session.

Data in a post request is still accessible (and manipulable) by the user.

Checkout this tutorial on PHP Sessions.

Sharing link on WhatsApp from mobile website (not application) for Android

LATEST UPDATE

Now you can use the latest API from whatsapp https://wa.me/ without worrying about the user agent, the API will do the user agent handling.

Share pre-filled text with contact selection option in respective whatsapp client (Android / iOS / Webapp):

https://wa.me/?text=urlencodedtext

Open Chat Dialog for a particular whatsapp user in respective whatsapp client (Android / iOS / Webapp):

https://wa.me/whatsappphonenumber

Share pre-filled text with a particular user (Combine above two):

https://wa.me/whatsappphonenumber/?text=urlencodedtext

Note : whatsappphonenumber should be full phone number in international format. Omit any zeroes, brackets or dashes when adding the phone number in international format.

For official documentation visit https://faq.whatsapp.com/en/general/26000030

Spark Dataframe distinguish columns with duplicated name

You can use def drop(col: Column) method to drop the duplicated column,for example:

DataFrame:df1

+-------+-----+
| a     | f   |
+-------+-----+
|107831 | ... |
|107831 | ... |
+-------+-----+

DataFrame:df2

+-------+-----+
| a     | f   |
+-------+-----+
|107831 | ... |
|107831 | ... |
+-------+-----+

when I join df1 with df2, the DataFrame will be like below:

val newDf = df1.join(df2,df1("a")===df2("a"))

DataFrame:newDf

+-------+-----+-------+-----+
| a     | f   | a     | f   |
+-------+-----+-------+-----+
|107831 | ... |107831 | ... |
|107831 | ... |107831 | ... |
+-------+-----+-------+-----+

Now, we can use def drop(col: Column) method to drop the duplicated column 'a' or 'f', just like as follows:

val newDfWithoutDuplicate = df1.join(df2,df1("a")===df2("a")).drop(df2("a")).drop(df2("f"))

Alternate background colors for list items

Try adding a pair of class attributes, say 'even' and 'odd', to alternating list elements, e.g.

<ul>
    <li class="even"><a href="link">Link 1</a></li>
    <li class="odd"><a href="link">Link 2</a></li>
    <li class="even"><a href="link">Link 3</a></li>
    <li class="odd"><a href="link">Link 4</a></li>
    <li class="even"><a href="link">Link 5</a></li>
</ul>

In a <style> section of the HTML page, or in a linked stylesheet, you would define those same classes, specifying your desired background colours:

li.even { background-color: red; }
li.odd { background-color: blue; }

You might want to use a template library as your needs evolve to provide you with greater flexibility and to cut down on the typing. Why type all those list elements by hand?

What is the 'new' keyword in JavaScript?

JavaScript is an object-oriented programming language and it's used exactly for creating instances. It's prototype-based, rather than class-based, but that does not mean that it is not object-oriented.

How do I add multiple conditions to "ng-disabled"?

Actually the ng-disabled directive works with the " || " logical operator for me. The " && " evaluate only one condition.

http://jsbin.com/kuqilejesi/2/edit?html,js,output

How to animate the change of image in an UIImageView?

CABasicAnimation* fadeAnim = [CABasicAnimation animationWithKeyPath:@"contents"];
fadeAnim.fromValue = (__bridge id)imageView.image.CGImage;
fadeAnim.toValue = (__bridge id)[UIImage imageNamed:@"newImage.png"].CGImage;
fadeAnim.duration = 2.0;
[imageView.layer addAnimation:fadeAnim forKey:@"contents"];
imageView.layer.contents = (__bridge id)[UIImage imageNamed:@"newImage.png"].CGImage;

Downloading jQuery UI CSS from Google's CDN

You could use this one if you mean the jQuery UI css:

<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

What is the difference between json.load() and json.loads() functions

In python3.7.7, the definition of json.load is as below according to cpython source code:

def load(fp, *, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):

    return loads(fp.read(),
        cls=cls, object_hook=object_hook,
        parse_float=parse_float, parse_int=parse_int,
        parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

json.load actually calls json.loads and use fp.read() as the first argument.

So if your code is:

with open (file) as fp:
    s = fp.read()
    json.loads(s)

It's the same to do this:

with open (file) as fp:
    json.load(fp)

But if you need to specify the bytes reading from the file as like fp.read(10) or the string/bytes you want to deserialize is not from file, you should use json.loads()

As for json.loads(), it not only deserialize string but also bytes. If s is bytes or bytearray, it will be decoded to string first. You can also find it in the source code.

def loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
    """Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
    containing a JSON document) to a Python object.

    ...

    """
    if isinstance(s, str):
        if s.startswith('\ufeff'):
            raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
                                  s, 0)
    else:
        if not isinstance(s, (bytes, bytearray)):
            raise TypeError(f'the JSON object must be str, bytes or bytearray, '
                            f'not {s.__class__.__name__}')
        s = s.decode(detect_encoding(s), 'surrogatepass')

How should I store GUID in MySQL tables?

Adding to the answer by ThaBadDawg, use these handy functions (thanks to a wiser collegue of mine) to get from 36 length string back to a byte array of 16.

DELIMITER $$

CREATE FUNCTION `GuidToBinary`(
    $Data VARCHAR(36)
) RETURNS binary(16)
DETERMINISTIC
NO SQL
BEGIN
    DECLARE $Result BINARY(16) DEFAULT NULL;
    IF $Data IS NOT NULL THEN
        SET $Data = REPLACE($Data,'-','');
        SET $Result =
            CONCAT( UNHEX(SUBSTRING($Data,7,2)), UNHEX(SUBSTRING($Data,5,2)),
                    UNHEX(SUBSTRING($Data,3,2)), UNHEX(SUBSTRING($Data,1,2)),
                    UNHEX(SUBSTRING($Data,11,2)),UNHEX(SUBSTRING($Data,9,2)),
                    UNHEX(SUBSTRING($Data,15,2)),UNHEX(SUBSTRING($Data,13,2)),
                    UNHEX(SUBSTRING($Data,17,16)));
    END IF;
    RETURN $Result;
END

$$

CREATE FUNCTION `ToGuid`(
    $Data BINARY(16)
) RETURNS char(36) CHARSET utf8
DETERMINISTIC
NO SQL
BEGIN
    DECLARE $Result CHAR(36) DEFAULT NULL;
    IF $Data IS NOT NULL THEN
        SET $Result =
            CONCAT(
                HEX(SUBSTRING($Data,4,1)), HEX(SUBSTRING($Data,3,1)),
                HEX(SUBSTRING($Data,2,1)), HEX(SUBSTRING($Data,1,1)), '-', 
                HEX(SUBSTRING($Data,6,1)), HEX(SUBSTRING($Data,5,1)), '-',
                HEX(SUBSTRING($Data,8,1)), HEX(SUBSTRING($Data,7,1)), '-',
                HEX(SUBSTRING($Data,9,2)), '-', HEX(SUBSTRING($Data,11,6)));
    END IF;
    RETURN $Result;
END
$$

CHAR(16) is actually a BINARY(16), choose your preferred flavour

To follow the code better, take the example given the digit-ordered GUID below. (Illegal characters are used for illustrative purposes - each place a unique character.) The functions will transform the byte ordering to achieve a bit order for superior index clustering. The reordered guid is shown below the example.

12345678-9ABC-DEFG-HIJK-LMNOPQRSTUVW
78563412-BC9A-FGDE-HIJK-LMNOPQRSTUVW

Dashes removed:

123456789ABCDEFGHIJKLMNOPQRSTUVW
78563412BC9AFGDEHIJKLMNOPQRSTUVW

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

It's weird ... I've got the exact same error, coming from a different thing. When I create my controller I passed the $location parameter, like this :

App.controller('MessageController', function ($scope, $http, $log, $location, $attrs, MessageFactory, SocialMessageFactory) {
   // controller code
});

This was proven to be a bug when we use third party libraries or pure JS to manipulate some specifics (here window.location) the next digest of angular will blow this error.

So I simply removed the $location from the controller creation parameter, and it worked again, without this error. Or if you absolutely need to use the $location from angular, you have to remove every single <a href="#">link</a> in the links of your template page, and rather write href="". Worked for me.

Hope it can help one day.

.NET String.Format() to add commas in thousands place for a number

just simple as this:

float num = 23658; // for example 
num = num.ToString("N0"); // Returns 23,658

more info is in Here

In Oracle SQL: How do you insert the current date + time into a table?

It only seems to because that is what it is printing out. But actually, you shouldn't write the logic this way. This is equivalent:

insert into errortable (dateupdated, table1id)
    values (sysdate, 1083);

It seems silly to convert the system date to a string just to convert it back to a date.

If you want to see the full date, then you can do:

select TO_CHAR(dateupdated, 'YYYY-MM-DD HH24:MI:SS'), table1id
from errortable;

TypeScript error TS1005: ';' expected (II)

I was injecting service like this:

private messageShowService MessageShowService

instead of:

private messageShowService: MessageShowService

and that was the reason of error, despite nothing related with ',' was there.

Do something if screen width is less than 960 px

You can also use a media query with javascript.

const mq = window.matchMedia( "(min-width: 960px)" );

if (mq.matches) {
       alert("window width >= 960px");
} else {
     alert("window width < 960px");
}

How to identify server IP address in PHP

If you are using PHP in bash shell you can use:

$server_name=exec('hostname');

Because $_SERVER[] SERVER_ADDR, HTTP_HOST and SERVER_NAME are not set.

How an 'if (A && B)' statement is evaluated?

Yes, it is called Short-circuit Evaluation.

If the validity of the boolean statement can be assured after part of the statement, the rest is not evaluated.

This is very important when some of the statements have side-effects.

How to construct a WebSocket URI relative to the page URI?

On localhost you should consider context path.

function wsURL(path) {
    var protocol = (location.protocol === 'https:') ? 'wss://' : 'ws://';
    var url = protocol + location.host;
    if(location.hostname === 'localhost') {
        url += '/' + location.pathname.split('/')[1]; // add context path
    }
    return url + path;
}

How many significant digits do floats and doubles have in java?

Floating point numbers are encoded using an exponential form, that is something like m * b ^ e, i.e. not like integers at all. The question you ask would be meaningful in the context of fixed point numbers. There are numerous fixed point arithmetic libraries available.

Regarding floating point arithmetic: The number of decimal digits depends on the presentation and the number system. For example there are periodic numbers (0.33333) which do not have a finite presentation in decimal but do have one in binary and vice versa.

Also it is worth mentioning that floating point numbers up to a certain point do have a difference larger than one, i.e. value + 1 yields value, since value + 1 can not be encoded using m * b ^ e, where m, b and e are fixed in length. The same happens for values smaller than 1, i.e. all the possible code points do not have the same distance.

Because of this there is no precision of exactly n digits like with fixed point numbers, since not every number with n decimal digits does have a IEEE encoding.

There is a nearly obligatory document which you should read then which explains floating point numbers: What every computer scientist should know about floating point arithmetic.

How can I add reflection to a C++ application?

Ponder is a C++ reflection library, in answer to this question. I considered the options and decided to make my own since I couldn't find one that ticked all my boxes.

Although there are great answers to this question, I don't want to use tonnes of macros, or rely on Boost. Boost is a great library, but there are lots of small bespoke C++0x projects out that are simpler and have faster compile times. There are also advantages to being able to decorate a class externally, like wrapping a C++ library that doesn't (yet?) support C++11. It is fork of CAMP, using C++11, that no longer requires Boost.

Reloading .env variables without restarting server (Laravel 5, shared hosting)

I know this is old, but for local dev, this is what got things back to a production .env file:

rm bootstrap/cache/config.php

then

php artisan config:cache
php artisan config:clear
php artisan cache:clear

How to use nan and inf in C?

<inf.h>

/* IEEE positive infinity.  */

#if __GNUC_PREREQ(3,3)
# define INFINITY   (__builtin_inff())
#else
# define INFINITY   HUGE_VALF
#endif

and

<bits/nan.h>
#ifndef _MATH_H
# error "Never use <bits/nan.h> directly; include <math.h> instead."
#endif


/* IEEE Not A Number.  */

#if __GNUC_PREREQ(3,3)

# define NAN    (__builtin_nanf (""))

#elif defined __GNUC__

# define NAN \
  (__extension__                                  \
   ((union { unsigned __l __attribute__ ((__mode__ (__SI__))); float __d; })  \
    { __l: 0x7fc00000UL }).__d)

#else

# include <endian.h>

# if __BYTE_ORDER == __BIG_ENDIAN
#  define __nan_bytes       { 0x7f, 0xc0, 0, 0 }
# endif
# if __BYTE_ORDER == __LITTLE_ENDIAN
#  define __nan_bytes       { 0, 0, 0xc0, 0x7f }
# endif

static union { unsigned char __c[4]; float __d; } __nan_union
    __attribute_used__ = { __nan_bytes };
# define NAN    (__nan_union.__d)

#endif  /* GCC.  */

Collection was modified; enumeration operation may not execute

InvalidOperationException- An InvalidOperationException has occurred. It reports a "collection was modified" in a foreach-loop

Use break statement, Once the object is removed.

ex:

ArrayList list = new ArrayList(); 

foreach (var item in list)
{
    if(condition)
    {
        list.remove(item);
        break;
    }
}

TreeMap sort by value

You can't have the TreeMap itself sort on the values, since that defies the SortedMap specification:

A Map that further provides a total ordering on its keys.

However, using an external collection, you can always sort Map.entrySet() however you wish, either by keys, values, or even a combination(!!) of the two.

Here's a generic method that returns a SortedSet of Map.Entry, given a Map whose values are Comparable:

static <K,V extends Comparable<? super V>>
SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
    SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
        new Comparator<Map.Entry<K,V>>() {
            @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                int res = e1.getValue().compareTo(e2.getValue());
                return res != 0 ? res : 1;
            }
        }
    );
    sortedEntries.addAll(map.entrySet());
    return sortedEntries;
}

Now you can do the following:

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

    System.out.println(map);
    // prints "{A=3, B=2, C=1}"
    System.out.println(entriesSortedByValues(map));
    // prints "[C=1, B=2, A=3]"

Note that funky stuff will happen if you try to modify either the SortedSet itself, or the Map.Entry within, because this is no longer a "view" of the original map like entrySet() is.

Generally speaking, the need to sort a map's entries by its values is atypical.


Note on == for Integer

Your original comparator compares Integer using ==. This is almost always wrong, since == with Integer operands is a reference equality, not value equality.

    System.out.println(new Integer(0) == new Integer(0)); // prints "false"!!!

Related questions

C++ - how to find the length of an integer

Not necessarily the most efficient, but one of the shortest and most readable using C++:

std::to_string(num).length()

Check if inputs are empty using jQuery

The :empty pseudo-selector is used to see if an element contains no childs, you should check the value :

$('#apply-form input').blur(function() {
     if(!this.value) { // zero-length string
            $(this).parents('p').addClass('warning');
     }
});

npm ERR cb() never called

I had the cb() never called! error, and none of the answers here directly worked for me. I was running Node v8.11.2, and I had to manually delete the package-lock.json file to get anywhere. After doing this, I ran npm cache verify per what some of the answers recommended. Then, running npm i yielded the following result:

npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

up to date in 5.118s

Is it possible to 'prefill' a google form using data from a google spreadsheet?

You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:

https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899

buildUrls()

In this example, question 1, "Name", has an ID of 726721210, while question 2, "Birthday" is 787184751. Questions 3 and 4 are blank.

You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:

function buildUrls() {
  var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
  var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1");  // Email, Name, Birthday
  var data = ss.getDataRange().getValues();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    var url = template.replace('##Name##',escape(data[i][1]))
                      .replace('##Birthday##',data[i][2].yyyymmdd());  // see yyyymmdd below
    Logger.log(url);  // You could do something more useful here.
  }
};

This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.

betterBuildUrls()

Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.

Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0] is "Name", [1] is "Birthday", and so on.

We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.

(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)

/**
 * Use Form API to generate pre-filled form URLs
 */
function betterBuildUrls() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Sheet1");
  var data = ss.getDataRange().getValues();  // Data for pre-fill

  var formUrl = ss.getFormUrl();             // Use form attached to sheet
  var form = FormApp.openByUrl(formUrl);
  var items = form.getItems();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    // Create a form response object, and prefill it
    var formResponse = form.createResponse();

    // Prefill Name
    var formItem = items[0].asTextItem();
    var response = formItem.createResponse(data[i][1]);
    formResponse.withItemResponse(response);

    // Prefill Birthday
    formItem = items[1].asDateItem();
    response = formItem.createResponse(data[i][2]);
    formResponse.withItemResponse(response);

    // Get prefilled form URL
    var url = formResponse.toPrefilledUrl();
    Logger.log(url);  // You could do something more useful here.
  }
};

yymmdd Function

Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd. This helper function extends the Date object with a new method to handle the conversion.

When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975 you could use 5/9/1975.)

// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear().toString();                                    
  var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
  var dd  = this.getDate().toString();             

  return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

Python - Passing a function into another function

Just pass it in like any other parameter:

def a(x):
    return "a(%s)" % (x,)

def b(f,x):
    return f(x)

print b(a,10)

Android : difference between invisible and gone?

  • View.INVISIBLE->The View is invisible but it will occupy some space in layout

  • View.GONE->The View is not visible and it will not occupy any space in layout

How to wait till the response comes from the $http request, in angularjs?

FYI, this is using Angularfire so it may vary a bit for a different service or other use but should solve the same isse $http has. I had this same issue only solution that fit for me the best was to combine all services/factories into a single promise on the scope. On each route/view that needed these services/etc to be loaded I put any functions that require loaded data inside the controller function i.e. myfunct() and the main app.js on run after auth i put

myservice.$loaded().then(function() {$rootScope.myservice = myservice;});

and in the view I just did

ng-if="myservice" ng-init="somevar=myfunct()"

in the first/parent view element/wrapper so the controller can run everything inside

myfunct()

without worrying about async promises/order/queue issues. I hope that helps someone with the same issues I had.

LEFT JOIN in LINQ to entities?

Ah, got it myselfs.
The quirks and quarks of LINQ-2-entities.
This looks most understandable:

var query2 = (
    from users in Repo.T_Benutzer
    from mappings in Repo.T_Benutzer_Benutzergruppen
        .Where(mapping => mapping.BEBG_BE == users.BE_ID).DefaultIfEmpty()
    from groups in Repo.T_Benutzergruppen
        .Where(gruppe => gruppe.ID == mappings.BEBG_BG).DefaultIfEmpty()
    //where users.BE_Name.Contains(keyword)
    // //|| mappings.BEBG_BE.Equals(666)  
    //|| mappings.BEBG_BE == 666 
    //|| groups.Name.Contains(keyword)

    select new
    {
         UserId = users.BE_ID
        ,UserName = users.BE_User
        ,UserGroupId = mappings.BEBG_BG
        ,GroupName = groups.Name
    }

);


var xy = (query2).ToList();

Remove the .DefaultIfEmpty(), and you get an inner join.
That was what I was looking for.

Update query PHP MySQL

<?php
require 'db_config.php';


  $id  = $_POST["id"];
  $post = $_POST;

  $sql = "UPDATE items SET title = '".$post['title']."'

    ,description = '".$post['description']."' 

    WHERE id = '".$id."'";

  $result = $mysqli->query($sql);


  $sql = "SELECT * FROM items WHERE id = '".$id."'"; 

  $result = $mysqli->query($sql);

  $data = $result->fetch_assoc();


echo json_encode($data);
?>

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

For similar assembly binding errors , following steps may help:

  1. Right click on your Solution and click Manage Nuget Packages for Solution ...
  2. go to Consolidate Tab (last tab) and check if any any differences between packages installed in different projects inside your solution. specially pay attention to your referenced projects which may have lower versions because they usually are less noticed)
  3. consolidate specially packages related to your assembly error and note that many packages are dependent on some other packages like *.code & *.api & ...
  4. after resolving all suspected consolidations , rebuild and rerun the app and see if the assembly bindings are resolved.

What are the differences between WCF and ASMX web services?

ASMX Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type.

Second, ASMX web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.

We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc

How to embed a YouTube channel into a webpage

Seems like the accepted answer does not work anymore. I found the correct method from another post: https://stackoverflow.com/a/46811403/6368026

Now you should use:

http://www.youtube.com/embed/videoseries?list=USERID And the USERID is your youtube user id with 'UU' appended.

For example, if your user id is TlQ5niAIDsLdEHpQKQsupg then you should put UUTlQ5niAIDsLdEHpQKQsupg. If you only have the channel id (which you can find in your channel URL) then just replace the first two characters (UC) with UU.

So in the end you would have an URL like this:

http://www.youtube.com/embed/videoseries?list=UUTlQ5niAIDsLdEHpQKQsupg

In Java, how to append a string more efficiently?

Use StringBuilder class. It is more efficient at what you are trying to do.

document.all vs. document.getElementById

Specifically, document.all was introduced for IE4 BEFORE document.getElementById had been introduced.

So, the presence of document.all means that the code is intended to support IE4, or is trying to identify the browser as IE4 (though it could have been Opera), or the person who wrote (or copied and pasted) the code wasn't up on the latest.

In the highly unlikely event that you need to support IE4, then, you do need document.all (or a library that handles these ancient IE specs).

mysql update multiple columns with same now()

Found a solution:

mysql> UPDATE table SET last_update=now(), last_monitor=last_update WHERE id=1;

I found this in MySQL Docs and after a few tests it works:

the following statement sets col2 to the current (updated) col1 value, not the original col1 value. The result is that col1 and col2 have the same value. This behavior differs from standard SQL.

UPDATE t1 SET col1 = col1 + 1, col2 = col1;

TypeError: 'str' object cannot be interpreted as an integer

x = int(input("Give starting number: "))
y = int(input("Give ending number: "))

for i in range(x, y):
    print(i)

This outputs:

i have uploaded the output with the code

href image link download on click

HTML download attribute to specify that the target will be downloaded when a user clicks on the hyperlink.

This attribute is only used if the href attribute is set.

The value of the attribute will be the name of the downloaded file. There are no restrictions on allowed values, and the browser will automatically detect the correct file extension and add it to the file (.img, .pdf, .txt, .html, etc.).

Example code:

<a href="https://www.w3schools.com/images/myw3schoolsimage.jpg"> Download Image >></a>

HTML5:

<a href="https://www.w3schools.com/images/myw3schoolsimage.jpg" download> Download Image >></a>

Output:

Download Image >>

Html5 download or chrome

Download Image >>

How do we determine the number of days for a given month in python

Just for the sake of academic interest, I did it this way...

(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day

Jest spyOn function called

You were almost done without any changes besides how you spyOn. When you use the spy, you have two options: spyOn the App.prototype, or component component.instance().

const spy = jest.spyOn(Class.prototype, "method")

The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.

const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);

The App.prototype bit on the first line there are what you needed to make things work. A JavaScript class doesn't have any of its methods until you instantiate it with new MyClass(), or you dip into the MyClass.prototype. For your particular question, you just needed to spy on the App.prototype method myClickFn.

jest.spyOn(component.instance(), "method")

const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");

This method requires a shallow/render/mount instance of a React.Component to be available. Essentially spyOn is just looking for something to hijack and shove into a jest.fn(). It could be:

A plain object:

const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");

A class:

class Foo {
    bar() {}
}

const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance

const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.

Or a React.Component instance:

const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");

Or a React.Component.prototype:

/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.

I've used and seen both methods. When I have a beforeEach() or beforeAll() block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.

EDIT: If you want to check the side effects of your myClickFn you can just invoke it in a separate test.

const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/

EDIT: Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn() as opposed to jest.spyOn, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.

function Component({ myClickFn, items }) {
   const handleClick = (id) => {
       return () => myClickFn(id);
   };
   return (<>
       {items.map(({id, name}) => (
           <div key={id} onClick={handleClick(id)}>{name}</div>
       ))}
   </>);
}

const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);

Android Fragments and animation

My modified support library supports using both View animations (i.e. <translate>, <rotate>) and Object Animators (i.e. <objectAnimator>) for Fragment Transitions. It is implemented with NineOldAndroids. Refer to my documentation on github for details.

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

Of the options you asked about:

  • float:left;
    I dislike floats because of the need to have additional markup to clear the float. As far as I'm concerned, the whole float concept was poorly designed in the CSS specs. Nothing we can do about that now though. But the important thing is it does work, and it works in all browsers (even IE6/7), so use it if you like it.

The additional markup for clearing may not be necessary if you use the :after selector to clear the floats, but this isn't an option if you want to support IE6 or IE7.

  • display:inline;
    This shouldn't be used for layout, with the exception of IE6/7, where display:inline; zoom:1 is a fall-back hack for the broken support for inline-block.

  • display:inline-block;
    This is my favourite option. It works well and consistently across all browsers, with a caveat for IE6/7, which support it for some elements. But see above for the hacky solution to work around this.

The other big caveat with inline-block is that because of the inline aspect, the white spaces between elements are treated the same as white spaces between words of text, so you can get gaps appearing between elements. There are work-arounds to this, but none of them are ideal. (the best is simply to not have any spaces between the elements)

  • display:table-cell;
    Another one where you'll have problems with browser compatibility. Older IEs won't work with this at all. But even for other browsers, it's worth noting that table-cell is designed to be used in a context of being inside elements that are styled as table and table-row; using table-cell in isolation is not the intended way to do it, so you may experience different browsers treating it differently.

Other techniques you may have missed? Yes.

  • Since you say this is for a multi-column layout, there is a CSS Columns feature that you might want to know about. However it isn't the most well supported feature (not supported by IE even in IE9, and a vendor prefix required by all other browsers), so you may not want to use it. But it is another option, and you did ask.

  • There's also CSS FlexBox feature, which is intended to allow you to have text flowing from box to box. It's an exciting feature that will allow some complex layouts, but this is still very much in development -- see http://html5please.com/#flexbox

Hope that helps.

posting hidden value

I'm not sure what you just did there, but from what I can tell this is what you're asking for:

bookingfacilities.php

<form action="successfulbooking.php" method="post">
    <input type="hidden" name="date" value="<?php echo $date; ?>">  
    <input type="submit" value="Submit Form">
</form>

successfulbooking.php

<?php
    $date = $_POST['date'];
    // add code here
?>

Not sure what you want to do with that third page(booking_now.php) too.

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

I too faced the same issue. I had installed Oracle Express edition 10g in Windows XP OS using VMware and it was working fine. Since it was very awkward typing SQL queries in the SQL utility provided by 10g and since I was used to working with SQL developer, I installed 32 bit SQL developer in XP and tried connecting to my DB SID "XE". But the connection failed with error-ORA-12505 TNS listener doesn't currently know of SID given in connect descriptor. I was at sea as to how this problem occurred since it was working fine with the SQL utility and I had also created few Informatica mappings using the same. I did browse a lot on this stuff hither thither and applied the suggestions offered to me after pinging the status of "lsnrctl" on public forums but to no avail. However, this morning I tried creating a new connection again, and Voila, it worked with no issues. I am guessing after reading in few posts that sometimes listener listens before the DB connects or something(pardon me for my crude reference as I am a newbie here) but I suggest to just restart the machine and check again.

Setting up a JavaScript variable from Spring model by using Thymeleaf

I've seen this kind of thing work in the wild:

<input type="button"  th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'" />

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

How to Pass Parameters to Activator.CreateInstance<T>()

public class AssemblyLoader<T>  where T:class
{
    public void(){
        var res = Load(@"C:\test\paquete.uno.dos.test.dll", "paquete.uno.dos.clasetest.dll") 
    }

    public T Load(string assemblyFile, string objectToInstantiate) 
    {
        var loaded = Activator.CreateInstanceFrom(assemblyFile, objectToInstantiate).Unwrap();

        return loaded as T;
    }
}

How do you get a directory listing in C?

The most similar method to readdir is probably using the little-known _find family of functions.

Finding local maxima/minima with Numpy in a 1D numpy array

None of these solutions worked for me since I wanted to find peaks in the center of repeating values as well. for example, in

ar = np.array([0,1,2,2,2,1,3,3,3,2,5,0])

the answer should be

array([ 3,  7, 10], dtype=int64)

I did this using a loop. I know it's not super clean, but it gets the job done.

def findLocalMaxima(ar):
# find local maxima of array, including centers of repeating elements    
maxInd = np.zeros_like(ar)
peakVar = -np.inf
i = -1
while i < len(ar)-1:
#for i in range(len(ar)):
    i += 1
    if peakVar < ar[i]:
        peakVar = ar[i]
        for j in range(i,len(ar)):
            if peakVar < ar[j]:
                break
            elif peakVar == ar[j]:
                continue
            elif peakVar > ar[j]:
                peakInd = i + np.floor(abs(i-j)/2)
                maxInd[peakInd.astype(int)] = 1
                i = j
                break
    peakVar = ar[i]
maxInd = np.where(maxInd)[0]
return maxInd 

How to check if object has been disposed in C#

The reliable solution is catching the ObjectDisposedException.

The solution to write your overridden implementation of the Dispose method doesn't work, since there is a race condition between the thread calling Dispose method and the one accessing to the object: after having checked the hypothetic IsDisposed property , the object could be really disposed, throwing the exception all the same.

Another approach could be exposing a hypothetic event Disposed (like this), which is used to notify about the disposing object to every object interested, but this could be difficoult to plan depending on the software design.

How do I clear this setInterval inside a function?

The setInterval method returns a handle that you can use to clear the interval. If you want the function to return it, you just return the result of the method call:

function intervalTrigger() {
  return window.setInterval( function() {
    if (timedCount >= markers.length) {
       timedCount = 0;
    }
    google.maps.event.trigger(markers[timedCount], "click");
    timedCount++;
  }, 5000 );
};
var id = intervalTrigger();

Then to clear the interval:

window.clearInterval(id);

What is the error "Every derived table must have its own alias" in MySQL?

Every derived table (AKA sub-query) must indeed have an alias. I.e. each query in brackets must be given an alias (AS whatever), which can the be used to refer to it in the rest of the outer query.

SELECT ID FROM (
    SELECT ID, msisdn FROM (
        SELECT * FROM TT2
    ) AS T
) AS T

In your case, of course, the entire query could be replaced with:

SELECT ID FROM TT2

Why does javascript replace only first instance when using replace?

You can use:

String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
    return this.toString();
}
return this.split(search).join(replace);
}

How can I use modulo operator (%) in JavaScript?

That would be the modulo operator, which produces the remainder of the division of two numbers.

What is the strict aliasing rule?

Strict aliasing is not allowing different pointer types to the same data.

This article should help you understand the issue in full detail.

What is the purpose of using WHERE 1=1 in SQL statements?

Using 1=1 is actually not a very good idea as this can cause full table scans by itself.

See this--> T-SQL 1=1 Performance Hit

Multiple FROMs - what it means

As of May 2017, multiple FROMs can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.

The general syntax involves adding FROM additional times within your Dockerfile - whichever is the last FROM statement is the final base image. To copy artifacts and outputs from intermediate images use COPY --from=<base_image_number>.

FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html  
COPY app.go    .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app    .
CMD ["./app"]  

The result would be two images, one for building, one with just the resulting app (much, much smaller)

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

multi               latest              bcbbf69a9b59        6 minutes ago       10.3MB  
golang              1.7.3               ef15416724f6        4 months ago        672MB  

what is a base image?

A set of files, plus EXPOSE'd ports, ENTRYPOINT and CMD.
You can add files and build a new image based on that base image, with a new Dockerfile starting with a FROM directive: the image mentioned after FROM is "the base image" for your new image.

does it mean that if I declare neo4j/neo4j in a FROM directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?

Only if you don't overwrite CMD and ENTRYPOINT.
But the image in itself is enough: you would use a FROM neo4j/neo4j if you had to add files related to neo4j for your particular usage of neo4j.

How to ignore a particular directory or file for tslint?

add the section in your code example

"linterOptions": {
"exclude": [
  "node_modules/**/*.",
  "db/**/*.",
  "integrations/**/*."
]

},

Batch program to to check if process exists

Try this:

@echo off
set run=
tasklist /fi "imagename eq notepad.exe" | find ":" > nul
if errorlevel 1 set run=yes
if "%run%"=="yes" echo notepad is running
if "%run%"=="" echo notepad is not running
pause

Javascript geocoding from address to latitude and longitude numbers not working

The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>

The address could be something like

1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)

or simply

1600 Amphitheatre Parkway, Mountain View, CA

By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.

{"results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Parkway",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Santa Clara County",
           "short_name" : "Santa Clara County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "94043",
           "short_name" : "94043",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4222556,
           "lng" : -122.0838589
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.4236045802915,
              "lng" : -122.0825099197085
           },
           "southwest" : {
              "lat" : 37.4209066197085,
              "lng" : -122.0852078802915
           }
        }
     },
     "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
     "types" : [ "street_address" ]
  }],"status" : "OK"}

Web Frameworks such like AngularJS allow us to perform these queries with ease.

JavaScript: Class.method vs. Class.prototype.method

Yes, the first function has no relationship with an object instance of that constructor function, you can consider it like a 'static method'.

In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.

The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new keyword, and the context within that function (the this keyword) will refer to the actual object instance where you call it.

Consider this example:

// constructor function
function MyClass () {
  var privateVariable; // private member only available within the constructor fn

  this.privilegedMethod = function () { // it can access private members
    //..
  };
}

// A 'static method', it's just like a normal function 
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};

MyClass.prototype.publicMethod = function () {
  // the 'this' keyword refers to the object instance
  // you can access only 'privileged' and 'public' members
};

var myObj = new MyClass(); // new object instance

myObj.publicMethod();
MyClass.staticMethod();

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

After hours of analysis reading tons of logs and sourcecode, finally found problem. And it is quite easy to solve it.

in sinle line: you need to pass --whitelisted-ips= into chrome driver (not chrome!) executables

You can do it in few ways:

If you use ChromeDriver locally/directly from code, just insert lines below before ChromeDriver init

    System.setProperty("webdriver.chrome.whitelistedIps", "");

If you use it remotely (eg. selenium hub/grid) you need to set system property when node starts, like in command:

java -Dwebdriver.chrome.whitelistedIps= testClass etc...

or docker by passing JAVA_OPTS env

  chrome:
    image: selenium/node-chrome:3.141.59
    container_name: chrome
    depends_on:
      - selenium-hub
    environment:
      - HUB_HOST=selenium-hub
      - HUB_PORT=4444
      - JAVA_OPTS=-Dwebdriver.chrome.whitelistedIps=

How to get the next auto-increment id in mysql

Use LAST_INSERT_ID() from your SQL query.

Or

You can also use mysql_insert_id() to get it using PHP.

How to increment a datetime by one day?

A short solution without libraries at all. :)

d = "8/16/18"
day_value = d[(d.find('/')+1):d.find('/18')]
tomorrow = f"{d[0:d.find('/')]}/{int(day_value)+1}{d[d.find('/18'):len(d)]}".format()
print(tomorrow)
# 8/17/18

Make sure that "string d" is actually in the form of %m/%d/%Y so that you won't have problems transitioning from one month to the next.

Converting Integer to String with comma for thousands

int bigNumber = 1234567;
String formattedNumber = String.format("%,d", bigNumber);

Where can I find the API KEY for Firebase Cloud Messaging?

You can find your Firebase Web API Key in the follwing way .

Go To project overview -> general -> web API key

Why does using an Underscore character in a LIKE filter give me all the results?

As you want to specifically search for a wildcard character you need to escape that

This is done by adding the ESCAPE clause to your LIKE expression. The character that is specified with the ESCAPE clause will "invalidate" the following wildcard character.

You can use any character you like (just not a wildcard character). Most people use a \ because that is what many programming languages also use

So your query would result in:

select * 
from Manager
where managerid LIKE '\_%' escape '\'
and managername like '%\_%' escape '\';

But you can just as well use any other character:

select * 
from Manager
where managerid LIKE '#_%' escape '#'
and managername like '%#_%' escape '#';

Here is an SQLFiddle example: http://sqlfiddle.com/#!6/63e88/4

How to redirect to another page using AngularJS?

You can use Angular $window:

$window.location.href = '/index.html';

Example usage in a contoller:

(function () {
    'use strict';

    angular
        .module('app')
        .controller('LoginCtrl', LoginCtrl);

    LoginCtrl.$inject = ['$window', 'loginSrv', 'notify'];

    function LoginCtrl($window, loginSrv, notify) {
        /* jshint validthis:true */
        var vm = this;
        vm.validateUser = function () {
             loginSrv.validateLogin(vm.username, vm.password).then(function (data) {          
                if (data.isValidUser) {    
                    $window.location.href = '/index.html';
                }
                else
                    alert('Login incorrect');
            });
        }
    }
})();

Can't install any packages in Node.js using "npm install"

npm set registry http://85.10.209.91/

(this proxy fetches the original data from registry.npmjs.org and manipulates the tarball urls to fix the tarball file structure issue).

The other solutions seem to have outdated versions.

Key existence check in HashMap

if(map.get(key) != null || (map.get(key) == null && map.containsKey(key)))

How to express a One-To-Many relationship in Django

If the "many" model does not justify the creation of a model per-se (not the case here, but it might benefits other people), another alternative would be to rely on specific PostgreSQL data types, via the Django Contrib package

Postgres can deal with Array or JSON data types, and this may be a nice workaround to handle One-To-Many when the many-ies can only be tied to a single entity of the one.

Postgres allows you to access single elements of the array, which means that queries can be really fast, and avoid application-level overheads. And of course, Django implements a cool API to leverage this feature.

It obviously has the disadvantage of not being portable to others database backend, but I thougt it still worth mentionning.

Hope it may help some people looking for ideas.

What's the bad magic number error?

The magic number comes from UNIX-type systems where the first few bytes of a file held a marker indicating the file type.

Python puts a similar marker into its pyc files when it creates them.

Then the python interpreter makes sure this number is correct when loading it.

Anything that damages this magic number will cause your problem. This includes editing the pyc file or trying to run a pyc from a different version of python (usually later) than your interpreter.

If they are your pyc files, just delete them and let the interpreter re-compile the py files. On UNIX type systems, that could be something as simple as:

rm *.pyc

or:

find . -name '*.pyc' -delete

If they are not yours, you'll have to either get the py files for re-compilation, or an interpreter that can run the pyc files with that particular magic value.

One thing that might be causing the intermittent nature. The pyc that's causing the problem may only be imported under certain conditions. It's highly unlikely it would import sometimes. You should check the actual full stack trace when the import fails?

As an aside, the first word of all my 2.5.1(r251:54863) pyc files is 62131, 2.6.1(r261:67517) is 62161. The list of all magic numbers can be found in Python/import.c, reproduced here for completeness (current as at the time the answer was posted, it may have changed since then):

1.5:   20121
1.5.1: 20121
1.5.2: 20121
1.6:   50428
2.0:   50823
2.0.1: 50823
2.1:   60202
2.1.1: 60202
2.1.2: 60202
2.2:   60717
2.3a0: 62011
2.3a0: 62021
2.3a0: 62011
2.4a0: 62041
2.4a3: 62051
2.4b1: 62061
2.5a0: 62071
2.5a0: 62081
2.5a0: 62091
2.5a0: 62092
2.5b3: 62101
2.5b3: 62111
2.5c1: 62121
2.5c2: 62131
2.6a0: 62151
2.6a1: 62161
2.7a0: 62171

Run certain code every n seconds

You can start a separate thread whose sole duty is to count for 5 seconds, update the file, repeat. You wouldn't want this separate thread to interfere with your main thread.

Jquery Date picker Default Date

Use the defaultDate option

$( ".selector" ).datepicker({ defaultDate: '01/01/01' });

If you change your date format, make sure to change the input into defaultDate (e.g. '01-01-2001')

How to hide form code from view code/inspect element browser?

You can use the following tag

<body oncontextmenu="return false"><!-- your page body hear--></body>

OR you can create your own menu when right click:

https://github.com/swisnl/jQuery-contextMenu

How to debug .htaccess RewriteRule not working

Perhaps a more logical method would be to create a file (e.g. test.html), add some content and then try to set it as the index page:

DirectoryIndex test.html

For the most part, the .htaccess rule will override the Apache configuration where working at the directory/file level

Check if enum exists in Java

Based on Jon Skeet answer i've made a class that permits to do it easily at work:

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import java.util.EnumSet;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * This permits to easily implement a failsafe implementation of the enums's valueOf
 * Better use it inside the enum so that only one of this object instance exist for each enum...
 * (a cache could solve this if needed)
 * </p>
 *
 * <p>
 * Basic usage exemple on an enum class called MyEnum:
 *
 *   private static final FailSafeValueOf<MyEnum> FAIL_SAFE = FailSafeValueOf.create(MyEnum.class);
 *   public static MyEnum failSafeValueOf(String enumName) {
 *       return FAIL_SAFE.valueOf(enumName);
 *   }
 *
 * </p>
 *
 * <p>
 * You can also use it outside of the enum this way:
 *   FailSafeValueOf.create(MyEnum.class).valueOf("EnumName");
 * </p>
 *
 * @author Sebastien Lorber <i>([email protected])</i>
 */
public class FailSafeValueOf<T extends Enum<T>> {

    private final Map<String,T> nameToEnumMap;

    private FailSafeValueOf(Class<T> enumClass) {
        Map<String,T> map = Maps.newHashMap();
        for ( T value : EnumSet.allOf(enumClass)) {
            map.put( value.name() , value);
        }
        nameToEnumMap = ImmutableMap.copyOf(map);
    }

    /**
     * Returns the value of the given enum element
     * If the 
     * @param enumName
     * @return
     */
    public T valueOf(String enumName) {
        return nameToEnumMap.get(enumName);
    }

    public static <U extends Enum<U>> FailSafeValueOf<U> create(Class<U> enumClass) {
        return new FailSafeValueOf<U>(enumClass);
    }

}

And the unit test:

import org.testng.annotations.Test;

import static org.testng.Assert.*;


/**
 * @author Sebastien Lorber <i>([email protected])</i>
 */
public class FailSafeValueOfTest {

    private enum MyEnum {
        TOTO,
        TATA,
        ;

        private static final FailSafeValueOf<MyEnum> FAIL_SAFE = FailSafeValueOf.create(MyEnum.class);
        public static MyEnum failSafeValueOf(String enumName) {
            return FAIL_SAFE.valueOf(enumName);
        }
    }

    @Test
    public void testInEnum() {
        assertNotNull( MyEnum.failSafeValueOf("TOTO") );
        assertNotNull( MyEnum.failSafeValueOf("TATA") );
        assertNull( MyEnum.failSafeValueOf("TITI") );
    }

    @Test
    public void testInApp() {
        assertNotNull( FailSafeValueOf.create(MyEnum.class).valueOf("TOTO") );
        assertNotNull( FailSafeValueOf.create(MyEnum.class).valueOf("TATA") );
        assertNull( FailSafeValueOf.create(MyEnum.class).valueOf("TITI") );
    }

}

Notice that i used Guava to make an ImmutableMap but actually you could use a normal map i think since the map is never returned...

How to get client IP address using jQuery

function GetUserIP(){
  var ret_ip;
  $.ajaxSetup({async: false});
  $.get('http://jsonip.com/', function(r){ 
    ret_ip = r.ip; 
  });
  return ret_ip;
}

If you want to use the IP and assign it to a variable, Try this. Just call GetUserIP()

Can someone give an example of cosine similarity, in a very simple, graphical way?

Here's a simple Python code to calculate cosine similarity:

import math

def dot_prod(v1, v2):
    ret = 0
    for i in range(len(v1)):
        ret += v1[i] * v2[i]
    return ret

def magnitude(v):
    ret = 0
    for i in v:
        ret += i**2
    return math.sqrt(ret)

def cos_sim(v1, v2):
    return (dot_prod(v1, v2)) / (magnitude(v1) * magnitude(v2))

How to parse JSON response from Alamofire API in Swift?

in swift 5 we do like, Use typealias for the completion. Typlealias nothing just use to clean the code.

typealias response = (Bool,Any?)->()


static func postCall(_ url : String, param : [String : Any],completion : @escaping response){
    Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in

        switch response.result {
           case .success(let JSON):
               print("\n\n Success value and JSON: \(JSON)")

           case .failure(let error):
               print("\n\n Request failed with error: \(error)")

           }
    }
}

How to 'insert if not exists' in MySQL?

There are several answers that cover how to solve this if you have a UNIQUE index that you can check against with ON DUPLICATE KEY or INSERT IGNORE. That is not always the case, and as UNIQUE has a length constraint (1000 bytes) you might not be able to change that. For example, I had to work with metadata in WordPress (wp_postmeta).

I finally solved it with two queries:

UPDATE wp_postmeta SET meta_value = ? WHERE meta_key = ? AND post_id = ?;
INSERT INTO wp_postmeta (post_id, meta_key, meta_value) SELECT DISTINCT ?, ?, ? FROM wp_postmeta WHERE NOT EXISTS(SELECT * FROM wp_postmeta WHERE meta_key = ? AND post_id = ?);

Query 1 is a regular UPDATE query with no effect when the dataset in question is not there. Query 2 is an INSERT which depends on a NOT EXISTS, i.e. the INSERT is only executed when the dataset doesn't exist.

How to printf "unsigned long" in C?

%lu is the correct format for unsigned long. Sounds like there are other issues at play here, such as memory corruption or an uninitialized variable. Perhaps show us a larger picture?

How to center a table of the screen (vertically and horizontally)

I think this should do the trick:

<table border="1px" align="center">

According to http://w3schools.com/tags/tag_table.asp this is deprecated, but try it. If it does not work, go for styles, as mentioned on the site.

Facebook Open Graph Error - Inferred Property

You need a space after the final set of quote marks

<meta property="og:url" content="http://www.mywebaddress.com"/>

Should be..likes this one

<meta property="og:url" content="http://www.mywebaddress.com" />

Running an executable in Mac Terminal

To run an executable in mac

1). Move to the path of the file:

cd/PATH_OF_THE_FILE

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

chmod +x ./NAME_OF_THE_FILE

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

./NAME_OF_THE_FILE

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

Multithreading in Bash

You can run several copies of your script in parallel, each copy for different input data, e.g. to process all *.cfg files on 4 cores:

    ls *.cfg | xargs -P 4 -n 1 read_cfg.sh

The read_cfg.sh script takes just one parameters (as enforced by -n)

A process crashed in windows .. Crash dump location

I have observed on Windows 2008 the Windows Error Reporting crash dumps get staged in the folder:

C:\Users\All Users\Microsoft\Windows\WER\ReportQueue

Which, starting with Windows Vista, is an alias for:

C:\ProgramData\Microsoft\Windows\WER\ReportQueue

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

In my case I had to include several additional exclusions. It appears it doesn't like Regular expressions which would've made this a nice one-liner.

android {
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/notice.txt'
    }
}

Android: How to turn screen on and off programmatically?

I wouldn't have hope of "waking the screen" in the activity. If the screen is off the activity is probably in a paused state and shouldn't be running any code.

When waking up, there is the issue of the lockscreen. I don't know how any app can automatically bypass the lockscreen.

You should consider running your background tasks in a service, and then using the notification manager to send a notification when whatever is detected. The notification should provide some sort of device alert (screen wake up, notification icon, notification led, etc). When clicking the notification it can launch the intent to start your activity.

You could also attempt to start the activity direct from the service, but I really don't know if that will turn the screen on or bypass the lockscreen.

What is LD_LIBRARY_PATH and how to use it?

Well, the error message tells you what to do: add the path where Jacob.dll resides to java.library.path. You can do that on the command line like this:

java -Djava.library.path="dlls" ...

(assuming Jacob.dll is in the "dlls" folder)

Also see java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

Another awk variant:

#!/usr/bin/awk -f
# usage:
# awk -f randomize_lines.awk lines.txt
# usage after "chmod +x randomize_lines.awk":
# randomize_lines.awk lines.txt

BEGIN {
  FS = "\n";
  srand();
}

{
  lines[ rand()] = $0;
}

END {
  for( k in lines ){
    print lines[k];
  }
}

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

Actually, the correct solution is:

composer require vendor/package

Taken from the CLI documentation for Composer:

The require command adds new packages to the composer.json file from the current directory.

php composer.phar require

After adding/changing the requirements, the modified requirements will be installed or updated.

If you do not want to choose requirements interactively, you can just pass them to the command.

php composer.phar require vendor/package:2.* vendor/package2:dev-master

While it is true that composer update installs new packages found in composer.json, it will also update the composer.lock file and any installed packages according to any fuzzy logic (> or * chars after the colons) found in composer.json! This can be avoided by using composer update vendor/package, but I wouldn't recommend making a habit of it, as you're one forgotten argument away from a potentially broken project…

Keep things sane and stick with composer require vendor/package for adding new dependencies!

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

The usage of the Hardware acceleration depends on the System Image you choose on the emulator.

So,

  1. Go to AVD manager, create virtual device, select hardware, click next.

  2. Choose the System Image that does not require HAXM (hardware acceleration) for running. (That is appears at the right bottom of System image window.)

Note: for other systems that require HAXM, there no way to run them without hardware acceleration.

How to unstage large number of files without deleting the content

Use git reset HEAD to reset the index without removing files. (If you only want to reset a particular file in the index, you can use git reset HEAD -- /path/to/file to do so.)

The pipe operator, in a shell, takes the stdout of the process on the left and passes it as stdin to the process on the right. It's essentially the equivalent of:

$ proc1 > proc1.out
$ proc2 < proc1.out
$ rm proc1.out

but instead it's $ proc1 | proc2, the second process can start getting data before the first is done outputting it, and there's no actual file involved.

Unable to convert MySQL date/time value to System.DateTime

In a Stimulsoft report add this parameter to the connection string (right click on datasource->edit)

Convert Zero Datetime=True;

HTML - how can I show tooltip ONLY when ellipsis is activated

Here are two other pure CSS solutions:

  1. Show the truncated text in place:

_x000D_
_x000D_
.overflow {_x000D_
  overflow: hidden;_x000D_
  -ms-text-overflow: ellipsis;_x000D_
  text-overflow: ellipsis;_x000D_
  white-space: nowrap;_x000D_
}_x000D_
_x000D_
.overflow:hover {_x000D_
  overflow: visible;_x000D_
}_x000D_
_x000D_
.overflow:hover span {_x000D_
  position: relative;_x000D_
  background-color: white;_x000D_
_x000D_
  box-shadow: 0 0 4px 0 black;_x000D_
  border-radius: 1px;_x000D_
}
_x000D_
<div>_x000D_
  <span class="overflow" style="float: left; width: 50px">_x000D_
    <span>Long text that might overflow.</span>_x000D_
  </span>_x000D_
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad recusandae perspiciatis accusantium quas aut explicabo ab. Doloremque quam eos, alias dolore, iusto pariatur earum, ullam, quidem dolores deleniti perspiciatis omnis._x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. Show an arbitrary "tooltip":

_x000D_
_x000D_
.wrap {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.overflow {_x000D_
  white-space: nowrap; _x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  _x000D_
  pointer-events:none;_x000D_
}_x000D_
_x000D_
.overflow:after {_x000D_
  content:"";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  width: 20px;_x000D_
  height: 15px;_x000D_
  z-index: 1;_x000D_
  border: 1px solid red; /* for visualization only */_x000D_
  pointer-events:initial;_x000D_
_x000D_
}_x000D_
_x000D_
.overflow:hover:after{_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.tooltip {_x000D_
  /* visibility: hidden; */_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 10;_x000D_
  left: 0;_x000D_
  background-color: #fff;_x000D_
  padding: 10px;_x000D_
  -webkit-box-shadow: 0 0 50px 0 rgba(0,0,0,0.3);_x000D_
  opacity: 0;_x000D_
  transition: opacity 0.5s ease;_x000D_
}_x000D_
_x000D_
_x000D_
.overflow:hover + .tooltip {_x000D_
  /*visibility: visible; */_x000D_
  display: initial;_x000D_
  transition: opacity 0.5s ease;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div>_x000D_
  <span class="wrap">_x000D_
    <span class="overflow" style="float: left; width: 50px">Long text that might overflow</span>_x000D_
    <span class='tooltip'>Long text that might overflow.</span>_x000D_
  </span>_x000D_
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad recusandae perspiciatis accusantium quas aut explicabo ab. Doloremque quam eos, alias dolore, iusto pariatur earum, ullam, quidem dolores deleniti perspiciatis omnis._x000D_
</div>
_x000D_
_x000D_
_x000D_

how to set background image in submit button?

The way I usually do it, is with the following css:

div#submitForm input {
  background: url("../images/buttonbg.png") no-repeat scroll 0 0 transparent;
  color: #000000;
  cursor: pointer;
  font-weight: bold;
  height: 20px;
  padding-bottom: 2px;
  width: 75px;
}

and the markup:

<div id="submitForm">
    <input type="submit" value="Submit" name="submit">
</div>

If things look different in the various browsers I implore you to use a reset style sheet which sets all margins, padding and maybe even borders to zero.

How do you explicitly set a new property on `window` in TypeScript?

After finding answers around, I think this page might be helpful. https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation Not sure about the history of declaration merging, but it explains why the following could work.

declare global {
    interface Window { MyNamespace: any; }
}

window.MyNamespace = window.MyNamespace || {};

Discard all and get clean copy of latest revision?

Those steps should be able to be shortened down to:

hg pull
hg update -r MY_BRANCH -C

The -C flag tells the update command to discard all local changes before updating.

However, this might still leave untracked files in your repository. It sounds like you want to get rid of those as well, so I would use the purge extension for that:

hg pull
hg update -r MY_BRANCH -C
hg purge

In any case, there is no single one command you can ask Mercurial to perform that will do everything you want here, except if you change the process to that "full clone" method that you say you can't do.

Change a column type from Date to DateTime during ROR migration

There's a change_column method, just execute it in your migration with datetime as a new type.

change_column(:my_table, :my_column, :my_new_type)

How to get all the values of input array element jquery

Use:

function getvalues(){
var inps = document.getElementsByName('pname[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
    alert("pname["+i+"].value="+inp.value);
}
}

Here is Demo.

CASE WHEN statement for ORDER BY clause

CASE is an expression - it returns a single scalar value (per row). It can't return a complex part of the parse tree of something else, like an ORDER BY clause of a SELECT statement.

It looks like you just need:

ORDER BY 
CASE WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount END desc,
CASE WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount END desc, 
Case WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount END DESC,
CASE WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount END DESC,
Case WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount END DESC,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC

Or possibly:

ORDER BY 
CASE
   WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
   WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
   WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
   WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
   WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC

It's a little tricky to tell which of the above (or something else) is what you're looking for because you've a) not explained what actual sort order you're trying to achieve, and b) not supplied any sample data and expected results, from which we could attempt to deduce the actual sort order you're trying to achieve.


This may be the answer we're looking for:

ORDER BY 
CASE
   WHEN TblList.PinRequestCount <> 0 THEN 5
   WHEN TblList.HighCallAlertCount <> 0 THEN 4
   WHEN TblList.HighAlertCount <> 0 THEN 3
   WHEN TblList.MediumCallAlertCount <> 0 THEN 2
   WHEN TblList.MediumAlertCount <> 0 THEN 1
END desc,
CASE
   WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
   WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
   WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
   WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
   WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC

Property 'value' does not exist on type 'Readonly<{}>'

I suggest to use

for string only state values

export default class Home extends React.Component<{}, { [key: string]: string }> { }

for string key and any type of state values

export default class Home extends React.Component<{}, { [key: string]: any}> { }

for any key / any values

export default class Home extends React.Component<{}, { [key: any]: any}> {}

REST API Authentication

You can use HTTP Basic or Digest Authentication. You can securely authenticate users using SSL on the top of it, however, it slows down the API a little bit.

  • Basic authentication - uses Base64 encoding on username and password
  • Digest authentication - hashes the username and password before sending them over the network.

OAuth is the best it can get. The advantages oAuth gives is a revokable or expirable token. Refer following on how to implement: Working Link from comments: https://www.ida.liu.se/~TDP024/labs/hmacarticle.pdf

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

To resolve this problem you first need to check the SSL certificates of the host your are connecting to. For example using ssllabs or other ssl tools. In my case the intermediate certificate was wrong.

If the certificate is ok, make sure the openSSL on your server is up to date. Run openssl -v to check your version. Maybe your version is to old to work with the certificate.

In very rare cases you might want to disable ssl security features like verify_peer, verify_peer_name or allow_self_signed. Please be very careful with this and never use this in production. This is only an option for temporary testing.

How to get the last day of the month?

The easiest way (without having to import calendar), is to get the first day of the next month, and then subtract a day from it.

import datetime as dt
from dateutil.relativedelta import relativedelta

thisDate = dt.datetime(2017, 11, 17)

last_day_of_the_month = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)
print last_day_of_the_month

Output:

datetime.datetime(2017, 11, 30, 0, 0)

PS: This code runs faster as compared to the import calendarapproach; see below:

import datetime as dt
import calendar
from dateutil.relativedelta import relativedelta

someDates = [dt.datetime.today() - dt.timedelta(days=x) for x in range(0, 10000)]

start1 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)

print ('Time Spent= ', dt.datetime.now() - start1)


start2 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year, 
                          thisDate.month, 
                          calendar.monthrange(thisDate.year, thisDate.month)[1])

print ('Time Spent= ', dt.datetime.now() - start2)

OUTPUT:

Time Spent=  0:00:00.097814
Time Spent=  0:00:00.109791

This code assumes that you want the date of the last day of the month (i.e., not just the DD part, but the entire YYYYMMDD date)

How to delete stuff printed to console by System.out.println()?

There are two different ways to clear the terminal in BlueJ. You can get BlueJ to automatically clear the terminal before every interactive method call. To do this, activate the 'Clear screen at method call' option in the 'Options' menu of the terminal. You can also clear the terminal programmatically from within your program. Printing a formfeed character (Unicode 000C) clears the BlueJ terminal, for example:

System.out.print('\u000C');

In oracle, how do I change my session to display UTF8?

Therefore, before starting '$ sqlplus' on OS, run the followings:

  • On Windows

    set NLS_LANG=AMERICAN_AMERICA.UTF8

  • On Unix (Solaris and Linux, centos etc)

    export NLS_LANG=AMERICAN_AMERICA.UTF8

It would also be advisable to set env variable in your '.bash_profile' [on start up script]

This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.

just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.

What is the maximum number of characters that nvarchar(MAX) will hold?

Max. capacity is 2 gigabytes of space - so you're looking at just over 1 billion 2-byte characters that will fit into a NVARCHAR(MAX) field.

Using the other answer's more detailed numbers, you should be able to store

(2 ^ 31 - 1 - 2) / 2 = 1'073'741'822 double-byte characters

1 billion, 73 million, 741 thousand and 822 characters to be precise

in your NVARCHAR(MAX) column (unfortunately, that last half character is wasted...)

Update: as @MartinMulder pointed out: any variable length character column also has a 2 byte overhead for storing the actual length - so I needed to subtract two more bytes from the 2 ^ 31 - 1 length I had previously stipulated - thus you can store 1 Unicode character less than I had claimed before.

Add class to <html> with Javascript?

You should append class not overwrite it

var headCSS = document.getElementsByTagName("html")[0].getAttribute("class") || "";
document.getElementsByTagName("html")[0].setAttribute("class",headCSS +"foo");

I would still recommend using jQuery to avoid browser incompatibilities

SVN 405 Method Not Allowed

I also met this problem just now and solved it in this way. So I recorded it here, and I wish it be useful for others.

Scenario:

  1. Before I commit the code, revision: 100
  2. (Someone else commits the code... revision increased to 199)
  3. I (forgot to run "svn up", ) commit the code, now my revision: 200
  4. I run "svn up".

The error occurred.

Solution:

  1. $ mv current_copy copy_back # Rename the current code copy
  2. $ svn checkout current_copy # Check it out again
  3. $ cp copy_back/ current_copy # Restore your modifications

How can I make Bootstrap columns all the same height?

here is my solution (compiled CSS):

.row.row-xs-eq {
  display: table;
  table-layout: fixed;
  margin: 0;
}

.row.row-xs-eq::before {
  content: none;
}

.row.row-xs-eq::after {
  content: none;
}

.row.row-xs-eq > [class^='col-'] {
  display: table-cell;
  float: none;
  padding: 0;
}

@media (min-width: 768px) {
  .row.row-sm-eq {
    display: table;
    table-layout: fixed;
    margin: 0;
  }

  .row.row-sm-eq::before {
    content: none;
  }

  .row.row-sm-eq::after {
    content: none;
  }

  .row.row-sm-eq > [class^='col-'] {
    display: table-cell;
    float: none;
    padding: 0;
  }
}

@media (min-width: 992px) {
  .row.row-md-eq {
    display: table;
    table-layout: fixed;
    margin: 0;
  }

  .row.row-md-eq::before {
    content: none;
  }

  .row.row-md-eq::after {
    content: none;
  }

  .row.row-md-eq > [class^='col-'] {
    display: table-cell;
    float: none;
    padding: 0;
  }
}

@media (min-width: 1200px) {
  .row.row-lg-eq {
    display: table;
    table-layout: fixed;
    margin: 0;
  }

  .row.row-lg-eq::before {
    content: none;
  }

  .row.row-lg-eq::after {
    content: none;
  }

  .row.row-lg-eq > [class^='col-'] {
    display: table-cell;
    float: none;
    padding: 0;
  }
}

So your code would look like:

<div class="row row-sm-eq">
  <!-- your old cols definition here -->
</div>

Basically this is the same system you use with .col-* classes with that difference you need to apply .row-* classes to the row itself.

With .row-sm-eq columns will be stacked on XS screens. If you don't need them to be stacked on any screens you can use .row-xs-eq.

The SASS version that we do actually use:

.row {
  @mixin row-eq-height {
    display: table;
    table-layout: fixed;
    margin: 0;

    &::before {
      content: none;
    }

    &::after {
      content: none;
    }

    > [class^='col-'] {
      display: table-cell;
      float: none;
      padding: 0;
    }
  }

  &.row-xs-eq {
    @include row-eq-height;
  }

  @media (min-width: $screen-sm-min) {
    &.row-sm-eq {
      @include row-eq-height;
    }
  }

  @media (min-width: $screen-md-min) {
    &.row-md-eq {
      @include row-eq-height;
    }
  }

  @media (min-width: $screen-lg-min) {
    &.row-lg-eq {
      @include row-eq-height;
    }
  }
}

Live demo


Note: mixing .col-xs-12 and .col-xs-6 inside a single row would not work properly.

Threads vs Processes in Linux

I think everyone has done a great job responding to your question. I'm just adding more information about thread versus process in Linux to clarify and summarize some of the previous responses in context of kernel. So, my response is in regarding to kernel specific code in Linux. According to Linux Kernel documentation, there is no clear distinction between thread versus process except thread uses shared virtual address space unlike process. Also note, the Linux Kernel uses the term "task" to refer to process and thread in general.

"There are no internal structures implementing processes or threads, instead there is a struct task_struct that describe an abstract scheduling unit called task"

Also according to Linus Torvalds, you should NOT think about process versus thread at all and because it's too limiting and the only difference is COE or Context of Execution in terms of "separate the address space from the parent " or shared address space. In fact he uses a web server example to make his point here (which highly recommend reading).

Full credit to linux kernel documentation

How can I get the class name from a C++ object?

Just write simple template:

template<typename T>
const char* getClassName(T) {
  return typeid(T).name();
}

struct A {} a;

void main() {
   std::cout << getClassName(a);
}

How do I remove all .pyc files from a project?

In current version of debian you have pyclean script which is in python-minimal package.

Usage is simple:

pyclean .

Could not find server 'server name' in sys.servers. SQL Server 2014

At first check out that your linked server is in the list by this query

select name from sys.servers

If it not exists then try to add to the linked server

EXEC sp_addlinkedserver @server = 'SERVER_NAME' --or may be server ip address

After that login to that linked server by

EXEC sp_addlinkedsrvlogin 'SERVER_NAME'
                         ,'false'
                         ,NULL
                         ,'USER_NAME'
                         ,'PASSWORD'

Then you can do whatever you want ,treat it like your local server

exec [SERVER_NAME].[DATABASE_NAME].dbo.SP_NAME @sample_parameter

Finally you can drop that server from linked server list by

sp_dropserver 'SERVER_NAME', 'droplogins'

If it will help you then please upvote.

How do I set bold and italic on UILabel of iPhone/iPad?

sectionLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:18];

There is a list of font names that you can set in place of 'fontWithName' attribute.The link is here

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

For me, it was an inconsistency between Debug profile (it was automatic) and Release profile (it was manual). Setting them both automatic/manual resolved the issue.

Type datetime for input parameter in procedure

You should use the ISO-8601 format for string representations of dates - anything else is dependent on the SQL Server language and dateformat settings.

The ISO-8601 format for a DATETIME when using only the date is: YYYYMMDD (no dashes or antyhing!)

For a DATETIME with the time portion, it's YYYY-MM-DDTHH:MM:SS (with dashes, and a T in the middle to separate date and time portions).

If you want to convert a string to a DATE for SQL Server 2008 or newer, you can use YYYY-MM-DD (with the dashes) to achieve the same result. And don't ask me why this is so inconsistent and confusing - it just is, and you'll have to work with that for now.

So in your case, you should try:

declare @a datetime
declare @b datetime 

set @a = '2012-04-06T12:23:45'   -- 6th of April, 2012
set @b = '2012-08-06T21:10:12'   -- 6th of August, 2012

exec LogProcedure 'AccountLog', N'test', @a, @b

Furthermore - your stored proc has problem, since you're concatenating together datetime and string into a string, but you're not converting the datetime to string first, and also, you're forgetting the close quotes in your statement after both dates.

So change this line here to this:

IF @DateFirst <> '' and @DateLast <> ''
   SET @FinalSQL  = @FinalSQL + '  OR CONVERT(Date, DateLog) >= ''' + 
                    CONVERT(VARCHAR(50), @DateFirst, 126) +   -- convert @DateFirst to string for concatenation!
                    ''' AND CONVERT(Date, DateLog) <=''' +  -- you need closing quotes after @DateFirst!
                    CONVERT(VARCHAR(50), @DateLast, 126) + ''''      -- convert @DateLast to string and also: closing tags after that missing!

With these settings, and once you've fixed your stored procedure which contains problems right now, it will work.

How to model type-safe enum types?

There are many ways of doing.

1) Use symbols. It won't give you any type safety, though, aside from not accepting non-symbols where a symbol is expected. I'm only mentioning it here for completeness. Here's an example of usage:

def update(what: Symbol, where: Int, newValue: Array[Int]): MatrixInt =
  what match {
    case 'row => replaceRow(where, newValue)
    case 'col | 'column => replaceCol(where, newValue)
    case _ => throw new IllegalArgumentException
  }

// At REPL:   
scala> val a = unitMatrixInt(3)
a: teste7.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 0 1 /

scala> a('row, 1) = a.row(0)
res41: teste7.MatrixInt =
/ 1 0 0 \
| 1 0 0 |
\ 0 0 1 /

scala> a('column, 2) = a.row(0)
res42: teste7.MatrixInt =
/ 1 0 1 \
| 0 1 0 |
\ 0 0 0 /

2) Using class Enumeration:

object Dimension extends Enumeration {
  type Dimension = Value
  val Row, Column = Value
}

or, if you need to serialize or display it:

object Dimension extends Enumeration("Row", "Column") {
  type Dimension = Value
  val Row, Column = Value
}

This can be used like this:

def update(what: Dimension, where: Int, newValue: Array[Int]): MatrixInt =
  what match {
    case Row => replaceRow(where, newValue)
    case Column => replaceCol(where, newValue)
  }

// At REPL:
scala> a(Row, 2) = a.row(1)
<console>:13: error: not found: value Row
       a(Row, 2) = a.row(1)
         ^

scala> a(Dimension.Row, 2) = a.row(1)
res1: teste.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 1 0 /

scala> import Dimension._
import Dimension._

scala> a(Row, 2) = a.row(1)
res2: teste.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 1 0 /

Unfortunately, it doesn't ensure that all matches are accounted for. If I forgot to put Row or Column in the match, the Scala compiler wouldn't have warned me. So it gives me some type safety, but not as much as can be gained.

3) Case objects:

sealed abstract class Dimension
case object Row extends Dimension
case object Column extends Dimension

Now, if I leave out a case on a match, the compiler will warn me:

MatrixInt.scala:70: warning: match is not exhaustive!
missing combination         Column

    what match {
    ^
one warning found

It's used pretty much the same way, and doesn't even need an import:

scala> val a = unitMatrixInt(3)
a: teste3.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 0 1 /

scala> a(Row,2) = a.row(0)
res15: teste3.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 1 0 0 /

You might wonder, then, why ever use an Enumeration instead of case objects. As a matter of fact, case objects do have advantages many times, such as here. The Enumeration class, though, has many Collection methods, such as elements (iterator on Scala 2.8), which returns an Iterator, map, flatMap, filter, etc.

This answer is essentially a selected parts from this article in my blog.

Insert an item into sorted list in Python

# function to insert a number in an sorted list


def pstatement(value_returned):
    return print('new sorted list =', value_returned)


def insert(input, n):
    print('input list = ', input)
    print('number to insert = ', n)
    print('range to iterate is =', len(input))

    first = input[0]
    print('first element =', first)
    last = input[-1]
    print('last element =', last)

    if first > n:
        list = [n] + input[:]
        return pstatement(list)
    elif last < n:
        list = input[:] + [n]
        return pstatement(list)
    else:
        for i in range(len(input)):
            if input[i] > n:
                break
    list = input[:i] + [n] + input[i:]
    return pstatement(list)

# Input values
listq = [2, 4, 5]
n = 1

insert(listq, n)

Using "&times" word in html changes to ×

Use the &#215 code instead of &times Because JSF don't understand the &times; code.

Use: &#215 with ;

This link provides some additional information about the topic.

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

What is the python keyword "with" used for?

Explanation from the Preshing on Programming blog:

It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

 with open('output.txt', 'w') as f:
     f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

jQuery - Create hidden form element on the fly

$('#myformelement').append('<input type="hidden" name="myfieldname" value="myvalue" />');

Div Background Image Z-Index Issue

For z-index to work, you also need to give it a position:

header {
    width: 100%;
    height: 100px;
    background: url(../img/top.png) repeat-x;
    z-index: 110;
    position: relative;
}

Convert from List into IEnumerable format

As far as I know List<T> implements IEnumerable<T>. It means that you do not have to convert or cast anything.

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

Java 8 stream map to list of keys sorted by values

You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort.

And you want to get the keys; use map to transform entries to keys.

List<Type> types = countByType.entrySet().stream()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

How to check if command line tools is installed

To check if command line tools are installed run:

xcode-select --version

// if installed you will see the below with the version found in your system
// xcode-select version 1234.

If command line tools are not installed run:

xcode-select --install

Excel VBA: AutoFill Multiple Cells with Formulas

Based on my Comment here is one way to get what you want done:

Start byt selecting any cell in your range and Press Ctrl + T

This will give you this pop up:

enter image description here

make sure the Where is your table text is correct and click ok you will now have:

enter image description here

Now If you add a column header in D it will automatically be added to the table all the way to the last row:

enter image description here

Now If you enter a formula into this column:

enter image description here

After you enter it, the formula will be auto filled all the way to last row:

enter image description here

Now if you add a new row at the next row under your table:

enter image description here

Once entered it will be resized to the width of your table and all columns with formulas will be added also:

enter image description here

Hope this solves your problem!

Writing a pandas DataFrame to CSV file

it could be not the answer for this case, but as I had the same error-message with .to_csvI tried .toCSV('name.csv') and the error-message was different ("SparseDataFrame' object has no attribute 'toCSV'). So the problem was solved by turning dataframe to dense dataframe

df.to_dense().to_csv("submission.csv", index = False, sep=',', encoding='utf-8')

Location of sqlite database on the device

You can also check whether your IDE has a utility like Eclipse's DDMS perspective which allows you to browse through the directory and/or copy files to and from the Emulator or a rooted device.

ActiveX component can't create object

It really looks as though the object you are referencing is not registered on the system. I know you said it's installed, but that doesn't necessarily mean it's registered. To confirm this, search for the progID that you used in your registry.

Example for this code:

set objFSO = CreateObject("Scripting.FileSystemObject") 

I would search for Scripting.FileSystemObject in the registry. Then I would look at registry key above the found value, for InProcServer32 value. This will give you the path to the ActiveX file that it was registered from (for Scripting.FileSystemObject the file is "c:\windows\system32\scrrun.dll").

If you can't find your progID in the registry, then it's not registered on your system which is your problem. If it's not registered you need to find out what file registers it, which is usually an .ocx or a .dll in the same folder path of your third party app, and then register these file(s). Here is the command to register a file:

regsvr32 /i "c:\windows\system32\scrrun.dll"

Even if you find the progID value in the registry and it references a file that is present on your system, you may still want to try re-registering the file. I have found that sometimes the registration got broken somehow somewhere and it was easier to re-register the files then it was to fix the issue.

Service located in another namespace

You can achieve this by deploying something at a higher layer than namespaced Services, like the service loadbalancer https://github.com/kubernetes/contrib/tree/master/service-loadbalancer. If you want to restrict it to a single namespace, use "--namespace=ns" argument (it defaults to all namespaces: https://github.com/kubernetes/contrib/blob/master/service-loadbalancer/service_loadbalancer.go#L715). This works well for L7, but is a little messy for L4.

How to update MySql timestamp column to current timestamp on PHP?

Another option:

UPDATE `table` SET the_col = current_timestamp

Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now().

Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

By default, oracle date subtraction returns a result in # of days.

So just multiply by 24 to get # of hours, and again by 60 for # of minutes.

Example:

select
  round((second_date - first_date) * (60 * 24),2) as time_in_minutes
from
  (
  select
    to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
   ,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
  from
    dual
  ) test_data

Fuzzy matching using T-SQL

Regarding de-duping things your string split and match is great first cut. If there are known items about the data that can be leveraged to reduce workload and/or produce better results, it is always good to take advantage of them. Bear in mind that often for de-duping it is impossible to entirely eliminate manual work, although you can make that much easier by catching as much as you can automatically and then generating reports of your "uncertainty cases."

Regarding name matching: SOUNDEX is horrible for quality of matching and especially bad for the type of work you are trying to do as it will match things that are too far from the target. It's better to use a combination of double metaphone results and the Levenshtein distance to perform name matching. With appropriate biasing this works really well and could probably be used for a second pass after doing a cleanup on your knowns.

You may also want to consider using an SSIS package and looking into Fuzzy Lookup and Grouping transformations (http://msdn.microsoft.com/en-us/library/ms345128(SQL.90).aspx).

Using SQL Full-Text Search (http://msdn.microsoft.com/en-us/library/cc879300.aspx) is a possibility as well, but is likely not appropriate to your specific problem domain.

Margin on child element moves parent element

add style display:inline-block to child element

Using Excel as front end to Access database (with VBA)

Given the ease of use of Access, I don't see a compelling reason to use Excel at all other than to export data for number crunching. Access is designed to easily build data forms and, in my opinion, will be orders of magnitude easier and less time-consuming than using Excel. A few hours to learn the Access object model will pay for itself many times over in terms of time and effort.

Django DB Settings 'Improperly Configured' Error

In my case, I got this when trying to run Django tests through PyCharm. I think it is because PyCharm does not load the initial Django project settings, i.e. those that manage.py shell runs initially. One can add them to the start of the testing script or just run the tests using manage.py test.

Versions:

  • Python 3.5 (in virtualenv)
  • PyCharm 2016.3.2 Professional
  • Django 1.10

splitting a string into an array in C++ without using vector

It is possible to turn the string into a stream by using the std::stringstream class (its constructor takes a string as parameter). Once it's built, you can use the >> operator on it (like on regular file based streams), which will extract, or tokenize word from it:

#include <iostream>
#include <sstream>

using namespace std;

int main(){
    string line = "test one two three.";
    string arr[4];
    int i = 0;
    stringstream ssin(line);
    while (ssin.good() && i < 4){
        ssin >> arr[i];
        ++i;
    }
    for(i = 0; i < 4; i++){
        cout << arr[i] << endl;
    }
}

How can I present a file for download from an MVC controller?

mgnoonan,

You can do this to return a FileStream:

/// <summary>
/// Creates a new Excel spreadsheet based on a template using the NPOI library.
/// The template is changed in memory and a copy of it is sent to
/// the user computer through a file stream.
/// </summary>
/// <returns>Excel report</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult NPOICreate()
{
    try
    {
        // Opening the Excel template...
        FileStream fs =
            new FileStream(Server.MapPath(@"\Content\NPOITemplate.xls"), FileMode.Open, FileAccess.Read);

        // Getting the complete workbook...
        HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);

        // Getting the worksheet by its name...
        HSSFSheet sheet = templateWorkbook.GetSheet("Sheet1");

        // Getting the row... 0 is the first row.
        HSSFRow dataRow = sheet.GetRow(4);

        // Setting the value 77 at row 5 column 1
        dataRow.GetCell(0).SetCellValue(77);

        // Forcing formula recalculation...
        sheet.ForceFormulaRecalculation = true;

        MemoryStream ms = new MemoryStream();

        // Writing the workbook content to the FileStream...
        templateWorkbook.Write(ms);

        TempData["Message"] = "Excel report created successfully!";

        // Sending the server processed data back to the user computer...
        return File(ms.ToArray(), "application/vnd.ms-excel", "NPOINewFile.xls");
    }
    catch(Exception ex)
    {
        TempData["Message"] = "Oops! Something went wrong.";

        return RedirectToAction("NPOI");
    }
}

Authentication plugin 'caching_sha2_password' is not supported

pip3 install mysql-connector-python did solve my problem as well. Ignore using mysql-connector module.

Read file from line 2 or skip header row

If you want the first line and then you want to perform some operation on file this code will helpful.

with open(filename , 'r') as f:
    first_line = f.readline()
    for line in f:
            # Perform some operations

/etc/apt/sources.list" E212: Can't open file for writing

I referenced to Zsolt in level 2, I input:

:w !sudo tee % > /dev/null

and then in my situation, I still can't modify the file, so it prompted that add "!". so I input

:q! 

then it works

How to use MD5 in javascript to transmit a password

If someone is sniffing your plain-text HTTP traffic (or cache/cookies) for passwords just turning the password into a hash won't help - The hash password can be "replayed" just as well as plain-text. The client would need to hash the password with something somewhat random (like the date and time) See the section on "AUTH CRAM-MD5" here: http://www.fehcom.de/qmail/smtpauth.html

enum Values to NSString (iOS)

In some cases when you need to convert enum -> NSString and NSString -> enum it might be simpler to use a typedef and #define (or const NSStrings) instead of enum:

typedef NSString *        ImageType;
#define ImageTypeJpg      @"JPG"
#define ImageTypePng      @"PNG"
#define ImageTypeGif      @"GIF"

and then just operate with "named" strings as with any other NSString:

@interface MyData : NSObject
@property (copy, nonatomic) ImageType imageType;
@end

@implementation MyData
- (void)doSomething {
    //...
    self.imageType = ImageTypePng;
    //...
    if ([self.imageType isEqualToString:ImageTypeJpg]) {
        //...
    }
}
@end

Release generating .pdb files, why?

PDB can be generated for Release as well as for Debug. This is set at (in VS2010 but in VS2005 must be similar):

Project ? Properties ? Build ? Advanced ? Debug Info

Just change it to None.

Access denied for user 'test'@'localhost' (using password: YES) except root user

For annoying searching getting here after searching for this error message:

Access denied for user 'someuser@somewhere' (using password: YES)

The issue for me was not enclosing the password in quotes. eg. I needed to use -p'password' instead of -ppassword

Simple line plots using seaborn

It's possible to get this done using seaborn.lineplot() but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:

# imports
import seaborn as sns
import numpy as np
import pandas as pd

# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])

# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)

# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>

And we get the following plot:

square plot

Export data from Chrome developer tool

In Chrome, in the Developer Tools, under Network, in the Name column, right-click and select "Save as HAR with content". Then open a new tab, go to https://toolbox.googleapps.com/apps/har_analyzer/ and open the saved HAR file.

How can I replace non-printable Unicode characters in Java?

I have redesigned the code for phone numbers +9 (987) 124124 Extract digits from a string in Java

 public static String stripNonDigitsV2( CharSequence input ) {
    if (input == null)
        return null;
    if ( input.length() == 0 )
        return "";

    char[] result = new char[input.length()];
    int cursor = 0;
    CharBuffer buffer = CharBuffer.wrap( input );
    int i=0;
    while ( i< buffer.length()  ) { //buffer.hasRemaining()
        char chr = buffer.get(i);
        if (chr=='u'){
            i=i+5;
            chr=buffer.get(i);
        }

        if ( chr > 39 && chr < 58 )
            result[cursor++] = chr;
        i=i+1;
    }

    return new String( result, 0, cursor );
}

htaccess remove index.php from url

To remove index.php from the URL, and to redirect the visitor to the non-index.php version of the page:

RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

This will cleanly redirect /index.php/myblog to simply /myblog.

Using a 301 redirect will preserve Google search engine rankings.

Writing new lines to a text file in PowerShell

Try this;

Add-Content -path $logpath @"
$((get-date).tostring()) Error $keyPath $value
key $key expected: $policyValue
local value is:  $localValue
"@

Curly braces in string in PHP

As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner. Remember to use double quotes (" ") as their content is parsed by PHP, because in single quotes (' ') you'll get the literal name of variable provided:

<?php

 $a = '12345';

// This works:
 echo "qwe{$a}rty"; // qwe12345rty, using braces
 echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used

// Does not work:
 echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
 echo "qwe$arty"; // qwe, because $a became $arty, which is undefined

?>

`getchar()` gives the same output as the input string

According to the definition of getchar(), it reads a character from the standard input. Unfortunately stdin is mistaken for keyboard which might not be the case for getchar. getchar uses a buffer as stdin and reads a single character at a time. In your case since there is no EOF, the getchar and putchar are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:

putchar(c);
printf("\n");     
c = getchar();

Now look at the output compared to the original code.

Another example that will explain you the concept of getchar and buffered stdin :

void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}

Enter two characters in the first case. The second time when getchar is running are you entering any character? NO but still putchar works.

This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar uses this buffer as stdin.

bootstrap datepicker today as default

Its simple

$(function() {
        $("#datePicker").datetimepicker({
            defaultDate:'now'

        });
    });

This will set today as default

AngularJs event to call after content is loaded

According to documentation of $viewContentLoaded, it supposed to work

Emitted every time the ngView content is reloaded.

$viewContentLoaded event is emitted that means to receive this event you need a parent controller like

<div ng-controller="MainCtrl">
  <div ng-view></div>
</div>

From MainCtrl you can listen the event

  $scope.$on('$viewContentLoaded', function(){
    //Here your view content is fully loaded !!
  });

Check the Demo

Why java.security.NoSuchProviderException No such provider: BC?

My experience with this was that when I had this in every execution it was fine using the provider as a string like this

Security.addProvider(new BounctCastleProvider());
new JcaPEMKeyConverter().setProvider("BC");

But when I optimized and put the following in the constructor:

   if(bounctCastleProvider == null) {
      bounctCastleProvider = new BouncyCastleProvider();
    }

    if(Security.getProvider(bouncyCastleProvider.getName()) == null) {
      Security.addProvider(bouncyCastleProvider);
    }

Then I had to use provider like this or I would get the above error:

new JcaPEMKeyConverter().setProvider(bouncyCastleProvider);

I am using bcpkix-jdk15on version 1.65

Is there any difference between "!=" and "<>" in Oracle Sql?

No there is no difference at all in functionality.
(The same is true for all other DBMS - most of them support both styles):

Here is the current SQL reference: https://docs.oracle.com/database/121/SQLRF/conditions002.htm#CJAGAABC

The SQL standard only defines a single operator for "not equals" and that is <>

Setting up an MS-Access DB for multi-user access

Access is a great multi-user database. It has lots of built in features to handle the multi-user situation. In fact, it is so very popular because it is such a great multi-user database. There is an upper limit on how many users can all use the database at the same time doing updates and edits - depending on how knowledgeable the developer is about access and how the database has been designed - anywhere from 20 users to approx 50 users. Some access databases can be built to handle up to 50 concurrent users, while many others can handle 20 or 25 concurrent users updating the database. These figures have been observed for databases that have been in use for several or more years and have been discussed many times on the access newsgroups.

Scala list concatenation, ::: vs ++

A different point is that the first sentence is parsed as:

scala> List(1,2,3).++(List(4,5))
res0: List[Int] = List(1, 2, 3, 4, 5)

Whereas the second example is parsed as:

scala> List(4,5).:::(List(1,2,3))
res1: List[Int] = List(1, 2, 3, 4, 5)

So if you are using macros, you should take care.

Besides, ++ for two lists is calling ::: but with more overhead because it is asking for an implicit value to have a builder from List to List. But microbenchmarks did not prove anything useful in that sense, I guess that the compiler optimizes such calls.

Micro-Benchmarks after warming up.

scala>def time(a: => Unit): Long = { val t = System.currentTimeMillis; a; System.currentTimeMillis - t}
scala>def average(a: () => Long) = (for(i<-1 to 100) yield a()).sum/100

scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ++ List(e) } })
res1: Long = 46
scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ::: List(e ) } })
res2: Long = 46

As Daniel C. Sobrai said, you can append the content of any collection to a list using ++, whereas with ::: you can only concatenate lists.

Get the name of an object's type

The kind() function from Agave.JS will return:

  • the closest prototype in the inheritance tree
  • for always-primitive types like 'null' and 'undefined', the primitive name.

It works on all JS objects and primitives, regardless of how they were created, and doesn't have any surprises. Examples:

Numbers

kind(37) === 'Number'
kind(3.14) === 'Number'
kind(Math.LN2) === 'Number'
kind(Infinity) === 'Number'
kind(Number(1)) === 'Number'
kind(new Number(1)) === 'Number'

NaN

kind(NaN) === 'NaN'

Strings

kind('') === 'String'
kind('bla') === 'String'
kind(String("abc")) === 'String'
kind(new String("abc")) === 'String'

Booleans

kind(true) === 'Boolean'
kind(false) === 'Boolean'
kind(new Boolean(true)) === 'Boolean'

Arrays

kind([1, 2, 4]) === 'Array'
kind(new Array(1, 2, 3)) === 'Array'

Objects

kind({a:1}) === 'Object'
kind(new Object()) === 'Object'

Dates

kind(new Date()) === 'Date'

Functions

kind(function(){}) === 'Function'
kind(new Function("console.log(arguments)")) === 'Function'
kind(Math.sin) === 'Function'

undefined

kind(undefined) === 'undefined'

null

kind(null) === 'null'

How do I access ViewBag from JS

<script type="text/javascript">
      $(document).ready(function() {
                showWarning('@ViewBag.Message');
      });

</script>

You can use ViewBag.PropertyName in javascript like this.

Laravel eloquent update record without loading from database

Post::where('id',3)->update(['title'=>'Updated title']);

Confused about __str__ on list in Python

print self.id.__str__() would work for you, although not that useful for you.

Your __str__ method will be more useful when you say want to print out a grid or struct representation as your program develops.

print self._grid.__str__()

def __str__(self):
    """
    Return a string representation of the grid for debugging.
    """
    grid_str = ""
    for row in range(self._rows):
        grid_str += str( self._grid[row] )
        grid_str += '\n'
    return grid_str

Push items into mongo array via mongoose

Use $push to update document and insert new value inside an array.

find:

db.getCollection('noti').find({})

result for find:

{
    "_id" : ObjectId("5bc061f05a4c0511a9252e88"),
    "count" : 1.0,
    "color" : "green",
    "icon" : "circle",
    "graph" : [ 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 2.0
        }
    ],
    "name" : "online visitor",
    "read" : false,
    "date" : ISODate("2018-10-12T08:57:20.853Z"),
    "__v" : 0.0
}

update:

db.getCollection('noti').findOneAndUpdate(
   { _id: ObjectId("5bc061f05a4c0511a9252e88") }, 
   { $push: { 
             graph: {
               "date" : ISODate("2018-10-24T08:55:13.331Z"),
               "count" : 3.0
               }  
           } 
   })

result for update:

{
    "_id" : ObjectId("5bc061f05a4c0511a9252e88"),
    "count" : 1.0,
    "color" : "green",
    "icon" : "circle",
    "graph" : [ 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 2.0
        }, 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 3.0
        }
    ],
    "name" : "online visitor",
    "read" : false,
    "date" : ISODate("2018-10-12T08:57:20.853Z"),
    "__v" : 0.0
}