Programs & Examples On #Tlabel

tlabel is a nonwindowed VCL control that displays non editable text on a form. It is defined in the StdCtrls.pas unit.

'mat-form-field' is not a known element - Angular 5 & Material2

I had this problem too. It turned out I forgot to include one of the components in app.module.ts

How to fix Error: this class is not key value coding-compliant for the key tableView.'

You have your storyboard set up to expect an outlet called tableView but the actual outlet name is myTableView.

If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.

How to detect tableView cell touched or clicked in swift

You should implement didSelect function.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 print("User touched on \(indexpath) row") 

}

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

If the classic solutions (register identifier for class in code or IB) do not work: try to relaunch Xcode, turns out my storyboard stopped saving edits I was made, including setting the reuse identifier.

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

Add these 2 lines

layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0

So you have:

   // Do any additional setup after loading the view, typically from a nib.
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
        layout.itemSize = CGSize(width: screenWidth/3, height: screenWidth/3)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        collectionView!.collectionViewLayout = layout

That will remove all the spaces and give you a grid layout:

enter image description here

If you want the first column to have a width equal to the screen width then add the following function:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if indexPath.row == 0
    {
        return CGSize(width: screenWidth, height: screenWidth/3)
    }
    return CGSize(width: screenWidth/3, height: screenWidth/3);

}

Grid layout will now look like (I've also added a blue background to first cell): enter image description here

Nested Recycler view height doesn't wrap its content

@user2302510 solution works not as good as you may expected. Full workaround for both orientations and dynamically data changes is:

public class MyLinearLayoutManager extends LinearLayoutManager {

    public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
        super(context, orientation, reverseLayout);
    }

    private int[] mMeasuredDimension = new int[2];

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                          int widthSpec, int heightSpec) {
        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);
        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {
            measureScrapChild(recycler, i,
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    mMeasuredDimension);

            if (getOrientation() == HORIZONTAL) {
                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
                }
            } else {
                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];
                }
            }
        }
        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        View view = recycler.getViewForPosition(position);
        if (view != null) {
            RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
            int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                    getPaddingLeft() + getPaddingRight(), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                    getPaddingTop() + getPaddingBottom(), p.height);
            view.measure(childWidthSpec, childHeightSpec);
            measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
            measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
            recycler.recycleView(view);
        }
    }
}

How to get textLabel of selected row in swift?

In my case I made small changes, when i search the value in tabelview select (didSelectRowAtIndexPath) the cell its return the index of the cell so im get problem in move one viewControler to another.By using this method i found a solution to redirect to a new viewControler

let indexPath = tableView.indexPathForSelectedRow!
let currentCellValue = tableView.cellForRow(at: indexPath!)! as UITableViewCell
let textLabelText = currentCellValue.textLabel!.text
print(textLabelText) 

Custom UITableViewCell from nib in Swift

swift 4.1.2

xib.

Create ImageCell2.swift

Step 1

import UIKit

class ImageCell2: UITableViewCell {

    @IBOutlet weak var imgBookLogo: UIImageView!
    @IBOutlet weak var lblTitle: UILabel!
    @IBOutlet weak var lblPublisher: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

}

step 2 . According Viewcontroller class

  import UIKit

    class ImageListVC: UIViewController,UITableViewDataSource,UITableViewDelegate {
    @IBOutlet weak var tblMainVC: UITableView!

    var arrBook : [BookItem] = [BookItem]()

    override func viewDidLoad() {
        super.viewDidLoad()
         //Regester Cell
        self.tblMainVC.register(UINib.init(nibName: "ImageCell2", bundle: nil), forCellReuseIdentifier: "ImageCell2")
        // Response Call adn Disply Record
        APIManagerData._APIManagerInstance.getAPIBook { (itemInstance) in
            self.arrBook = itemInstance.arrItem!
            self.tblMainVC.reloadData()
        }
    }
    //MARK: DataSource & delegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.arrBook.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//    [enter image description here][2]
        let cell  = tableView.dequeueReusableCell(withIdentifier: "ImageCell2") as! ImageCell2
        cell.lblTitle.text = self.arrBook[indexPath.row].title
        cell.lblPublisher.text = self.arrBook[indexPath.row].publisher
        if let authors = self.arrBook[indexPath.row].author {
            for item in authors{
                print(" item \(item)")
            }
        }
        let  url  = self.arrBook[indexPath.row].imageURL
        if url == nil {
            cell.imgBookLogo.kf.setImage(with: URL.init(string: ""), placeholder: UIImage.init(named: "download.jpeg"))
        }
        else{
            cell.imgBookLogo.kf.setImage(with: URL(string: url!)!, placeholder: UIImage.init(named: "download.jpeg"))
        }
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    } 

}

creating custom tableview cells in swift

I have the same problem.

Generally what I did is the same as you.

class dynamicCell: UITableViewCell {

    @IBOutlet var testLabel : UILabel

    init(style: UITableViewCellStyle, reuseIdentifier: String) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
}

and in the uitableviewcell method:

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    var cell :dynamicCell = tableView.dequeueReusableCellWithIdentifier("cell") as dynamicCell

    cell.testLabel.text = "so sad"

    println(cell.testLabel)

    return cell;
}

and yeah the tableview shows nothing! But guess what, it actually shows something...because the log I get from the println(cell.testLabel) shows that all the Labels are actually displayed out.

BUT! their Frames is strange, which have something like this:

frame = (0 -21; 42 21);

so it has a (0,-21) as (x,y), so that means the label just appears at somewhere outside the bound of the cell.

so I try to add adjust the frame manually like this:

cell.testLabel.frame = CGRectMake(10, 10, 42, 21)

and sadly, it doesn't work.

---------------update after 10 min -----------------

I DID IT. so, it seems that the problem comes from the Size Classes.

Click on your .storyboard file and go to the File Inspector Tab

UNCHECK THE Size Classes checkbox

and finally, my "so sad"Label comes out!

Make a simple fade in animation in Swift?

If you want repeatable fade animation you can do that by using CABasicAnimation like below :

First create handy UIView extension :

extension UIView {

    enum AnimationKeyPath: String {
        case opacity = "opacity"
    }

    func flash(animation: AnimationKeyPath ,withDuration duration: TimeInterval = 0.5, repeatCount: Float = 5){
        let flash = CABasicAnimation(keyPath: animation.rawValue)
        flash.duration = duration
        flash.fromValue = 1 // alpha
        flash.toValue = 0 // alpha
        flash.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        flash.autoreverses = true
        flash.repeatCount = repeatCount

        layer.add(flash, forKey: nil)
    }
}

How to use it:

    // You can use it with all kind of UIViews e.g. UIButton, UILabel, UIImage, UIImageView, ...
    imageView.flash(animation: .opacity, withDuration: 1, repeatCount: 5)
    titleLabel.flash(animation: .opacity, withDuration: 1, repeatCount: 5)

Add swipe to delete UITableViewCell

Simply add method:

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: UITableViewRowActionStyle.destructive, title: "Delete") { (action, indexPath) in
        self.arrayFruit.remove(at: indexPath.row)
        self.tblList.reloadData()
    }

    let edit = UITableViewRowAction(style: UITableViewRowActionStyle.normal, title: "Edit") { (action, indexpath) in

        let alert = UIAlertController(title: "FruitApp", message: "Enter Fuit Name", preferredStyle: UIAlertControllerStyle.alert)
        alert.addTextField(configurationHandler: { (textField) in
            textField.placeholder = "Enter new fruit name"
        })
        alert.addAction(UIAlertAction(title: "Update", style: UIAlertActionStyle.default, handler: { [weak alert](_) in
            let textField = alert?.textFields![0]
            self.arrayFruit[indexPath.row] = (textField?.text!)!
            self.tblList.reloadData()
        }))

        self.present(alert, animated: true, completion: nil)
    }
    edit.backgroundColor = UIColor.blue
    return [delete,edit]
}

enter image description here

Make a UIButton programmatically in Swift

Swift 3: You can create a UIButton programmatically

either inside a methods scope for example in ViewDidLoad() Be sure to add constraints to the button, otherwise you wont see it

let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.target(forAction: #selector(buttonAction), withSender: self)
//button.backgroundColor etc

view.addSubview(button)

@objc func buttonAction() {
   //some Action
}

or outside your scope as global variable to access it from anywhere in your module

let button: UIButton = {
   let b = UIButton()
   b.translatesAutoresizingMaskIntoConstraints = false
   //b.backgroundColor etc
   return b
}()

and then you setup the constraints

func setupButtonView() {
   view.addSubview(button)
   button.widthAnchor.constraint(equalToConstant: 40).isActive = true
   button.heightAnchor.constraint(equalToConstant: 40).isActive = true
   // etc

}

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

add parameter nativeQuery = true

ex: @Query(value="Update user set user_name =:user_name,password =:password where user_id =:user_id",nativeQuery = true)

D3 Appending Text to a SVG Rectangle

A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

http://bl.ocks.org/mbostock/7341714

Multi-line labels are also a little tricky, you might want to check out this wrap function.

On Selenium WebDriver how to get Text from Span Tag

If you'd rather use xpath and that span is the only span below your div, use my example below. I'd recommend using CSS (see sircapsalot's post).

String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']//span)).getText();

css example:

String kk = wd.findElement(By.cssSelector("div[id='customSelect_3'] span[class='selectLabel clear']")).getText();

Call PHP function from Twig template

This worked for me (using Slim Twig-View):

$twig->getEnvironment()->addFilter(
   new \Twig_Filter('md5', function($arg){ return md5($arg); })
);

This creates a new filter named md5 which returns the MD5 checksum of the argument.

Selenium and xpath: finding a div with a class/id and verifying text inside

To account for leading and trailing whitespace, you probably want to use normalize-space()

//div[contains(@class, 'Caption') and normalize-space(.)='Model saved']

and

//div[@id='alertLabel' and normalize-space(.)='Save to server successful']

Note that //div[contains(@class, 'Caption') and normalize-space(.//text())='Model saved'] also works.

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
}()

Changing the text on a label

self.labelText = 'change the value'

The above sentence makes labelText change the value, but not change depositLabel's text.

To change depositLabel's text, use one of following setences:

self.depositLabel['text'] = 'change the value'

OR

self.depositLabel.config(text='change the value')

Creating a UITableView Programmatically

When you register a class, and use dequeueReusableCellWithIdentifier:forIndexPath:, the dequeue method is guaranteed to return a cell, so your if (cell == nil) clause is never entered. So, just do it the old way, don't register the class, and use dequeueReusableCellWithIdentifier:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"newFriendCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
//etc.
return cell;
}

As for the segue, it can't be called because you can't make a segue to a table that you've created in code, not in IB. Again, go back to the old way and use tableView:didSelectRowAtIndexPath: which will be called when you select a cell. Instantiate your detail controller there and do the trasition in code.

After edit:

I didn't see your added code there. You've implemented didDeselectRowAtIndexPath rather than didSelectRowAtIndexPath. If you change that, your segue should work.

Getting list of items inside div using Selenium Webdriver

I'm not sure if your findElements statement gets you all the divs. I would try the following:

List<WebElement> elementsRoot = driver.findElements(By.xpath("//div[@class=\"facetContainerDiv\"]/div));

for(int i = 0; i < elementsRoot.size(); ++i) {
     WebElement checkbox = elementsRoot.get(i).findElement(By.xpath("./label/input"));
     checkbox.click();
     blah blah blah
}

The idea here is that you get the root element then use another a 'sub' xpath or any selector you like to find the node element. Of course the xpath or selector may need to be adjusted to properly find the element you want.

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

If you want to use valueChangeListener, you need to submit the form every time a new option is chosen. Something like this:

<p:selectOneMenu value="#{mymb.employee}" onchange="submit()"
                 valueChangeListener="#{mymb.handleChange}" >
    <f:selectItems value="#{mymb.employeesList}" var="emp"
                   itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeID}" />
</p:selectOneMenu>

public void handleChange(ValueChangeEvent event){  
    System.out.println("New value: " + event.getNewValue());
}

Or else, if you want to use <p:ajax>, it should look like this:

<p:selectOneMenu value="#{mymb.employee}" >
    <p:ajax listener="#{mymb.handleChange}" />
    <f:selectItems value="#{mymb.employeesList}" var="emp"
                   itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeID}" />
</p:selectOneMenu>

private String employeeID;

public void handleChange(){  
    System.out.println("New value: " + employee);
}

One thing to note is that in your example code, I saw that the value attribute of your <p:selectOneMenu> is #{mymb.employeesList} which is the same as the value of <f:selectItems>. The value of your <p:selectOneMenu> should be similar to my examples above which point to a single employee, not a list of employees.

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 to set selected index JComboBox by value

The right way to set an item selected when the combobox is populated by some class' constructor (as @milosz posted):

combobox.getModel().setSelectedItem(new ClassName(parameter1, parameter2));

In your case the code would be:

test.getModel().setSelectedItem(new ComboItem(3, "banana"));

The representation of if-elseif-else in EL using JSF

You can use EL if you want to work as IF:

<h:outputLabel value="#{row==10? '10' : '15'}"/>

Changing styles or classes:

style="#{test eq testMB.test? 'font-weight:bold' : 'font-weight:normal'}"

class="#{test eq testMB.test? 'divRred' : 'divGreen'}"

Dynamically changing font size of UILabel

Its a little bit not sophisticated but this should work, for example lets say you want to cap your uilabel to 120x120, with max font size of 28:

magicLabel.numberOfLines = 0;
magicLabel.lineBreakMode = NSLineBreakByWordWrapping;
...
magicLabel.text = text;
    for (int i = 28; i>3; i--) {
        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:(CGFloat)i] constrainedToSize:CGSizeMake(120.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
        if (size.height < 120) {
            magicLabel.font = [UIFont systemFontOfSize:(CGFloat)i];
            break;
        }
    }

Use jQuery to change value of a label

val() is more like a shortcut for attr('value'). For your usage use text() or html() instead

Minimum and maximum date

As you can see, 01/01/1970 returns 0, which means it is the lowest possible date.

new Date('1970-01-01Z00:00:00:000') //returns Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)
new Date('1970-01-01Z00:00:00:000').getTime() //returns 0
new Date('1970-01-01Z00:00:00:001').getTime() //returns 1

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Alternatively you can edit the source and create your own incrementations

FontAwesome 5

https://github.com/FortAwesome/Font-Awesome/blob/master/web-fonts-with-css/less/_larger.less

// Icon Sizes
// -------------------------

.larger(@factor) when (@factor > 0) {
  .larger((@factor - 1));

  .@{fa-css-prefix}-@{factor}x {
    font-size: (@factor * 1em);
  }
}

/* makes the font 33% larger relative to the icon container */
.@{fa-css-prefix}-lg {
  font-size: (4em / 3);
  line-height: (3em / 4);
  vertical-align: -.0667em;
}

.@{fa-css-prefix}-xs {
  font-size: .75em;
}

.@{fa-css-prefix}-sm {
  font-size: .875em;
}

// Change the number below to create your own incrementations
// This currently creates classes .fa-1x - .fa-10x
.larger(10);

FontAwesome 4

https://github.com/FortAwesome/Font-Awesome/blob/v4.7.0/less/larger.less

// Icon Sizes
// -------------------------

/* makes the font 33% larger relative to the icon container */
.@{fa-css-prefix}-lg {
    font-size: (4em / 3);
    line-height: (3em / 4);
    vertical-align: -15%;
}

.@{fa-css-prefix}-2x { font-size: 2em; }
.@{fa-css-prefix}-3x { font-size: 3em; }
.@{fa-css-prefix}-4x { font-size: 4em; }
.@{fa-css-prefix}-5x { font-size: 5em; }

// Your custom sizes
.@{fa-css-prefix}-6x { font-size: 6em; }
.@{fa-css-prefix}-7x { font-size: 7em; }
.@{fa-css-prefix}-8x { font-size: 8em; }

Hibernate: ids for this class must be manually assigned before calling save()

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

2D cross-platform game engine for Android and iOS?

Here is just a reply from Richard Pickup on LinkedIn to a similar question of mine:

I've used cocos 2dx marmalade and unity on both iOS and android. For 2d games cocos2dx is the way to go every time. Unity is just too much overkill for 2d games and as already stated marmalade is just a thin abstraction layer not really a game engine. You can even run cocos2d on top of marmalade. My approach would be to use cocos2dx on iOS and android then in future run cocosd2dx code on top of marmalade as an easy way to port to bb10 and win phone 7

Moving Average Pandas

To get the moving average in pandas we can use cum_sum and then divide by count.

Here is the working example:

import pandas as pd
import numpy as np

df = pd.DataFrame({'id': range(5),
                   'value': range(100,600,100)})

# some other similar statistics
df['cum_sum'] = df['value'].cumsum()
df['count'] = range(1,len(df['value'])+1)
df['mov_avg'] = df['cum_sum'] / df['count']

# other statistics
df['rolling_mean2'] = df['value'].rolling(window=2).mean()

print(df)

output

   id  value  cum_sum  count  mov_avg     rolling_mean2
0   0    100      100      1    100.0           NaN
1   1    200      300      2    150.0           150.0
2   2    300      600      3    200.0           250.0
3   3    400     1000      4    250.0           350.0
4   4    500     1500      5    300.0           450.0

How do I get an apk file from an Android device?

If you know (or if you can "guess") the path to the .apk (it seems to be of the format /data/app/com.example.someapp-{1,2,..}.apk to , then you can just copy it from /data/app as well. This worked even on my non-rooted, stock Android phone.

Just use a Terminal Emulator app (such as this one) and run:

# step 1: confirm path
ls /data/app/com.example.someapp-1.apk
# if it doesn't show up, try -2, -3. Note that globbing (using *) doesn't work here.
# step 2: copy (make sure you adapt the path to match what you discovered above)
cp /data/app/com.example.someapp-1.apk /mnt/sdcard/

Then you can move it from the SD-card to wherever you want (or attach it to an email etc). The last bit might be technically optional, but it makes your life a lot easier when trying to do something with the .apk file.

Open link in new tab or window

It shouldn't be your call to decide whether the link should open in a new tab or a new window, since ultimately this choice should be done by the settings of the user's browser. Some people like tabs; some like new windows.

Using _blank will tell the browser to use a new tab/window, depending on the user's browser configuration and how they click on the link (e.g. middle click, Ctrl+click, or normal click).

Check if a value is in an array (C#)

    public static bool Contains(Array a, object val)
    {
        return Array.IndexOf(a, val) != -1;
    }

how to kill the tty in unix

you do not need to know pts number, just type:

ps all | grep bash

then:

kill pid1 pid2 pid3 ...

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

@Before(JUnit4) -> @BeforeEach(JUnit5) - method is called before every test

@After(JUnit4) -> @AfterEach(JUnit5) - method is called after every test

@BeforeClass(JUnit4) -> @BeforeAll(JUnit5) - static method is called before executing all tests in this class. It can be a large task as starting server, read file, making db connection...

@AfterClass(JUnit4) -> @AfterAll(JUnit5) - static method is called after executing all tests in this class.

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

You can generate many types of barcodes, namely 1D or 2D. Add the required library:

require_once('class/BCGcode39.barcode.php');

Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:

Example

Since several have asked for an example here is what I was able to do to get it done

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

require_once('class/BCGcode128.barcode.php');

header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();
$code->parse('HELLO');

$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);

$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);

to

$drawing = new BCGDrawing('image.png', $color_white);

HTML anchor link - href and onclick both?

<a href="#Foo" onclick="return runMyFunction();">Do it!</a>

and

function runMyFunction() {
  //code
  return true;
}

This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.

how to set default main class in java?

you can right click on the project select "set configuration" then "Customize", from there you can choose your main class. ScreenShot

Adding multiple class using ng-class

Below active and activemenu are classes and itemCount and ShowCart is expression/boolean values.

ng-class="{'active' : itemCount, 'activemenu' : showCart}"

Permission denied error on Github Push

Another way to get this error, is if you have duplicate or conflicting ~/.ssh/* entries. First check what is on your ssh key-chain with:

$ ssh-add -l
2048 SHA256:<hash1> [email protected] (RSA)
2048 SHA256:<hash2> [email protected] (RSA)
2048 SHA256:<hash3> [email protected] (RSA)

As you can see there are two emails which are the same, and easy for you to get confused. Then check your config file:

$ cat ~/.ssh/config

# GitHub: [email protected]
Host github_ex
 HostName github.com
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/github_ex

# GitHub: [email protected]
Host github
 HostName github.com
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/github

# Bitbucket: [email protected]
Host bitbucket
 HostName bitbucket.org
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/bitbuc

Here you see that you have two different email accounts to github but same HostName. Someone is bound to get confused, including your git.

To resolve, manually remove (after copying) the (default) files:

cd ~/.ssh
rm id_rsa
rm id_rsa.pub

Now copy back the one you want to use, for example Host github:

cp -a github id_rsa
cp -a github.pub id_rsa.pub

Then try again.

For some reason, removing keys with ssh-add -d id_rsa didn't work as expected, as it seem that key-chain is cached.

how to set the background color of the whole page in css

The problem is that the body of the page isn't actually visible. The DIVs under have width of 100% and have background colors themselves that override the body CSS.

To Fix the no-man's land, this might work. It's not elegant, but works.

#doc3 {
    margin: auto 10px;
    width: auto;
    height: 2000px;
    background-color: yellow;
}

Find distance between two points on map using Google Map API V2

public class GoogleDirection {

    public final static String MODE_DRIVING = "driving";
    public final static String MODE_WALKING = "walking";
    public final static String MODE_BICYCLING = "bicycling";

    public final static String STATUS_OK = "OK";
    public final static String STATUS_NOT_FOUND = "NOT_FOUND";
    public final static String STATUS_ZERO_RESULTS = "ZERO_RESULTS";
    public final static String STATUS_MAX_WAYPOINTS_EXCEEDED = "MAX_WAYPOINTS_EXCEEDED";
    public final static String STATUS_INVALID_REQUEST = "INVALID_REQUEST";
    public final static String STATUS_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT";
    public final static String STATUS_REQUEST_DENIED = "REQUEST_DENIED";
    public final static String STATUS_UNKNOWN_ERROR = "UNKNOWN_ERROR";

    public final static int SPEED_VERY_FAST = 1;
    public final static int SPEED_FAST = 2;
    public final static int SPEED_NORMAL = 3;
    public final static int SPEED_SLOW = 4;
    public final static int SPEED_VERY_SLOW = 5;

    private OnDirectionResponseListener mDirectionListener = null;
    private OnAnimateListener mAnimateListener = null;

    private boolean isLogging = false;

    private LatLng animateMarkerPosition = null;
    private LatLng beginPosition = null;
    private LatLng endPosition = null;
    private ArrayList<LatLng> animatePositionList = null;
    private Marker animateMarker = null;
    private Polyline animateLine = null;
    private GoogleMap gm = null;
    private int step = -1;
    private int animateSpeed = -1;
    private int zoom = -1;
    private double animateDistance = -1;
    private double animateCamera = -1;
    private double totalAnimateDistance = 0;
    private boolean cameraLock = false;
    private boolean drawMarker = false;
    private boolean drawLine = false;
    private boolean flatMarker = false;
    private boolean isCameraTilt = false;
    private boolean isCameraZoom = false;
    private boolean isAnimated = false;

    private Context mContext = null;

    public GoogleDirection(Context context) { 
        mContext = context;
    }

    public String request(LatLng start, LatLng end, String mode) {
        final String url = "http://maps.googleapis.com/maps/api/directions/xml?"
                + "origin=" + start.latitude + "," + start.longitude  
                + "&destination=" + end.latitude + "," + end.longitude 
                + "&sensor=false&units=metric&mode=" + mode;

        if(isLogging)
            Log.i("GoogleDirection", "URL : " + url);
        new RequestTask().execute(new String[]{ url });
        return url;
    }

    private class RequestTask extends AsyncTask<String, Void, Document> {
        protected Document doInBackground(String... url) {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(url[0]);
                HttpResponse response = httpClient.execute(httpPost, localContext);
                InputStream in = response.getEntity().getContent();
                DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                return builder.parse(in);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } 
            return null;
        }

        protected void onPostExecute(Document doc) {
            super.onPostExecute(doc);
            if(mDirectionListener != null)
                mDirectionListener.onResponse(getStatus(doc), doc, GoogleDirection.this);
        }

        private String getStatus(Document doc) {
            NodeList nl1 = doc.getElementsByTagName("status");
            Node node1 = nl1.item(0);
            if(isLogging)
                Log.i("GoogleDirection", "Status : " + node1.getTextContent());
            return node1.getTextContent();
        }
    }

    public void setLogging(boolean state) {
        isLogging = state;
    }

    public String getStatus(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("status");
        Node node1 = nl1.item(0);
        if(isLogging)
            Log.i("GoogleDirection", "Status : " + node1.getTextContent());
        return node1.getTextContent();
    }

    public String[] getDurationText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        String[] arr_str = new String[nl1.getLength() - 1];
        for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "text"));
            arr_str[i] = node2.getTextContent();
            if(isLogging)
                Log.i("GoogleDirection", "DurationText : " + node2.getTextContent());
        }
        return arr_str;
    }

    public int[] getDurationValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        int[] arr_int = new int[nl1.getLength() - 1];
        for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "value"));
            arr_int[i] = Integer.parseInt(node2.getTextContent());
            if(isLogging)
                Log.i("GoogleDirection", "Duration : " + node2.getTextContent());
        }
        return arr_int;
    }

    public String getTotalDurationText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        if(isLogging)
            Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
        return node2.getTextContent();
    }

    public int getTotalDurationValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        if(isLogging)
            Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
        return Integer.parseInt(node2.getTextContent());
    }

    public String[] getDistanceText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        String[] arr_str = new String[nl1.getLength() - 1];
        for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "text"));
            arr_str[i] = node2.getTextContent();
            if(isLogging)
                Log.i("GoogleDirection", "DurationText : " + node2.getTextContent());
        }
        return arr_str;
    }

    public int[] getDistanceValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        int[] arr_int = new int[nl1.getLength() - 1];
        for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "value"));
            arr_int[i] = Integer.parseInt(node2.getTextContent());
            if(isLogging)
                Log.i("GoogleDirection", "Duration : " + node2.getTextContent());
        }
        return arr_int;
    }

    public String getTotalDistanceText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        if(isLogging)
            Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
        return node2.getTextContent();
    }

    public int getTotalDistanceValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        if(isLogging)
            Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
        return Integer.parseInt(node2.getTextContent());
    }

    public String getStartAddress(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("start_address");
        Node node1 = nl1.item(0);
        if(isLogging)
            Log.i("GoogleDirection", "StartAddress : " + node1.getTextContent());
        return node1.getTextContent();
    }

    public String getEndAddress(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("end_address");
        Node node1 = nl1.item(0);
        if(isLogging)
            Log.i("GoogleDirection", "StartAddress : " + node1.getTextContent());
        return node1.getTextContent();
    }

    public String getCopyRights(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("copyrights");
        Node node1 = nl1.item(0);
        if(isLogging)
            Log.i("GoogleDirection", "CopyRights : " + node1.getTextContent());
        return node1.getTextContent();
    }

    public ArrayList<LatLng> getDirection(Document doc) {
        NodeList nl1, nl2, nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");
        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();

                Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
                nl3 = locationNode.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));

                locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "points"));
                ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
                for(int j = 0 ; j < arr.size() ; j++) {
                    listGeopoints.add(new LatLng(arr.get(j).latitude
                            , arr.get(j).longitude));
                }

                locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "lat"));
                lat = Double.parseDouble(latNode.getTextContent());
                lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }

        return listGeopoints;
    }

    public ArrayList<LatLng> getSection(Document doc) {
        NodeList nl1, nl2, nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");
        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();

                Node locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }

        return listGeopoints;
    }

    public PolylineOptions getPolyline(Document doc, int width, int color) {
        ArrayList<LatLng> arr_pos = getDirection(doc);
        PolylineOptions rectLine = new PolylineOptions().width(dpToPx(width)).color(color);
        for(int i = 0 ; i < arr_pos.size() ; i++)        
            rectLine.add(arr_pos.get(i));
        return rectLine;
    }

    private int getNodeIndex(NodeList nl, String nodename) {
        for(int i = 0 ; i < nl.getLength() ; i++) {
            if(nl.item(i).getNodeName().equals(nodename))
                return i;
        }
        return -1;
    }

    private ArrayList<LatLng> decodePoly(String encoded) {
        ArrayList<LatLng> poly = new ArrayList<LatLng>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;
        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;
            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng position = new LatLng((double)lat / 1E5, (double)lng / 1E5);
            poly.add(position);
        }
        return poly;
    }

    private int dpToPx(int dp) {
        DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
        int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));       
        return px;
    }

    public void setOnDirectionResponseListener(OnDirectionResponseListener listener) {
        mDirectionListener = listener;
    }

    public void setOnAnimateListener(OnAnimateListener listener) {
        mAnimateListener = listener;
    }

    public interface OnDirectionResponseListener {
        public void onResponse(String status, Document doc, GoogleDirection gd);
    }

    public interface OnAnimateListener {
        public void onFinish();
        public void onStart();
        public void onProgress(int progress, int total);
    }

    public void animateDirection(GoogleMap gm, ArrayList<LatLng> direction, int speed
            , boolean cameraLock, boolean isCameraTilt, boolean isCameraZoom
            , boolean drawMarker, MarkerOptions mo, boolean flatMarker
            , boolean drawLine, PolylineOptions po) {
        if(direction.size() > 1) {
            isAnimated = true;
            animatePositionList = direction;
            animateSpeed = speed;
            this.drawMarker = drawMarker;
            this.drawLine = drawLine;
            this.flatMarker = flatMarker;
            this.isCameraTilt = isCameraTilt;
            this.isCameraZoom = isCameraZoom;
            step = 0;
            this.cameraLock = cameraLock;
            this.gm = gm;

            setCameraUpdateSpeed(speed);

            beginPosition = animatePositionList.get(step);
            endPosition = animatePositionList.get(step + 1);
            animateMarkerPosition = beginPosition;

            if(mAnimateListener != null)
                mAnimateListener.onProgress(step, animatePositionList.size());

            if(cameraLock) {
                float bearing = getBearing(beginPosition, endPosition);
                CameraPosition.Builder cameraBuilder = new CameraPosition.Builder()
                    .target(animateMarkerPosition).bearing(bearing);

                if(isCameraTilt) 
                    cameraBuilder.tilt(90);
                else 
                    cameraBuilder.tilt(gm.getCameraPosition().tilt);

                if(isCameraZoom) 
                    cameraBuilder.zoom(zoom);
                else 
                    cameraBuilder.zoom(gm.getCameraPosition().zoom);

                CameraPosition cameraPosition = cameraBuilder.build();
                gm.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }

            if(drawMarker) {
                if(mo != null)
                    animateMarker = gm.addMarker(mo.position(beginPosition));
                else 
                    animateMarker = gm.addMarker(new MarkerOptions().position(beginPosition));

                if(flatMarker) {
                    animateMarker.setFlat(true);

                    float rotation = getBearing(animateMarkerPosition, endPosition) + 180;
                    animateMarker.setRotation(rotation);
                }
            }


            if(drawLine) {
                if(po != null) 
                    animateLine = gm.addPolyline(po.add(beginPosition)
                            .add(beginPosition).add(endPosition)
                            .width(dpToPx((int)po.getWidth())));
                else 
                    animateLine = gm.addPolyline(new PolylineOptions()
                            .width(dpToPx(5)));
            }

            new Handler().postDelayed(r, speed);
            if(mAnimateListener != null)
                mAnimateListener.onStart();
        }
    }

    public void cancelAnimated() {
        isAnimated = false;
    }

    public boolean isAnimated() {
        return isAnimated;
    }

    private Runnable r = new Runnable() {
        public void run() {

            animateMarkerPosition = getNewPosition(animateMarkerPosition, endPosition);

            if(drawMarker)
                animateMarker.setPosition(animateMarkerPosition);


            if(drawLine) {
                List<LatLng> points = animateLine.getPoints();
                points.add(animateMarkerPosition);
                animateLine.setPoints(points);
            }

            if((animateMarkerPosition.latitude == endPosition.latitude 
                    && animateMarkerPosition.longitude == endPosition.longitude)) {
                if(step == animatePositionList.size() - 2) {
                    isAnimated = false;
                    totalAnimateDistance = 0;
                    if(mAnimateListener != null)
                        mAnimateListener.onFinish();
                } else {
                    step++;
                    beginPosition = animatePositionList.get(step);
                    endPosition = animatePositionList.get(step + 1);
                    animateMarkerPosition = beginPosition;

                    if(flatMarker && step + 3 < animatePositionList.size() - 1) {
                        float rotation = getBearing(animateMarkerPosition, animatePositionList.get(step + 3)) + 180;
                        animateMarker.setRotation(rotation);
                    }

                    if(mAnimateListener != null)
                        mAnimateListener.onProgress(step, animatePositionList.size());
                }
            }

            if(cameraLock && (totalAnimateDistance > animateCamera || !isAnimated)) {
                totalAnimateDistance = 0;
                float bearing = getBearing(beginPosition, endPosition);
                CameraPosition.Builder cameraBuilder = new CameraPosition.Builder()
                    .target(animateMarkerPosition).bearing(bearing);

                if(isCameraTilt) 
                    cameraBuilder.tilt(90);
                else 
                    cameraBuilder.tilt(gm.getCameraPosition().tilt);

                if(isCameraZoom) 
                    cameraBuilder.zoom(zoom);
                else 
                    cameraBuilder.zoom(gm.getCameraPosition().zoom);

                CameraPosition cameraPosition = cameraBuilder.build();
                gm.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

            }

            if(isAnimated) {
                new Handler().postDelayed(r, animateSpeed);
            }
        }
    };

    public Marker getAnimateMarker() {
        return animateMarker;
    }

    public Polyline getAnimatePolyline() {
        return animateLine;
    }

    private LatLng getNewPosition(LatLng begin, LatLng end) {
        double lat = Math.abs(begin.latitude - end.latitude); 
        double lng = Math.abs(begin.longitude - end.longitude);

        double dis = Math.sqrt(Math.pow(lat, 2) + Math.pow(lng, 2));
        if(dis >= animateDistance) {
            double angle = -1;

            if(begin.latitude <= end.latitude && begin.longitude <= end.longitude)
                angle = Math.toDegrees(Math.atan(lng / lat));
            else if(begin.latitude > end.latitude && begin.longitude <= end.longitude)
                angle = (90 - Math.toDegrees(Math.atan(lng / lat))) + 90;
            else if(begin.latitude > end.latitude && begin.longitude > end.longitude)
                angle = Math.toDegrees(Math.atan(lng / lat)) + 180;
            else if(begin.latitude <= end.latitude && begin.longitude > end.longitude)
                angle = (90 - Math.toDegrees(Math.atan(lng / lat))) + 270;

            double x = Math.cos(Math.toRadians(angle)) * animateDistance;
            double y = Math.sin(Math.toRadians(angle)) * animateDistance;
            totalAnimateDistance += animateDistance;
            double finalLat = begin.latitude + x;
            double finalLng = begin.longitude + y;

            return new LatLng(finalLat, finalLng);
        } else {
            return end;
        }
    }

    private float getBearing(LatLng begin, LatLng end) {
        double lat = Math.abs(begin.latitude - end.latitude); 
        double lng = Math.abs(begin.longitude - end.longitude);
         if(begin.latitude < end.latitude && begin.longitude < end.longitude)
            return (float)(Math.toDegrees(Math.atan(lng / lat)));
        else if(begin.latitude >= end.latitude && begin.longitude < end.longitude)
            return (float)((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
        else if(begin.latitude >= end.latitude && begin.longitude >= end.longitude)
            return  (float)(Math.toDegrees(Math.atan(lng / lat)) + 180);
        else if(begin.latitude < end.latitude && begin.longitude >= end.longitude)
            return (float)((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
         return -1;
    }

    public void setCameraUpdateSpeed(int speed) {       
        if(speed == SPEED_VERY_SLOW) {
            animateDistance = 0.000005;
            animateSpeed = 20;
            animateCamera = 0.0004;
            zoom = 19;
        } else if(speed == SPEED_SLOW) {
            animateDistance = 0.00001;
            animateSpeed = 20;
            animateCamera = 0.0008;
            zoom = 18;
        } else if(speed == SPEED_NORMAL) {
            animateDistance = 0.00005;
            animateSpeed = 20;
            animateCamera = 0.002;
            zoom = 16;
        } else if(speed == SPEED_FAST) {
            animateDistance = 0.0001;
            animateSpeed = 20;
            animateCamera = 0.004;
            zoom = 15;
        } else if(speed == SPEED_VERY_FAST) {
            animateDistance = 0.0005;
            animateSpeed = 20;
            animateCamera = 0.004;
            zoom = 13;
        } else {
            animateDistance = 0.00005;
            animateSpeed = 20;
            animateCamera = 0.002;
            zoom = 16;
        }
    }
}

//Main Activity

public class MapActivity extends ActionBarActivity {

    GoogleMap map = null;
    GoogleDirection gd;

    LatLng start,end;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        start = new LatLng(13.744246499553903, 100.53428772836924);
        end = new LatLng(13.751279688694071, 100.54316081106663);


        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(start, 15));

        gd = new GoogleDirection(this);
        gd.setOnDirectionResponseListener(new GoogleDirection.OnDirectionResponseListener() {
            public void onResponse(String status, Document doc, GoogleDirection gd) {
                Toast.makeText(getApplicationContext(), status, Toast.LENGTH_SHORT).show();

                gd.animateDirection(map, gd.getDirection(doc), GoogleDirection.SPEED_FAST
                        , true, true, true, false, null, false, true, new PolylineOptions().width(8).color(Color.RED));

                map.addMarker(new MarkerOptions().position(start)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.markera)));

                map.addMarker(new MarkerOptions().position(end)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.markerb)));

                String TotalDistance = gd.getTotalDistanceText(doc);
                String TotalDuration = gd.getTotalDurationText(doc);
            }
        });

        gd.request(start, end, GoogleDirection.MODE_DRIVING);
    }
}

Mockito, JUnit and Spring

Your question seems to be asking about which of the three examples you have given is the preferred approach.

Example 1 using the Reflection TestUtils is not a good approach for Unit testing. You really don't want to be loading the spring context at all for a unit test. Just mock and inject what is required as shown by your other examples.

You do want to load the spring context if you want to do some Integration testing, however I would prefer using @RunWith(SpringJUnit4ClassRunner.class) to perform the loading of the context along with @Autowired if you need access to its' beans explicitly.

Example 2 is a valid approach and the use of @RunWith(MockitoJUnitRunner.class) will remove the need to specify a @Before method and an explicit call to MockitoAnnotations.initMocks(this);

Example 3 is another valid approach that doesn't use @RunWith(...). You haven't instantiated your class under test HelloFacadeImpl explicitly, but you could have done the same with Example 2.

My suggestion is to use Example 2 for your unit testing as it reduces the code clutter. You can fall back to the more verbose configuration if and when you're forced to do so.

How do you express binary literals in Python?

I've tried this in Python 3.6.9

Convert Binary to Decimal

>>> 0b101111
47

>>> int('101111',2)
47

Convert Decimal to binary

>>> bin(47)
'0b101111'

Place a 0 as the second parameter python assumes it as decimal.

>>> int('101111',0)
101111

How to change the font color in the textbox in C#?

Assuming WinForms, the ForeColor property allows to change all the text in the TextBox (not just what you're about to add):

TextBox.ForeColor = Color.Red;

To only change the color of certain words, look at RichTextBox.

Correct use of flush() in JPA/Hibernate

Can em.flush() cause any harm when using it within a transaction?

Yes, it may hold locks in the database for a longer duration than necessary.

Generally, When using JPA you delegates the transaction management to the container (a.k.a CMT - using @Transactional annotation on business methods) which means that a transaction is automatically started when entering the method and commited / rolled back at the end. If you let the EntityManager handle the database synchronization, sql statements execution will be only triggered just before the commit, leading to short lived locks in database. Otherwise your manually flushed write operations may retain locks between the manual flush and the automatic commit which can be long according to remaining method execution time.

Notes that some operation automatically triggers a flush : executing a native query against the same session (EM state must be flushed to be reachable by the SQL query), inserting entities using native generated id (generated by the database, so the insert statement must be triggered thus the EM is able to retrieve the generated id and properly manage relationships)

Git ignore file for Xcode projects

I've added:

xcuserstate
xcsettings

and placed my .gitignore file at the root of my project.

After committing and pushing. I then ran:

git rm --cached UserInterfaceState.xcuserstate WorkspaceSettings.xcsettings

buried with the folder below:

<my_project_name>/<my_project_name>.xcodeproj/project.xcworkspace/xcuserdata/<my_user_name>.xcuserdatad/

I then ran git commit and push again

Disable and enable buttons in C#

button2.Enabled == true ; must be button2.Enabled = true ;.

You have a compare == where you should have an assign =.

Update int column in table with unique incrementing values

Try something like this:

with toupdate as (
    select p.*,
           (coalesce(max(interfaceid) over (), 0) +
            row_number() over (order by (select NULL))
           ) as newInterfaceId
    from prices
   )
update p
    set interfaceId = newInterfaceId
    where interfaceId is NULL

This doesn't quite make them consecutive, but it does assign new higher ids. To make them consecutive, try this:

with toupdate as (
    select p.*,
           (coalesce(max(interfaceid) over (), 0) +
            row_number() over (partition by interfaceId order by (select NULL))
           ) as newInterfaceId
    from prices
   )
update p
    set interfaceId = newInterfaceId
    where interfaceId is NULL

Redirect to an external URL from controller action in Spring MVC

In short "redirect://yahoo.com" will lend you to yahoo.com.

where as "redirect:yahoo.com" will lend you your-context/yahoo.com ie for ex- localhost:8080/yahoo.com

Reading a column from CSV file using JAVA

If you are using Java 7+, you may want to use NIO.2, e.g.:

Code:

public static void main(String[] args) throws Exception {

    File file = new File("test.csv");

    List<String> lines = Files.readAllLines(file.toPath(), 
            StandardCharsets.UTF_8);

    for (String line : lines) {
        String[] array = line.split(",", -1);
        System.out.println(array[0]);
    }

}

Output:

a
1RW
1RW
1RW
1RW
1RW
1RW
1R1W
1R1W
1R1W

How to get indices of a sorted array in Python

Import numpy as np

FOR INDEX

S=[11,2,44,55,66,0,10,3,33]

r=np.argsort(S)

[output]=array([5, 1, 7, 6, 0, 8, 2, 3, 4])

argsort Returns the indices of S in sorted order

FOR VALUE

np.sort(S)

[output]=array([ 0,  2,  3, 10, 11, 33, 44, 55, 66])

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

DELETE TB1, TB2
    FROM customer_details
        LEFT JOIN customer_booking on TB1.cust_id = TB2.fk_cust_id
    WHERE TB1.cust_id = $id

Defining a `required` field in Bootstrap

Form validation can be enabled in markup via the data-api or via JavaScript. Automatically enable form validation by adding data-toggle="validator" to your form element.

<form role="form" data-toggle="validator">
   ...
</form>

Or activate validation via JavaScript:

$('#myForm').validator()

and you need to use required flag in input field

For more details Click Here

How can I get the Windows last reboot reason

This article explains in detail how to find the reason for last startup/shutdown. In my case, this was due to windows SCCM pushing updates even though I had it disabled locally. Visit the article for full details with pictures. For reference, here are the steps copy/pasted from the website:

  1. Press the Windows + R keys to open the Run dialog, type eventvwr.msc, and press Enter.

  2. If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).

  3. In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on System, and click/tap on Filter Current Log.

  4. Do either step 5 or 6 below for what shutdown events you would like to see.

  5. To See the Dates and Times of All User Shut Downs of the Computer

    A) In Event sources, click/tap on the drop down arrow and check the USER32 box.

    B) In the All Event IDs field, type 1074, then click/tap on OK.

    C) This will give you a list of power off (shutdown) and restart Shutdown Type of events at the top of the middle pane in Event Viewer.

    D) You can scroll through these listed events to find the events with power off as the Shutdown Type. You will notice the date and time, and what user was responsible for shutting down the computer per power off event listed.

    E) Go to step 7.

  6. To See the Dates and Times of All Unexpected Shut Downs of the Computer

    A) In the All Event IDs field, type 6008, then click/tap on OK.

    B) This will give you a list of unexpected shutdown events at the top of the middle pane in Event Viewer. You can scroll through these listed events to see the date and time of each one.

How do you add multi-line text to a UIButton?

If you use auto-layout on iOS 6 you might also need to set the preferredMaxLayoutWidth property:

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
button.titleLabel.preferredMaxLayoutWidth = button.frame.size.width;

How many concurrent requests does a single Flask process receive?

When running the development server - which is what you get by running app.run(), you get a single synchronous process, which means at most 1 request is being processed at a time.

By sticking Gunicorn in front of it in its default configuration and simply increasing the number of --workers, what you get is essentially a number of processes (managed by Gunicorn) that each behave like the app.run() development server. 4 workers == 4 concurrent requests. This is because Gunicorn uses its included sync worker type by default.

It is important to note that Gunicorn also includes asynchronous workers, namely eventlet and gevent (and also tornado, but that's best used with the Tornado framework, it seems). By specifying one of these async workers with the --worker-class flag, what you get is Gunicorn managing a number of async processes, each of which managing its own concurrency. These processes don't use threads, but instead coroutines. Basically, within each process, still only 1 thing can be happening at a time (1 thread), but objects can be 'paused' when they are waiting on external processes to finish (think database queries or waiting on network I/O).

This means, if you're using one of Gunicorn's async workers, each worker can handle many more than a single request at a time. Just how many workers is best depends on the nature of your app, its environment, the hardware it runs on, etc. More details can be found on Gunicorn's design page and notes on how gevent works on its intro page.

Warning: comparison with string literals results in unspecified behaviour

There is a distinction between 'a' and "a":

  • 'a' means the value of the character a.
  • "a" means the address of the memory location where the string "a" is stored (which will generally be in the data section of your program's memory space). At that memory location, you will have two bytes -- the character 'a' and the null terminator for the string.

Getting the .Text value from a TextBox

if(sender is TextBox) {
 var text = (sender as TextBox).Text;
}

How to create a POJO?

When you aren't doing anything to make your class particularly designed to work with a given framework, ORM, or other system that needs a special sort of class, you have a Plain Old Java Object, or POJO.

Ironically, one of the reasons for coining the term is that people were avoiding them in cases where they were sensible and some people concluded that this was because they didn't have a fancy name. Ironic, because your question demonstrates that the approach worked.

Compare the older POD "Plain Old Data" to mean a C++ class that doesn't do anything a C struct couldn't do (more or less, non-virtual members that aren't destructors or trivial constructors don't stop it being considered POD), and the newer (and more directly comparable) POCO "Plain Old CLR Object" in .NET.

text-overflow: ellipsis not working

You may try using ellipsis by adding the following in CSS:

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

But it seems like this code just applies to one-line trim. More ways to trim text and show ellipsis can be found in this website: http://blog.sanuker.com/?p=631

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Process GET parameters

The <f:viewParam> manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>, but then for GET parameters.

The following example

<f:metadata>
    <f:viewParam name="id" value="#{bean.id}" />
</f:metadata>

does basically the following:

  • Get the request parameter value by name id.
  • Convert and validate it if necessary (you can use required, validator and converter attributes and nest a <f:converter> and <f:validator> in it like as with <h:inputText>)
  • If conversion and validation succeeds, then set it as a bean property represented by #{bean.id} value, or if the value attribute is absent, then set it as request attribtue on name id so that it's available by #{id} in the view.

So when you open the page as foo.xhtml?id=10 then the parameter value 10 get set in the bean this way, right before the view is rendered.

As to validation, the following example sets the param to required="true" and allows only values between 10 and 20. Any validation failure will result in a message being displayed.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
</f:metadata>
<h:message for="id" />

Performing business action on GET parameters

You can use the <f:viewAction> for this.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
    <f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />

with

public void onload() {
    // ...
}

The <f:viewAction> is however new since JSF 2.2 (the <f:viewParam> already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event> instead.

<f:event type="preRenderView" listener="#{bean.onload}" />

This is however invoked on every request. You need to explicitly check if the request isn't a postback:

public void onload() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        // ...
    }
}

When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:

public void onload() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
        // ...
    }
}

Using <f:event> this way is in essence a workaround/hack, that's exactly why the <f:viewAction> was introduced in JSF 2.2.


Pass view parameters to next view

You can "pass-through" the view parameters in navigation links by setting includeViewParams attribute to true or by adding includeViewParams=true request parameter.

<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">

which generates with the above <f:metadata> example basically the following link

<a href="next.xhtml?id=10">

with the original parameter value.

This approach only requires that next.xhtml has also a <f:viewParam> on the very same parameter, otherwise it won't be passed through.


Use GET forms in JSF

The <f:viewParam> can also be used in combination with "plain HTML" GET forms.

<f:metadata>
    <f:viewParam id="query" name="query" value="#{bean.query}" />
    <f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
    <label for="query">Query</label>
    <input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
    <input type="submit" value="Search" />
    <h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
     ...
</h:dataTable>

With basically this @RequestScoped bean:

private String query;
private List<Result> results;

public void search() {
    results = service.search(query);
}

Note that the <h:message> is for the <f:viewParam>, not the plain HTML <input type="text">! Also note that the input value displays #{param.query} when #{bean.query} is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).


See also:

How to generate a random number between 0 and 1?

double r2()
{
   return (rand() % 10001) / 10000.0;
}

Android Color Picker

If you want a fragment solution, I have made a fork of android-color-picker where DialogFragment is used and is re-created on configuration change. Here's the link: https://github.com/lomza/android-color-picker

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

fade's answer worked for me. I moved from 8.0.30 to 8.5.5 and the difference was the valve in <8.0.30>/manager/META-INF/context.xml was already commented out from the tar file but was uncommented in 8.5.5 tar.

I failed to read this important message in the 403 response:

By default the Manager is only accessible from a browser running on the same machine as Tomcat. If you wish to modify this restriction, you'll need to edit the Manager's context.xml file.

And failed to read this too:

Since r1734267 a RemoteAddrValve.is configured by default in Manager and HostManager web applications. This feature is present in 9.0.0.M4 and 8.5.0 onwards.

https://bz.apache.org/bugzilla/show_bug.cgi?id=59672

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

Don't check. Go ahead and assume that it is the right input, and catch an exception if it isn't.

intresult = None
while intresult is None:
    input = raw_input()
    try: intresult = int(input)
    except ValueError: pass

ADB - Android - Getting the name of the current activity

Android Q broke most of these for me. Here's a new one that seems to be working (at least on Android Q).

adb shell "dumpsys activity activities | grep mResumedActivity"

Output looks like:

mResumedActivity: ActivityRecord{7f6df99 u0 com.sample.app/.feature.SampleActivity t92}

Edit: Works on Android R for me as well

Array vs ArrayList in performance

I agree with somebody's recently deleted post that the differences in performance are so small that, with very very few exceptions, (he got dinged for saying never) you should not make your design decision based upon that.

In your example, where the elements are Objects, the performance difference should be minimal.

If you are dealing with a large number of primitives, an array will offer significantly better performance, both in memory and time.

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

How can I listen to the form submit event in javascript?

Why do people always use jQuery when it isn't necessary?
Why can't people just use simple JavaScript?

var ele = /*Your Form Element*/;
if(ele.addEventListener){
    ele.addEventListener("submit", callback, false);  //Modern browsers
}else if(ele.attachEvent){
    ele.attachEvent('onsubmit', callback);            //Old IE
}

callback is a function that you want to call when the form is being submitted.

About EventTarget.addEventListener, check out this documentation on MDN.

To cancel the native submit event (prevent the form from being submitted), use .preventDefault() in your callback function,

document.querySelector("#myForm").addEventListener("submit", function(e){
    if(!isValid){
        e.preventDefault();    //stop form from submitting
    }
});

Listening to the submit event with libraries

If for some reason that you've decided a library is necessary (you're already using one or you don't want to deal with cross-browser issues), here's a list of ways to listen to the submit event in common libraries:

  1. jQuery

    $(ele).submit(callback);
    

    Where ele is the form element reference, and callback being the callback function reference. Reference

_x000D_
_x000D_
    <iframe width="100%" height="100%" src="http://jsfiddle.net/DerekL/wnbo1hq0/show" frameborder="0"></iframe>
_x000D_
_x000D_
_x000D_

  1. AngularJS (1.x)

    <form ng-submit="callback()">
    
    $scope.callback = function(){ /*...*/ };
    

    Very straightforward, where $scope is the scope provided by the framework inside your controller. Reference

  2. React

    <form onSubmit={this.handleSubmit}>
    
    class YourComponent extends Component {
        // stuff
    
        handleSubmit(event) {
            // do whatever you need here
    
            // if you need to stop the submit event and 
            // perform/dispatch your own actions
            event.preventDefault();
        }
    
        // more stuff
    }
    

    Simply pass in a handler to the onSubmit prop. Reference

  3. Other frameworks/libraries

    Refer to the documentation of your framework.


Validation

You can always do your validation in JavaScript, but with HTML5 we also have native validation.

<!-- Must be a 5 digit number -->
<input type="number" required pattern="\d{5}">

You don't even need any JavaScript! Whenever native validation is not supported, you can fallback to a JavaScript validator.

Demo: http://jsfiddle.net/DerekL/L23wmo1L/

iPhone: How to get current milliseconds?

CFAbsoluteTimeGetCurrent()

Absolute time is measured in seconds relative to the absolute reference date of Jan 1 2001 00:00:00 GMT. A positive value represents a date after the reference date, a negative value represents a date before it. For example, the absolute time -32940326 is equivalent to December 16th, 1999 at 17:54:34. Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.

How to change Oracle default data pump directory to import dumpfile?

I want change default directory dumpfile.

You could create a new directory and give it required privileges, for example:

SQL> CREATE DIRECTORY dmpdir AS '/opt/oracle';
Directory created.

SQL> GRANT read, write ON DIRECTORY dmpdir TO scott;
Grant succeeded.

To use the newly created directory, you could just add it as a parameter:

DIRECTORY=dmpdir

Oracle introduced a default directory from 10g R2, called DATA_PUMP_DIR, that can be used. To check the location, you could look into dba_directories:

SQL> select DIRECTORY_NAME, DIRECTORY_PATH from dba_directories where DIRECTORY_NAME = 'DATA_PUMP_DIR';

DIRECTORY_NAME       DIRECTORY_PATH
-------------------- --------------------------------------------------
DATA_PUMP_DIR        C:\app\Lalit/admin/orcl/dpdump/

SQL>

Fatal error: Call to undefined function imap_open() in PHP

On Mac OS X with Homebrew, as obviously, PHP is already installed due to provided error we cannot run:

Update: Tha latest version brew instal php --with-imap will not work any more!!!

$ brew install php72 --with-imap
Warning: homebrew/php/php72 7.2.xxx is already installed

Also, installing module only, here will not work:

$ brew install php72-imap
Error: No available formula with the name "php72-imap"

So, we must reinstall it:

$ brew reinstall php72 --with-imap

It will take a while :-) (built in 8 minutes 17 seconds)

document.body.appendChild(i)

You can appendChild to document.body but not if the document hasn't been loaded. So you should put everything in:

window.onload=function(){
    //your code
}

This works or you can make appendChild to be dependent on something else like another event for eg.

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_body_append

As a matter of fact you can try changing the innerHTML of the document.body it works...!

Get the last day of the month in SQL

Works in SQL server

Declare @GivenDate datetime
SET @GivenDate = GETDATE()

Select DATEADD(MM,DATEDIFF(MM, 0, @GivenDate),0) --First day of the month 

Select DATEADD(MM,DATEDIFF(MM, -1, @GivenDate),-1) --Last day of the month

What is the best workaround for the WCF client `using` block issue?

I wrote a higher order function to make it work right. We've used this in several projects and it seems to work great. This is how things should have been done from the start, without the "using" paradigm or so on.

TReturn UseService<TChannel, TReturn>(Func<TChannel, TReturn> code)
{
    var chanFactory = GetCachedFactory<TChannel>();
    TChannel channel = chanFactory.CreateChannel();
    bool error = true;
    try {
        TReturn result = code(channel);
        ((IClientChannel)channel).Close();
        error = false;
        return result;
    }
    finally {
        if (error) {
            ((IClientChannel)channel).Abort();
        }
    }
}

You can make calls like this:

int a = 1;
int b = 2;
int sum = UseService((ICalculator calc) => calc.Add(a, b));
Console.WriteLine(sum);

This is pretty much just like you have in your example. In some projects, we write strongly typed helper methods, so we end up writing things like "Wcf.UseFooService(f=>f...)".

I find it quite elegant, all things considered. Is there a particular problem you encountered?

This allows other nifty features to be plugged in. For instance, on one site, the site authenticates to the service on behalf of the logged in user. (The site has no credentials by itself.) By writing our own "UseService" method helper, we can configure the channel factory the way we want, etc. We're also not bound to using the generated proxies -- any interface will do.

What is the purpose of "&&" in a shell command?

####################### && or (Logical AND) ######################
first_command="1"
two_command="2"

if [[ ($first_command == 1) && ($two_command == 2)]];then
 echo "Equal"
fi

When program checks if command, then the program creates a number called exit code, if both conditions are true, exit code is zero (0), otherwise, exit code is positive number. only when displaying Equal if exit code is produced zero (0) that means both conditions are true.

javascript : sending custom parameters with window.open() but its not working

You can use this but there remains a security issue

<script type="text/javascript">
function fnc1()
{
    var a=window.location.href;

    username="p";
    password=1234;
    window.open(a+'?username='+username+'&password='+password,"");

}   
</script>
<input type="button" onclick="fnc1()" />
<input type="text" id="atext"  />

How to create multidimensional array

Quote taken from Data Structures and Algorithms with JavaScript

The Good Parts (O’Reilly, p. 64). Crockford extends the JavaScript array object with a function that sets the number of rows and columns and sets each value to a value passed to the function. Here is his definition:

Array.matrix = function(numrows, numcols, initial) {
    var arr = [];
    for (var i = 0; i < numrows; ++i) {
        var columns = [];
        for (var j = 0; j < numcols; ++j) {
            columns[j] = initial;
        }
        arr[i] = columns;
    }
    return arr;
}

Here is some code to test the definition:

var nums = Array.matrix(5,5,0);
print(nums[1][1]); // displays 0
var names = Array.matrix(3,3,"");
names[1][2] = "Joe";
print(names[1][2]); // display "Joe"

We can also create a two-dimensional array and initialize it to a set of values in one line:

var grades = [[89, 77, 78],[76, 82, 81],[91, 94, 89]];
print(grades[2][2]); // displays 89

Install / upgrade gradle on Mac OS X

As mentioned in this tutorial, it's as simple as:

To install

brew install gradle

To upgrade

brew upgrade gradle

(using Homebrew of course)

Also see (finally) updated docs.

Cheers :)!

How to get MAC address of client using PHP?

//Simple & effective way to get client mac address
// Turn on output buffering
ob_start();
//Get the ipconfig details using system commond
system('ipconfig /all');

// Capture the output into a variable

    $mycom=ob_get_contents();

// Clean (erase) the output buffer

    ob_clean();

$findme = "Physical";
//Search the "Physical" | Find the position of Physical text
$pmac = strpos($mycom, $findme);

// Get Physical Address
$mac=substr($mycom,($pmac+36),17);
//Display Mac Address
echo $mac;

How to run SQL script in MySQL?

From linux 14.04 to MySql 5.7, using cat command piped with mysql login:

cat /Desktop/test.sql | sudo mysql -uroot -p 

You can use this method for many MySQL commands to execute directly from Shell. Eg:

echo "USE my_db; SHOW tables;" | sudo mysql -uroot -p 

Make sure you separate your commands with semicolon (';').

I didn't see this approach in the answers above and thought it is a good contribution.

how to add new <li> to <ul> onclick with javascript

First you have to create a li(with id and value as you required) then add it to your ul.

Javascript ::

addAnother = function() {
    var ul = document.getElementById("list");
    var li = document.createElement("li");
    var children = ul.children.length + 1
    li.setAttribute("id", "element"+children)
    li.appendChild(document.createTextNode("Element "+children));
    ul.appendChild(li)
}

Check this example that add li element to ul.

How to print an exception in Python 3?

These are the changes since python 2:

    try:
        1 / 0
    except Exception as e: # (as opposed to except Exception, e:)
                           # ^ that will just look for two classes, Exception and e
        # for the repr
        print(repr(e))
        # for just the message, or str(e), since print calls str under the hood
        print(e)
        # the arguments that the exception has been called with. 
        # the first one is usually the message. (OSError is different, though)
        print(e.args)

You can look into the standard library module traceback for fancier stuff.

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

How do I import a sql data file into SQL Server?

  1. Start SQL Server Management Studio
  2. Connect to your database
  3. File > Open > File and pick your file
  4. Execute it

How to save a pandas DataFrame table as a png

As jcdoming suggested, use Seaborn heatmap():

import seaborn as sns
import matplotlib.pyplot as plt

fig = plt.figure(facecolor='w', edgecolor='k')
sns.heatmap(df.head(), annot=True, cmap='viridis', cbar=False)
plt.savefig('DataFrame.png')

DataFrame as a heat map

Popup Message boxes

import javax.swing.*;
class Demo extends JFrame
{
           String str1;
           Demo(String s1)
           {
             str1=s1;
            JOptionPane.showMessageDialog(null,"your message : "+str1);
            }
            public static void main (String ar[])
            {
             new Demo("Java");
            }
}

How can I print a quotation mark in C?

#include<stdio.h>
int main(){
char ch='"';
printf("%c",ch);
return 0;
}

Output: "

Useful example of a shutdown hook in Java?

You could do the following:

  • Let the shutdown hook set some AtomicBoolean (or volatile boolean) "keepRunning" to false
  • (Optionally, .interrupt the working threads if they wait for data in some blocking call)
  • Wait for the working threads (executing writeBatch in your case) to finish, by calling the Thread.join() method on the working threads.
  • Terminate the program

Some sketchy code:

  • Add a static volatile boolean keepRunning = true;
  • In run() you change to

    for (int i = 0; i < N && keepRunning; ++i)
        writeBatch(pw, i);
    
  • In main() you add:

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            keepRunning = false;
            mainThread.join();
        }
    });
    

That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.


From the docs:

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

If you are building the code yourself, then this issue could be overcome by giving "-target 1.5" to the java compiler (or by setting the corresponding option in your IDE or your build config).

scrollTop animation without jquery

HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript (linear):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollY will be -Infinity
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript (ease in and out):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollCount will be Infinity
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall (see below)
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  - newTimestamp - oldTimestamp equals the delta time

    a * cos (bx + c) + d                        | c translates along the x axis = 0
  = a * cos (bx) + d                            | d translates along the y axis = 1 -> only positive y values
  = a * cos (bx) + 1                            | a stretches along the y axis = cosParameter = window.scrollY / 2
  = cosParameter + cosParameter * (cos bx)  | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
  = cosParameter + cosParameter * (cos scrollCount * x)
*/

Note:

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

enter image description here

3# Simple scrolling library on Github

Using if-else in JSP

It's almost always advisable to not use scriptlets in your JSP. They're considered bad form. Instead, try using JSTL (JSP Standard Tag Library) combined with EL (Expression Language) to run the conditional logic you're trying to do. As an added benefit, JSTL also includes other important features like looping.

Instead of:

<%String user=request.getParameter("user"); %>
<%if(user == null || user.length() == 0){
    out.print("I see! You don't have a name.. well.. Hello no name");   
}
else {%>
    <%@ include file="response.jsp" %>
<% } %>

Use:

<c:choose>
    <c:when test="${empty user}">
        I see!  You don't have a name.. well.. Hello no name
    </c:when>
    <c:otherwise>
        <%@ include file="response.jsp" %>
    </c:otherwise>
</c:choose>

Also, unless you plan on using response.jsp somewhere else in your code, it might be easier to just include the html in your otherwise statement:

<c:otherwise>
    <h1>Hello</h1>
    ${user}
</c:otherwise>

Also of note. To use the core tag, you must import it as follows:

 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

You want to make it so the user will receive a message when the user submits a username. The easiest way to do this is to not print a message at all when the "user" param is null. You can do some validation to give an error message when the user submits null. This is a more standard approach to your problem. To accomplish this:

In scriptlet:

<% String user = request.getParameter("user");
   if( user != null && user.length() > 0 ) {
       <%@ include file="response.jsp" %>
   }
%>

In jstl:

<c:if test="${not empty user}">
    <%@ include file="response.jsp" %>
</c:if>

How can I start an interactive console for Perl?

You can use the perl debugger on a trivial program, like so:

perl -de1

Alternatively there's Alexis Sukrieh's Perl Console application, but I haven't used it.

How do I get interactive plots again in Spyder/IPython/matplotlib?

You can quickly control this by typing built-in magic commands in Spyder's IPython console, which I find faster than picking these from the preferences menu. Changes take immediate effect, without needing to restart Spyder or the kernel.

To switch to "automatic" (i.e. interactive) plots, type:

%matplotlib auto

then if you want to switch back to "inline", type this:

%matplotlib inline

(Note: these commands don't work in non-IPython consoles)

See more background on this topic: Purpose of "%matplotlib inline"

How to change button color with tkinter

When you do self.button = Button(...).grid(...), what gets assigned to self.button is the result of the grid() command, not a reference to the Button object created.

You need to assign your self.button variable before packing/griding it. It should look something like this:

self.button = Button(self,text="Click Me",command=self.color_change,bg="blue")
self.button.grid(row = 2, column = 2, sticky = W)

How to make tesseract to recognize only numbers, when they are mixed with letters?

I made it a bit different (with tess-two). Maybe it will be useful for somebody.

So you need to initialize first the API.

TessBaseAPI baseApi = new TessBaseAPI();
baseApi.init(datapath, language, ocrEngineMode);

Then set the following variables

baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_LINE);
baseApi.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST, "!?@#$%&*()<>_-+=/:;'\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
baseApi.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, ".,0123456789");
baseApi.setVariable("classify_bln_numeric_mode", "1");

In this way the engine will check only the numbers.

get all the elements of a particular form

How would you like to differentiate between forms? You can use different IDs, and then use this function:

function getInputElements(formId) {
    var form = document.getElementById(formId);
    if (form === null) {
        return null;
    }
    return form.getElementsByTagName('input');
}

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

try :

mvn install:install-file -DgroupId=jdk.tools -DartifactId=jdk.tools -Dversion=1.6 -Dpackaging=jar -Dfile="C:\Program Files\Java\jdk\lib\tools.jar"

also check : http://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html

Most common C# bitwise operations on enums

C++ operations are: & | ^ ~ (for and, or, xor and not bitwise operations). Also of interest are >> and <<, which are bitshift operations.

So, to test for a bit being set in a flag, you would use: if (flags & 8) //tests bit 4 has been set

How can I create an executable JAR with dependencies using Maven?

There are millions of answers already, I wanted to add you don't need <mainClass> if you don't need to add entryPoint to your application. For example APIs may not have necessarily have main method.

maven plugin config

  <build>
    <finalName>log-enrichment</finalName>
    <plugins>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
    </plugins>
  </build>

build

mvn clean compile assembly:single

verify

ll target/
total 35100
drwxrwx--- 1 root vboxsf     4096 Sep 29 16:25 ./
drwxrwx--- 1 root vboxsf     4096 Sep 29 16:25 ../
drwxrwx--- 1 root vboxsf        0 Sep 29 16:08 archive-tmp/
drwxrwx--- 1 root vboxsf        0 Sep 29 16:25 classes/
drwxrwx--- 1 root vboxsf        0 Sep 29 16:25 generated-sources/
drwxrwx--- 1 root vboxsf        0 Sep 29 16:25 generated-test-sources/
-rwxrwx--- 1 root vboxsf 35929841 Sep 29 16:10 log-enrichment-jar-with-dependencies.jar*
drwxrwx--- 1 root vboxsf        0 Sep 29 16:08 maven-status/

Max retries exceeded with URL in requests

Adding my own experience for those who are experiencing this in the future. My specific error was

Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known'

It turns out that this was actually because I had reach the maximum number of open files on my system. It had nothing to do with failed connections, or even a DNS error as indicated.

Retrieving the first digit of a number

Integer.parseInt will take a string and return a int.

Creating an IFRAME using JavaScript

You can use:

<script type="text/javascript">
    function prepareFrame() {
        var ifrm = document.createElement("iframe");
        ifrm.setAttribute("src", "http://google.com/");
        ifrm.style.width = "640px";
        ifrm.style.height = "480px";
        document.body.appendChild(ifrm);
    }
</script> 

also check basics of the iFrame element

Taking multiple inputs from user in python

Try this:

print ("Enter the Five Numbers with Comma")

k=[x for x in input("Enter Number:").split(',')]

for l in k:
    print (l)

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

This error might also occur due to proxy settings, once check that your proxy allow the access to npm commands.

It worked for me quite well.

How to use comparison operators like >, =, < on BigDecimal

Every object of the Class BigDecimal has a method compareTo you can use to compare it to another BigDecimal. The result of compareTo is then compared > 0, == 0 or < 0 depending on what you need. Read the documentation and you will find out.

The operators ==, <, > and so on can only be used on primitive data types like int, long, double or their wrapper classes like Integerand Double.

From the documentation of compareTo:

Compares this BigDecimal with the specified BigDecimal.

Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.

Returns: -1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.

How to force IE to reload javascript?

In javascript I think that it is not possible, because modern browsers have a policy on security in javascripts.. and clearing the cache is a very violating one.

You can try to add

<META HTTP-EQUIV="Pragma" CONTENT="no-cache">

In your header, but you will have performance loss.

How to add Class in <li> using wp_nav_menu() in Wordpress?

None of these responses really seem to answer the question. Here's something similar to what I'm utilizing on a site of mine by targeting a menu item by its title/name:

function add_class_to_menu_item($sorted_menu_objects, $args) {
    $theme_location = 'primary_menu';  // Name, ID, or Slug of the target menu location
    $target_menu_title = 'Link';  // Name/Title of the menu item you want to target
    $class_to_add = 'my_own_class';  // Class you want to add

    if ($args->theme_location == $theme_location) {
        foreach ($sorted_menu_objects as $key => $menu_object) {
            if ($menu_object->title == $target_menu_title) {
                $menu_object->classes[] = $class_to_add;
                break; // Optional.  Leave if you're only targeting one specific menu item
            }
        }
    }

    return $sorted_menu_objects;
}
add_filter('wp_nav_menu_objects', 'add_class_to_menu_item', 10, 2);

Check whether user has a Chrome extension installed

I used the cookie method:

In my manifest.js file I included a content script that only runs on my site:

 "content_scripts": [
        {
        "matches": [
            "*://*.mysite.co/*"
            ],
        "js": ["js/mysite.js"],
        "run_at": "document_idle"
        }
    ], 

in my js/mysite.js I have one line:

document.cookie = "extension_downloaded=True";

and in my index.html page I look for that cookie.

if (document.cookie.indexOf('extension_downloaded') != -1){
    document.getElementById('install-btn').style.display = 'none';
}

Draw a connecting line between two elements

I also had the same requirement few days back

I used an full width and height svg and added it below all my divs and added lines to these svg dynamically.

Checkout the how I did it here using svg

HTML

<div id="ui-browser"><div class="anchor"></div>
     <div id="control-library" class="library">
       <div class="name-title">Control Library</div>
       <ul>
         <li>Control A</li>
         <li>Control B</li>
         <li>Control C</li>
         <li>Control D</li>
       </ul>
     </div><!--
--></div><!--
--><div id="canvas">
     <svg id='connector_canvas'></svg>
     <div class="ui-item item-1"><div class="con_anchor"></div></div>
     <div class="ui-item item-2"><div class="con_anchor"></div></div>
     <div class="ui-item item-3"><div class="con_anchor"></div></div>
     <div class="ui-item item-1"><div class="con_anchor"></div></div>
     <div class="ui-item item-2"><div class="con_anchor"></div></div>
     <div class="ui-item item-3"><div class="con_anchor"></div></div>
   </div><!--
--><div id="property-browser"></div>

https://jsfiddle.net/kgfamo4b/

    $('.anchor').on('click',function(){
   var width = parseInt($(this).parent().css('width'));
   if(width==10){
     $(this).parent().css('width','20%');
     $('#canvas').css('width','60%');
   }else{
      $(this).parent().css('width','10px');
     $('#canvas').css('width','calc( 80% - 10px)');
   }
});

$('.ui-item').draggable({
  drag: function( event, ui ) {
           var lines = $(this).data('lines');
           var con_item =$(this).data('connected-item');
           var con_lines = $(this).data('connected-lines');

           if(lines) {
             lines.forEach(function(line,id){
                    $(line).attr('x1',$(this).position().left).attr('y1',$(this).position().top+1);  
             }.bind(this));
           }

           if(con_lines){
               con_lines.forEach(function(con_line,id){
                  $(con_line).attr('x2',$(this).position().left)
                        .attr('y2',$(this).position().top+(parseInt($(this).css('height'))/2)+(id*5));
               }.bind(this));

           }

       }
});

$('.ui-item').droppable({
  accept: '.con_anchor',
  drop: function(event,ui){
     var item = ui.draggable.closest('.ui-item');
     $(this).data('connected-item',item);
     ui.draggable.css({top:-2,left:-2});
     item.data('lines').push(item.data('line'));

     if($(this).data('connected-lines')){
        $(this).data('connected-lines').push(item.data('line'));

         var y2_ = parseInt(item.data('line').attr('y2'));
         item.data('line').attr('y2',y2_+$(this).data('connected-lines').length*5);

     }else $(this).data('connected-lines',[item.data('line')]);

     item.data('line',null);
    console.log('dropped');
  }
});


$('.con_anchor').draggable({drag: function( event, ui ) {
     var _end = $(event.target).parent().position();
     var end = $(event.target).position();
     if(_end&&end)  
     $(event.target).parent().data('line')
                                                    .attr('x2',end.left+_end.left+5).attr('y2',end.top+_end.top+2);
},stop: function(event,ui) {
        if(!ui.helper.closest('.ui-item').data('line')) return;
        ui.helper.css({top:-2,left:-2});
        ui.helper.closest('.ui-item').data('line').remove();
        ui.helper.closest('.ui-item').data('line',null);
        console.log('stopped');
      }
});


$('.con_anchor').on('mousedown',function(e){
    var cur_ui_item = $(this).closest('.ui-item');
    var connector = $('#connector_canvas');
    var cur_con;

  if(!$(cur_ui_item).data('lines')) $(cur_ui_item).data('lines',[]);

  if(!$(cur_ui_item).data('line')){
         cur_con = $(document.createElementNS('http://www.w3.org/2000/svg','line'));
         cur_ui_item.data('line',cur_con);
    } else cur_con = cur_ui_item.data('line');

    connector.append(cur_con);
    var start = cur_ui_item.position();
     cur_con.attr('x1',start.left).attr('y1',start.top+1);
     cur_con.attr('x2',start.left+1).attr('y2',start.top+1);
});

What is getattr() exactly and how do I use it?

I think this example is self explanatory. It runs the method of first parameter, whose name is given in the second parameter.

class MyClass:
   def __init__(self):
      pass
   def MyMethod(self):
      print("Method ran")

# Create an object
object = MyClass()
# Get all the methods of a class
method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# You can use any of the methods in method_list
# "MyMethod" is the one we want to use right now

# This is the same as running "object.MyMethod()"
getattr(object,'MyMethod')()

Use JavaScript to place cursor at end of text in text input element

Try this one works with Vanilla JavaScript.

<input type="text" id="yourId" onfocus=" let value = this.value; this.value = null; this.value=value" name="nameYouWant" class="yourClass" value="yourValue" placeholder="yourPlaceholder...">

In Js

document.getElementById("yourId").focus()

Disable HttpClient logging

This worked for my tests;

java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(java.util.logging.Level.FINEST);
java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(java.util.logging.Level.FINEST);
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "ERROR");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "ERROR");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.headers", "ERROR");

Get item in the list in Scala?

Why parentheses?

Here is the quote from the book programming in scala.

Another important idea illustrated by this example will give you insight into why arrays are accessed with parentheses in Scala. Scala has fewer special cases than Java. Arrays are simply instances of classes like any other class in Scala. When you apply parentheses surrounding one or more values to a variable, Scala will transform the code into an invocation of a method named apply on that variable. So greetStrings(i) gets transformed into greetStrings.apply(i). Thus accessing an element of an array in Scala is simply a method call like any other. This principle is not restricted to arrays: any application of an object to some arguments in parentheses will be transformed to an apply method call. Of course this will compile only if that type of object actually defines an apply method. So it's not a special case; it's a general rule.

Here are a few examples how to pull certain element (first elem in this case) using functional programming style.

  // Create a multdimension Array 
  scala> val a = Array.ofDim[String](2, 3)
  a: Array[Array[String]] = Array(Array(null, null, null), Array(null, null, null))
  scala> a(0) = Array("1","2","3")
  scala> a(1) = Array("4", "5", "6")
  scala> a
  Array[Array[String]] = Array(Array(1, 2, 3), Array(4, 5, 6))

  // 1. paratheses
  scala> a.map(_(0))
  Array[String] = Array(1, 4)
  // 2. apply
  scala> a.map(_.apply(0))
  Array[String] = Array(1, 4)
  // 3. function literal
  scala> a.map(a => a(0))
  Array[String] = Array(1, 4)
  // 4. lift
  scala> a.map(_.lift(0))
  Array[Option[String]] = Array(Some(1), Some(4))
  // 5. head or last 
  scala> a.map(_.head)
  Array[String] = Array(1, 4)

Eloquent ORM laravel 5 Get Array of ids

read about the lists() method

$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()

How to set a radio button in Android

For radioButton use

radio1.setChecked(true);

It does not make sense to have just one RadioButton. If you have more of them you need to uncheck others through

radio2.setChecked(false); ...

If your setting is just on/off use CheckBox.

Flexbox Not Centering Vertically in IE

i have updated both fiddles. i hope it will make your work done.

centering

    html, body
{
    height: 100%;
    width: 100%;
}

body
{
    margin: 0;
}

.outer
{
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.inner
{
    width: 80%;
    margin: 0 auto;
}

center and scroll

html, body
    {
        height: 100%;
        width: 100%;
    }

    body
    {
        margin: 0;
        display:flex;
    }

    .outer
    {
        min-width: 100%;  
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .inner
    {
        width: 80%;
    margin-top:40px;
    margin: 0 auto;
    }

How to compare the contents of two string objects in PowerShell

You want to do $arrayOfString[0].Title -eq $myPbiject.item(0).Title

-match is for regex matching ( the second argument is a regex )

Count number of 1's in binary representation

I have actually done this using a bit of sleight of hand: a single lookup table with 16 entries will suffice and all you have to do is break the binary rep into nibbles (4-bit tuples). The complexity is in fact O(1) and I wrote a C++ template which was specialized on the size of the integer you wanted (in # bits)… makes it a constant expression instead of indetermined.

fwiw you can use the fact that (i & -i) will return you the LS one-bit and simply loop, stripping off the lsbit each time, until the integer is zero — but that’s an old parity trick.

Assigning out/ref parameters in Moq

I struggled with this for an hour this afternoon and could not find an answer anywhere. After playing around on my own with it I was able to come up with a solution which worked for me.

string firstOutParam = "first out parameter string";
string secondOutParam = 100;
mock.SetupAllProperties();
mock.Setup(m=>m.Method(out firstOutParam, out secondOutParam)).Returns(value);

The key here is mock.SetupAllProperties(); which will stub out all of the properties for you. This may not work in every test case scenario, but if all you care about is getting the return value of YourMethod then this will work fine.

TypeScript Objects as Dictionary types as in C#

You can use Record for this:

https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt

Example (A mapping between AppointmentStatus enum and some meta data):

  const iconMapping: Record<AppointmentStatus, Icon> = {
    [AppointmentStatus.Failed]: { Name: 'calendar times', Color: 'red' },
    [AppointmentStatus.Canceled]: { Name: 'calendar times outline', Color: 'red' },
    [AppointmentStatus.Confirmed]: { Name: 'calendar check outline', Color: 'green' },
    [AppointmentStatus.Requested]: { Name: 'calendar alternate outline', Color: 'orange' },
    [AppointmentStatus.None]: { Name: 'calendar outline', Color: 'blue' }
  }

Now with interface as value:

interface Icon { Name: string Color: string }

Usage:

const icon: SemanticIcon = iconMapping[appointment.Status]

How to make a loop in x86 assembly language?

You need to use conditional jmp commands. This isn't the same syntax as you're using; looks like MASM, but using GAS here's an example from some code I wrote to calculate gcd:

gcd_alg:
    subl    %ecx, %eax      /* a = a - c */
    cmpl    $0, %eax        /* if a == 0 */
    je      gcd_done        /* jump to end */
    cmpl    %ecx, %eax      /* if a < c */
    jl      gcd_preswap     /* swap and start over */
    jmp     gcd_alg         /* keep subtracting */

Basically, I compare two registers with the cmpl instruction (compare long). If it is less the JL (jump less) instruction jumps to the preswap location, otherwise it jumps back to the same label.

As for clearing the screen, that depends on the system you're using.

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

it worked for me after deleting and adding the server back.

Parse string to DateTime in C#

Try the following code

Month = Date = DateTime.Now.Month.ToString();   
Year = DateTime.Now.Year.ToString(); 
ViewBag.Today = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(Int32.Parse(Month)) + Year;

Radio Buttons "Checked" Attribute Not Working

also try this way

$('input:radio[name="name"][id="abcd'+no+'"]').attr("checked", "checked");

if there is <form /> tag then ("checked", true) otherwise ("checked", "checked")

Illegal mix of collations error in MySql

I also got same error, but in my case main problem was in where condition the parameter that i'm checking was having some unknown hidden character (+%A0)

When A0 convert I got 160 but 160 was out of the range of the character that db knows, that's why database cannot recognize it as character other thing is my table column is varchar

  • the solution that I did was I checked there is some characters like that and remove those before run the sql command

  • ex:- preg_replace('/\D/', '', $myParameter);

How do I redirect a user when a button is clicked?

$("#yourbuttonid").click(function(){ document.location = "<%= Url.Action("Youraction") %>";})

How can I convert an integer to a hexadecimal string in C?

Usually with printf (or one of its cousins) using the %x format specifier.

Can I set an unlimited length for maxJsonLength in web.config?

if, after implementing the above addition into your web.config, you get an “Unrecognized configuration section system.web.extensions.” error then try adding this to your web.config in the <ConfigSections> section:

            <sectionGroup name="system.web.extensions" type="System.Web.Extensions">
              <sectionGroup name="scripting" type="System.Web.Extensions">
                    <sectionGroup name="webServices" type="System.Web.Extensions">
                          <section name="jsonSerialization" type="System.Web.Extensions"/>
                    </sectionGroup>
              </sectionGroup>
        </sectionGroup>

Kill a postgresql session/connection

For me worked the following:

sudo gitlab-ctl stop
sudo gitlab-ctl start gitaly
sudo gitlab-rake gitlab:setup [type yes and let it finish]
sudo gitlab-ctl start

I am using:
gitlab_edition: "gitlab-ce"
gitlab_version: '12.4.0-ce.0.el7'

Why can't I display a pound (£) symbol in HTML?

You need to save your PHP script file in UTF-8 encoding, and leave the <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> in the HTML.

For text editor, I recommend Notepad++, because it can detect and display the actual encoding of the file (in the lower right corner of the editor), and you can convert it as well.

Checkout Jenkins Pipeline Git SCM with credentials?

For what it's worth adding to the discussion... what I did that ended up helping me... Since the pipeline is run within a workspace within a docker image that is cleaned up each time it runs. I grabbed the credentials needed to perform necessary operations on the repo within my pipeline and stored them in a .netrc file. this allowed me to authorize the git repo operations successfully.

withCredentials([usernamePassword(credentialsId: '<credentials-id>', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
    sh '''
        printf "machine github.com\nlogin $GIT_USERNAME\n password $GIT_PASSWORD" >> ~/.netrc
        // continue script as necessary working with git repo...
    '''
}

how to set windows service username and password through commandline

This works:

sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"

Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)

Just keep in mind that:

  • The spacing in the above example matters. obj= "foo" is correct; obj="foo" is not.
  • '.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.
  • Passwords aren't validated until the service is started
  • Quote your parameters, as above. You can sometimes get by without quotes, but good luck.

How to use Chrome's network debugger with redirects

I don't know of a way to force Chrome to not clear the Network debugger, but this might accomplish what you're looking for:

  1. Open the js console
  2. window.addEventListener("beforeunload", function() { debugger; }, false)

This will pause chrome before loading the new page by hitting a breakpoint.

How to iterate using ngFor loop Map containing key as string and values as map iteration

For Angular 6.1+ , you can use default pipe keyvalue ( Do review and upvote also ) :

<ul>
    <li *ngFor="let recipient of map | keyvalue">
        {{recipient.key}} --> {{recipient.value}}
    </li>
</ul>

WORKING DEMO


For the previous version :

One simple solution to this is convert map to array : Array.from

Component Side :

map = new Map<String, String>();

constructor(){
    this.map.set("sss","sss");
    this.map.set("aaa","sss");
    this.map.set("sass","sss");
    this.map.set("xxx","sss");
    this.map.set("ss","sss");
    this.map.forEach((value: string, key: string) => {
        console.log(key, value);
    });
}

getKeys(map){
    return Array.from(map.keys());
}

Template Side :

<ul>
  <li *ngFor="let recipient of getKeys(map)">
    {{recipient}}
   </li>
</ul>

WORKING DEMO

How to reset sequence in postgres and fill id column with new data?

If you are using pgAdmin3, expand 'Sequences,' right click on a sequence, go to 'Properties,' and in the 'Definition' tab change 'Current value' to whatever value you want. There is no need for a query.

How do I restart a service on a remote machine in Windows?

Several good solutions here. If you're still on Win2K and can't install anything on the remote computer, this also works:

Open the Computer Management Console (right click My Computer, choose Manage; open from Administrative Tools in the Start Menu; or open from the MMC using the snap-in).

Right click on your computer name and choose "Connect to Remote Computer"

Put in the computer name and credentials and you have full access to many admin functions including the services control panel.

how to make a countdown timer in java

You'll see people using the Timer class to do this. Unfortunately, it isn't always accurate. Your best bet is to get the system time when the user enters input, calculate a target system time, and check if the system time has exceeded the target system time. If it has, then break out of the loop.

How can I generate an apk that can run without server with react-native?

The GUI way in Android Studio

  • Have the Android app part of the React Native app open in Android Studio (this just means opening the android folder of your react-native project with Android Studio)
  • Go to the "Build" tab at the top
  • Go down to "Build Bundle(s) / APK(s)"
  • Then select "Build APK(s)"
  • This will walk you through a process of locating your keys to sign the APK or creating your keys if you don't have them already which is all very straightforward. If you're just practicing, you can generate these keys and save them to your desktop.
  • Once that process is complete and if the build was successful, there will be a popup down below in Android Studio. Click the link within it that says "locate" (the APK)
  • That will take you to the apk file, move that over to your android device. Then navigate to that file on the Android device and install it.

Python Anaconda - How to Safely Uninstall

Package "anaconda clean", available from Anaconda platform, should uninstall safely.

conda install anaconda-clean   # install the package anaconda clean
anaconda-clean --yes           # clean all anaconda related files and directories 
rm -rf ~/anaconda3             # removes the entire anaconda directory

rm -rf ~/.anaconda_backup       # anaconda clean creates a back_up of files/dirs, remove it 
                                # (conda list; cmd shouldn't respond after the clean up)

Refer: https://docs.anaconda.com/anaconda/install/uninstall for more details.

Python TypeError: not enough arguments for format string

Note that the % syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:

instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)

This also fixes the error that you happened to have.

How do you write multiline strings in Go?

You can put content with `` around it, like

var hi = `I am here,
hello,
`

iOS: Multi-line UILabel in Auto Layout

I have a UITableViewCell which has a text wrap label. I worked text wrapping as follows.

1) Set UILabel constraints as follows.

enter image description here

2) Set no. of lines to 0.

3) Added UILabel height constraint to UITableViewCell.

@IBOutlet weak var priorityLabelWidth: NSLayoutConstraint!

4) On UITableViewCell:

priorityLabel.sizeToFit()
priorityLabelWidth.constant = priorityLabel.intrinsicContentSize().width+5

spark submit add multiple jars in classpath

For --driver-class-path option you can use : as delimeter to pass multiple jars. Below is the example with spark-shell command but I guess the same should work with spark-submit as well

    spark-shell --driver-class-path /path/to/example.jar:/path/to/another.jar

Spark version: 2.2.0

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

This error can also show up if there are parts in your string that json.loads() does not recognize. An in this example string, an error will be raised at character 27 (char 27).

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

My solution to this would be to use the string.replace() to convert these items to a string:

import json

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

string = string.replace("False", '"False"')

dict_list = json.loads(string)

should use size_t or ssize_t

ssize_t is used for functions whose return value could either be a valid size, or a negative value to indicate an error. It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX] (SSIZE_MAX is system-dependent).

So you should use size_t whenever you mean to return a size in bytes, and ssize_t whenever you would return either a size in bytes or a (negative) error value.

See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html

What is the best way to uninstall gems from a rails3 project?

If you want to clean up all your gems and start over

sudo gem clean

Array vs. Object efficiency in JavaScript

It depends on usage. If the case is lookup objects is very faster.

Here is a Plunker example to test performance of array and object lookups.

https://plnkr.co/edit/n2expPWVmsdR3zmXvX4C?p=preview

You will see that; Looking up for 5.000 items in 5.000 length array collection, take over 3000 milisecons

However Looking up for 5.000 items in object has 5.000 properties, take only 2 or 3 milisecons

Also making object tree don't make huge difference

VMWare Player vs VMWare Workstation

One main reason we went with Workstation over Player at my job is because we need to run VMs that use a physical disk as their hard drive instead of a virtual disk. Workstation supports using physical disks while Player does not.

What is the difference between React Native and React?

React Native

  • It is a framework for building native applications using JavaScript.

  • It compiles to native app components, which makes it possible for you to build native mobile applications.

  • No need to overhaul your old app. All you have to do is add React Native UI components into your existing app’s code, without having to rewrite.

React js

  • It supporting both front-end web and being run on a server, for building user interfaces and web applications.

  • It also allows us to create reusable UI components.

  • You can reuse code components in React JS, saving you a lot of time.

Extract time from date String

A very simple way is to use Formatter (see date time conversions) or more directly String.format as in

String.format("%tR", new Date())

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

For those experiencing this error on CI/CD, adding the line below worked for me on my GitHub Actions CI/CD workflow right after running pip install pyflakes diff-cover:

git fetch origin master:refs/remotes/origin/master

This is a snippet of the solution from the diff-cover github repo:

Solution: diff-cover matches source files in the coverage XML report with source files in the git diff. For this reason, it's important that the relative paths to the files match. If you are using coverage.py to generate the coverage XML report, then make sure you run diff-cover from the same working directory.

I got the solution on the links below. It is a documented diff-cover error.

https://diff-cover.readthedocs.io/en/latest//README.html https://github.com/Bachmann1234/diff_cover/blob/master/README.rst

Hope this helps :-).

How to get the anchor from the URL using jQuery?

You can use the .indexOf() and .substring(), like this:

var url = "www.aaa.com/task1/1.3.html#a_1";
var hash = url.substring(url.indexOf("#")+1);

You can give it a try here, if it may not have a # in it, do an if(url.indexOf("#") != -1) check like this:

var url = "www.aaa.com/task1/1.3.html#a_1", idx = url.indexOf("#");
var hash = idx != -1 ? url.substring(idx+1) : "";

If this is the current page URL, you can just use window.location.hash to get it, and replace the # if you wish.

How to remove a column from an existing table?

This is the correct answer:

ALTER TABLE MEN DROP COLUMN Lname

But... if a CONSTRAINT exists on the COLUMN, then you must DROP the CONSTRAINT first, then you will be able to DROP the COLUMN. In order to drop a CONSTRAINT, run:

ALTER TABLE MEN DROP CONSTRAINT {constraint_name_on_column_Lname}

Android get current Locale, not default

All answers above - do not work. So I will put here a function that works on 4 and 9 android

private String getCurrentLanguage(){
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
      return LocaleList.getDefault().get(0).getLanguage();
   } else{
      return Locale.getDefault().getLanguage();
   }
}

angular 4: *ngIf with multiple conditions

You got a ninja ')'.

Try :

<div *ngIf="currentStatus !== 'open' || currentStatus !== 'reopen'">

File upload progress bar with jQuery

If you are using jquery on your project, and do not want to implement the upload mechanism from scratch, you can use https://github.com/blueimp/jQuery-File-Upload.

They have a very nice api with multiple file selection, drag&drop support, progress bar, validation and preview images, cross-domain support, chunked and resumable file uploads. And they have sample scripts for multiple server languages(node, php, python and go).

Demo url: https://blueimp.github.io/jQuery-File-Upload/.

How can I override Bootstrap CSS styles?

Update 2020 - Bootstrap 4, Bootstrap 5 beta

There are 3 rules to follow when overriding Bootstrap CSS..

  1. import/include bootstrap.css before your CSS rules (overrides)
  2. add more specificity (or equal) to your CSS selectors
  3. if any rule is overridden, use !important attribute to force your rules. If you follow rules 1 & 2 this shouldn't be necessary except for when using Bootstrap utility classes which often contain !important as explained here

Yes, overrides should be put in a separate styles.css (or custom.css) file so that the bootstrap.css remains unmodified. This makes it easier to upgrade the Bootstrap version without impacting the overrides. The reference to the styles.css follows after the bootstrap.css for the overrides to work.

<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/styles.css">

Just add whatever changes are needed in the custom CSS. For example:

legend {
  display: block;
  width: inherit;
  padding: 0;
  margin-bottom: 0;
  font-size: inherit;
  line-height: inherit;
  color: inherit;
  white-space: initial;
}

Note: It's not a good practice to use !important in the override CSS, unless you're overriding one of the Bootstrap Utility classes. CSS specificity always works for one CSS class to override another. Just make sure you use a CSS selector that is that same as, or more specific than the bootstrap.css

For example, consider the Bootstrap 4 dark Navbar link color. Here's the bootstrap.css...

.navbar-dark .navbar-nav .nav-link {
    color: rgba(255,255,255,.5);
}

So, to override the Navbar link color, you can use the same selector, or a more specific selector such as:

#mynavbar .navbar-nav .nav-link {
    color: #ffcc00;
}

When the CSS selectors are the same, the last one takes precedence, which it why the styles.css should follow the bootstrap.css.

What does a just-in-time (JIT) compiler do?

JIT-Just in time the word itself says when it's needed (on demand)

Typical scenario:

The source code is completely converted into machine code

JIT scenario:

The source code will be converted into assembly language like structure [for ex IL (intermediate language) for C#, ByteCode for java].

The intermediate code is converted into machine language only when the application needs that is required codes are only converted to machine code.

JIT vs Non-JIT comparison:

  • In JIT not all the code is converted into machine code first a part of the code that is necessary will be converted into machine code then if a method or functionality called is not in machine then that will be turned into machine code... it reduces burden on the CPU.

  • As the machine code will be generated on run time....the JIT compiler will produce machine code that is optimised for running machine's CPU architecture.

JIT Examples:

  1. In Java JIT is in JVM (Java Virtual Machine)
  2. In C# it is in CLR (Common Language Runtime)
  3. In Android it is in DVM (Dalvik Virtual Machine), or ART (Android RunTime) in newer versions.

Get checkbox value in jQuery

jQuery(".checkboxClass").click(function(){
        var selectedCountry = new Array();
        var n = jQuery(".checkboxClass:checked").length;
        if (n > 0){
            jQuery(".checkboxClass:checked").each(function(){
                selectedCountry.push($(this).val());
            });
        }
        alert(selectedCountry);
    });

Convert object string to JSON

Use with caution (because of eval()):

function strToJson(str) {
  eval("var x = " + str + ";");
  return JSON.stringify(x);
}

call as:

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
alert( strToJson(str) );

Using a list as a data source for DataGridView

Set the DataGridView property

    gridView1.AutoGenerateColumns = true;

And make sure the list of objects your are binding, those object properties should be public.

First Heroku deploy failed `error code=H10`

If you locally start node server by nodemon, like I did, and it locally works, try npm start. Nodemon was telling me no errors, but npm start told me a lot of them in a understandable way and then I could solve them by following another posts here. I hope it helps to someone.

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

As you are creating a database from scratch, you could use:

Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword"); 
PreparedStatement ps = connection.prepareStatement("CREATE DATABASE databasename");
int result = ps.executeUpdate();

Here is an identical scenario.

What is the best way to paginate results in SQL Server

Incredibly, no other answer has mentioned the fastest way to do pagination in all SQL Server versions. Offsets can be terribly slow for large page numbers as is benchmarked here. There is an entirely different, much faster way to perform pagination in SQL. This is often called the "seek method" or "keyset pagination" as described in this blog post here.

SELECT TOP 10 first_name, last_name, score, COUNT(*) OVER()
FROM players
WHERE (score < @previousScore)
   OR (score = @previousScore AND player_id < @previousPlayerId)
ORDER BY score DESC, player_id DESC

The "seek predicate"

The @previousScore and @previousPlayerId values are the respective values of the last record from the previous page. This allows you to fetch the "next" page. If the ORDER BY direction is ASC, simply use > instead.

With the above method, you cannot immediately jump to page 4 without having first fetched the previous 40 records. But often, you do not want to jump that far anyway. Instead, you get a much faster query that might be able to fetch data in constant time, depending on your indexing. Plus, your pages remain "stable", no matter if the underlying data changes (e.g. on page 1, while you're on page 4).

This is the best way to implement pagination when lazy loading more data in web applications, for instance.

Note, the "seek method" is also called keyset pagination.

Total records before pagination

The COUNT(*) OVER() window function will help you count the number of total records "before pagination". If you're using SQL Server 2000, you will have to resort to two queries for the COUNT(*).

Calculating moving average

Here is example code showing how to compute a centered moving average and a trailing moving average using the rollmean function from the zoo package.

library(tidyverse)
library(zoo)

some_data = tibble(day = 1:10)
# cma = centered moving average
# tma = trailing moving average
some_data = some_data %>%
    mutate(cma = rollmean(day, k = 3, fill = NA)) %>%
    mutate(tma = rollmean(day, k = 3, fill = NA, align = "right"))
some_data
#> # A tibble: 10 x 3
#>      day   cma   tma
#>    <int> <dbl> <dbl>
#>  1     1    NA    NA
#>  2     2     2    NA
#>  3     3     3     2
#>  4     4     4     3
#>  5     5     5     4
#>  6     6     6     5
#>  7     7     7     6
#>  8     8     8     7
#>  9     9     9     8
#> 10    10    NA     9

What are intent-filters in Android?

When there are multiple activities set as main and launcher with an intent filter in the manifest. Then first activity considers as Launcher activity, and android launch or open the first activity.

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

The above code makes an app icon available in the device menu, so if we declare 2 launcher activity in the manifest, there will be 2 app icons get created in the device app menu.

So there will be 2 app icons, on click of the first icon, first declared activity in manifest will be launch, and click of another second declared activity gets launch

How to connect android emulator to the internet

After having tried all of the above solutions, I found that on mac os x :

  • you must check the order of your network devices in system preferences >> network >> gear icon
  • you must check the order of you dns servers in /etc/resolv.conf

Then restart your android emulator, it should work.

Call php function from JavaScript

The only way to execute PHP from JS is AJAX. You can send data to server (for eg, GET /ajax.php?do=someFunction) then in ajax.php you write:

function someFunction() {
    echo 'Answer';
}

if ($_GET['do'] === "someFunction") {
    someFunction();
}

and then, catch the answer with JS (i'm using jQuery for making AJAX requests)

Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.

Custom "confirm" dialog in JavaScript?

You might want to consider abstracting it out into a function like this:

function dialog(message, yesCallback, noCallback) {
    $('.title').html(message);
    var dialog = $('#modal_dialog').dialog();

    $('#btnYes').click(function() {
        dialog.dialog('close');
        yesCallback();
    });
    $('#btnNo').click(function() {
        dialog.dialog('close');
        noCallback();
    });
}

You can then use it like this:

dialog('Are you sure you want to do this?',
    function() {
        // Do something
    },
    function() {
        // Do something else
    }
);

Clearing UIWebview cache

Swift 3.

// Remove all cache 
URLCache.shared.removeAllCachedResponses()

// Delete any associated cookies     
if let cookies = HTTPCookieStorage.shared.cookies {
    for cookie in cookies {
        HTTPCookieStorage.shared.deleteCookie(cookie)
    }
}

Example using Hyperlink in WPF

If you want your application to open the link in a web browser you need to add a HyperLink with the RequestNavigate event set to a function that programmatically opens a web-browser with the address as a parameter.

<TextBlock>           
    <Hyperlink NavigateUri="http://www.google.com" RequestNavigate="Hyperlink_RequestNavigate">
        Click here
    </Hyperlink>
</TextBlock>

In the code-behind you would need to add something similar to this to handle the RequestNavigate event:

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
    // for .NET Core you need to add UseShellExecute = true
    // see https://docs.microsoft.com/dotnet/api/system.diagnostics.processstartinfo.useshellexecute#property-value
    Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
    e.Handled = true;
}

In addition you will also need the following imports:

using System.Diagnostics;
using System.Windows.Navigation;

It will look like this in your application:

oO

Call a PHP function after onClick HTML event

You don't need javascript for doing so. Just delete the onClick and write the php Admin.php file like this:

<!-- HTML STARTS-->
<?php
//If all the required fields are filled
if (!empty($GET_['fullname'])&&!empty($GET_['email'])&&!empty($GET_['name']))
{
function addNewContact()
    {
    $new = '{';
    $new .= '"fullname":"' . $_GET['fullname'] . '",';
    $new .= '"email":"' . $_GET['email'] . '",';
    $new .= '"phone":"' . $_GET['phone'] . '",';
    $new .= '}';
    return $new;
    }

function saveContact()
    {
    $datafile = fopen ("data/data.json", "a+");
    if(!$datafile){
        echo "<script>alert('Data not existed!')</script>";
        } 
    else{
        $contact_list = $contact_list . addNewContact();
        file_put_contents("data/data.json", $contact_list);
        }
    fclose($datafile);
    }

// Call the function saveContact()
saveContact();
echo "Thank you for joining us";
}
else //If the form is not submited or not all the required fields are filled

{ ?>

<form>
    <fieldset>
        <legend>Add New Contact</legend>
        <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
        <input type="email" name="email" placeholder="[email protected]" required /> <br />
        <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
        <input type="submit" name="submit" class="button" value="Add Contact"/>
        <input type="button" name="cancel" class="button" value="Reset" />
    </fieldset>
</form>
<?php }
?>
<!-- HTML ENDS -->

Thought I don't like the PHP bit. Do you REALLY want to create a file for contacts? It'd be MUCH better to use a mysql database. Also, adding some breaks to that file would be nice too...

Other thought, IE doesn't support placeholder.

How can I write a heredoc to a file in Bash script?

Note:

The question (how to write a here document (aka heredoc) to a file in a bash script?) has (at least) 3 main independent dimensions or subquestions:

  1. Do you want to overwrite an existing file, append to an existing file, or write to a new file?
  2. Does your user or another user (e.g., root) own the file?
  3. Do you want to write the contents of your heredoc literally, or to have bash interpret variable references inside your heredoc?

(There are other dimensions/subquestions which I don't consider important. Consider editing this answer to add them!) Here are some of the more important combinations of the dimensions of the question listed above, with various different delimiting identifiers--there's nothing sacred about EOF, just make sure that the string you use as your delimiting identifier does not occur inside your heredoc:

  1. To overwrite an existing file (or write to a new file) that you own, substituting variable references inside the heredoc:

    cat << EOF > /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    EOF
    
  2. To append an existing file (or write to a new file) that you own, substituting variable references inside the heredoc:

    cat << FOE >> /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    FOE
    
  3. To overwrite an existing file (or write to a new file) that you own, with the literal contents of the heredoc:

    cat << 'END_OF_FILE' > /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    END_OF_FILE
    
  4. To append an existing file (or write to a new file) that you own, with the literal contents of the heredoc:

    cat << 'eof' >> /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    eof
    
  5. To overwrite an existing file (or write to a new file) owned by root, substituting variable references inside the heredoc:

    cat << until_it_ends | sudo tee /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    until_it_ends
    
  6. To append an existing file (or write to a new file) owned by user=foo, with the literal contents of the heredoc:

    cat << 'Screw_you_Foo' | sudo -u foo tee -a /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    Screw_you_Foo
    

What does [STAThread] do?

It tells the compiler that you're in a Single Thread Apartment model. This is an evil COM thing, it's usually used for Windows Forms (GUI's) as that uses Win32 for its drawing, which is implemented as STA. If you are using something that's STA model from multiple threads then you get corrupted objects.

This is why you have to invoke onto the Gui from another thread (if you've done any forms coding).

Basically don't worry about it, just accept that Windows GUI threads must be marked as STA otherwise weird stuff happens.

Using global variables between files?

The problem is you defined myList from main.py, but subfile.py needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file settings.py. This file is responsible for defining globals and initializing them:

# settings.py

def init():
    global myList
    myList = []

Next, your subfile can import globals:

# subfile.py

import settings

def stuff():
    settings.myList.append('hey')

Note that subfile does not call init()— that task belongs to main.py:

# main.py

import settings
import subfile

settings.init()          # Call only once
subfile.stuff()         # Do stuff with global var
print settings.myList[0] # Check the result

This way, you achieve your objective while avoid initializing global variables more than once.

Colorizing text in the console with C++

Do not use "system("Color …")" if you don't want the entire screen to be filled up with color. This is the script needed to make colored text:

#include <iostream>
#include <windows.h>

int main()
{
const WORD colors[] =
{
0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F,
0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6
};

HANDLE hstdin = GetStdHandle(STD_INPUT_HANDLE);
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
WORD   index = 0;


    SetConsoleTextAttribute(hstdout, colors[index]);
    std::cout << "Hello world" << std::endl;
FlushConsoleInputBuffer(hstdin);
return 0;
}

fastest MD5 Implementation in JavaScript

Node.js has built-in support

const crypto = require('crypto')
crypto.createHash('md5').update('hello world').digest('hex')

Code snippet above computes MD5 hex string for string hello world

The advantage of this solution is you don't need to install additional library.

I think built in solution should be the fastest. If not, we should create issue/PR for the Node.js project.

Is it possible to open developer tools console in Chrome on Android phone?

Please do yourself a favor and just hit the easy button:

download Web Inspector (Open Source) from the Play store.

A CAVEAT: ATTOW, console output does not accept rest params! I.e. if you have something like this:

console.log('one', 'two', 'three');

you will only see

one

logged to the console. You'll need to manually wrap the params in an Array and join, like so:

console.log([ 'one', 'two', 'three' ].join(' '));

to see the expected output.

But the app is open source! A patch may be imminent! The patcher could even be you!

How do you create an asynchronous method in C#?

One very simple way to make a method asynchronous is to use Task.Yield() method. As MSDN states:

You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.

Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.

private async Task<DateTime> CountToAsync(int num = 1000)
{
    await Task.Yield();
    for (int i = 0; i < num; i++)
    {
        Console.WriteLine("#{0}", i);
    }
    return DateTime.Now;
}

How to make a dropdown readonly using jquery?

I had the same problem, my solution was to disable all options not selected. Very easy with jQuery:

$('option:not(:selected)').attr('disabled', true);

Edit => If you have multiple dropdowns on same page, disable all not selected options on select-ID as below.

$('#select_field_id option:not(:selected)').attr('disabled', true);

SELECT * WHERE NOT EXISTS

SELECT * FROM employees WHERE name NOT IN (SELECT name FROM eotm_dyn)

OR

SELECT * FROM employees WHERE NOT EXISTS (SELECT * FROM eotm_dyn WHERE eotm_dyn.name = employees.name)

OR

SELECT * FROM employees LEFT OUTER JOIN eotm_dyn ON eotm_dyn.name = employees.name WHERE eotm_dyn IS NULL

select unique rows based on single distinct column

If you are using MySql 5.7 or later, according to these links (MySql Official, SO QA), we can select one record per group by with out the need of any aggregate functions.

So the query can be simplified to this.

select * from comments_table group by commentname;

Try out the query in action here

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

How to select count with Laravel's fluent query builder?

You can use an array in the select() to define more columns and you can use the DB::raw() there with aliasing it to followers. Should look like this:

$query = DB::table('category_issue')
    ->select(array('issues.*', DB::raw('COUNT(issue_subscriptions.issue_id) as followers')))
    ->where('category_id', '=', 1)
    ->join('issues', 'category_issue.issue_id', '=', 'issues.id')
    ->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
    ->group_by('issues.id')
    ->order_by('followers', 'desc')
    ->get();

Get DataKey values in GridView RowCommand

On the Button:

CommandArgument='<%# Eval("myKey")%>'

On the Server Event

e.CommandArgument

How to select multiple rows filled with constants?

Try the connect by clause in oracle, something like this

select level,level+1,level+2 from dual connect by level <=3;

For more information on connect by clause follow this link : removed URL because oraclebin site is now malicious.

Angularjs simple file download causes router to redirect

If you need a directive more advanced, I recomend the solution that I implemnted, correctly tested on Internet Explorer 11, Chrome and FireFox.

I hope it, will be helpfull.

HTML :

<a href="#" class="btn btn-default" file-name="'fileName.extension'"  ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>

DIRECTIVE :

directive('fileDownload',function(){
    return{
        restrict:'A',
        scope:{
            fileDownload:'=',
            fileName:'=',
        },

        link:function(scope,elem,atrs){


            scope.$watch('fileDownload',function(newValue, oldValue){

                if(newValue!=undefined && newValue!=null){
                    console.debug('Downloading a new file'); 
                    var isFirefox = typeof InstallTrigger !== 'undefined';
                    var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
                    var isIE = /*@cc_on!@*/false || !!document.documentMode;
                    var isEdge = !isIE && !!window.StyleMedia;
                    var isChrome = !!window.chrome && !!window.chrome.webstore;
                    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                    var isBlink = (isChrome || isOpera) && !!window.CSS;

                    if(isFirefox || isIE || isChrome){
                        if(isChrome){
                            console.log('Manage Google Chrome download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var downloadLink = angular.element('<a></a>');//create a new  <a> tag element
                            downloadLink.attr('href',fileURL);
                            downloadLink.attr('download',scope.fileName);
                            downloadLink.attr('target','_self');
                            downloadLink[0].click();//call click function
                            url.revokeObjectURL(fileURL);//revoke the object from URL
                        }
                        if(isIE){
                            console.log('Manage IE download>10');
                            window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName); 
                        }
                        if(isFirefox){
                            console.log('Manage Mozilla Firefox download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var a=elem[0];//recover the <a> tag from directive
                            a.href=fileURL;
                            a.download=scope.fileName;
                            a.target='_self';
                            a.click();//we call click function
                        }


                    }else{
                        alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
                    }
                }
            });

        }
    }
})

IN CONTROLLER:

$scope.myBlobObject=undefined;
$scope.getFile=function(){
        console.log('download started, you can show a wating animation');
        serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
        .then(function(data){//is important that the data was returned as Aray Buffer
                console.log('Stream download complete, stop animation!');
                $scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        },function(fail){
                console.log('Download Error, stop animation and show error message');
                                    $scope.myBlobObject=[];
                                });
                            }; 

IN SERVICE:

function getStream(params){
                 console.log("RUNNING");
                 var deferred = $q.defer();

                 $http({
                     url:'../downloadURL/',
                     method:"PUT",//you can use also GET or POST
                     data:params,
                     headers:{'Content-type': 'application/json'},
                     responseType : 'arraybuffer',//THIS IS IMPORTANT
                    })
                    .success(function (data) {
                        console.debug("SUCCESS");
                        deferred.resolve(data);
                    }).error(function (data) {
                         console.error("ERROR");
                         deferred.reject(data);
                    });

                 return deferred.promise;
                };

BACKEND(on SPRING):

@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
        @RequestBody Map<String,String> spParams
        ) throws IOException {
        OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}

Connect over ssh using a .pem file

Use the -i option:

ssh -i mykey.pem [email protected]

As noted in this answer, this file needs to have correct permissions set. The ssh man page says:

ssh will simply ignore a private key file if it is accessible by others.

You can change the permissions with this command:

chmod go= mykey.pem

That is, set permissions for group and others equal to the empty list of permissions.

JPA: unidirectional many-to-one and cascading delete

@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)

Given annotation worked for me. Can have a try

For Example :-

     public class Parent{
            @Id
            @GeneratedValue(strategy=GenerationType.AUTO)
            @Column(name="cct_id")
            private Integer cct_id;
            @OneToMany(cascade=CascadeType.REMOVE, fetch=FetchType.EAGER,mappedBy="clinicalCareTeam", orphanRemoval=true)
            @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
            private List<Child> childs;
        }
            public class Child{
            @ManyToOne(fetch=FetchType.EAGER)
            @JoinColumn(name="cct_id")
            private Parent parent;
    }

Is it possible to get only the first character of a String?

String has a charAt method that returns the character at the specified position. Like arrays and Lists, String is 0-indexed, i.e. the first character is at index 0 and the last character is at index length() - 1.

So, assuming getSymbol() returns a String, to print the first character, you could do:

System.out.println(ld.getSymbol().charAt(0)); // char at index 0

How to install grunt and how to build script with it

I got the same issue, but i solved it with changing my Grunt.js to Gruntfile.js Check your file name before typing grunt.cmd on windows cmd (if you're using windows).

How can I pause setInterval() functions?

I know this thread is old, but this could be another solution:

var do_this = null;

function y(){
   // what you wanna do
}

do_this = setInterval(y, 1000);

function y_start(){
    do_this = setInterval(y, 1000);
};
function y_stop(){
    do_this = clearInterval(do_this);
};

Python regex for integer?

Regexp work on the character base, and \d means a single digit 0...9 and not a decimal number.

A regular expression that matches only integers with a sign could be for example

^[-+]?[0-9]+$

meaning

  1. ^ - start of string
  2. [-+]? - an optional (this is what ? means) minus or plus sign
  3. [0-9]+ - one or more digits (the plus means "one or more" and [0-9] is another way to say \d)
  4. $ - end of string

Note: having the sign considered part of the number is ok only if you need to parse just the number. For more general parsers handling expressions it's better to leave the sign out of the number: source streams like 3-2 could otherwise end up being parsed as a sequence of two integers instead of an integer, an operator and another integer. My experience is that negative numbers are better handled by constant folding of the unary negation operator at an higher level.

How to actually search all files in Visual Studio

One can access the "Find in Files" window via the drop-down menu selection and search all files in the Entire Solution: Edit > Find and Replace > Find in Files

enter image description here

Other, alternative is to open the "Find in Files" window via the "Standard Toolbars" button as highlighted in the below screen-short:

enter image description here

How can I access Google Sheet spreadsheets only with Javascript?

For this type of thing you should use Google Fusion Tables. The API is designed for that purpose.

How can I disable a button in a jQuery dialog from a function?

Just for the record, this post helped me to solve my problem. In short words, you have to set the disabled attribute to disabled, not to false:

_send_button.attr('disabled','disabled');

This is how all the code looks, I also added some styles to make it look disabled:

var _send_button = $('.ui-dialog-buttonpane button:contains(Send)');
var original_text = _send_button.text();
_send_button.text('Please wait...');
_send_button.addClass('ui-state-disabled');
_send_button.attr('disabled','disabled');
_send_button.fadeTo(500,0.2);

Is Python faster and lighter than C++?

Also: Psyco vs. C++.

It's still a bad comparison, since noone would do the numbercrunchy stuff benchmarks tend to focus on in pure Python anyway. A better one would be comparing the performance of realistic applications, or C++ versus NumPy, to get an idea whether your program will be noticeably slower.

How can I merge properties of two JavaScript objects dynamically?

For not-too-complicated objects you could use JSON:

var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog', car: 'chevy'}
var objMerge;

objMerge = JSON.stringify(obj1) + JSON.stringify(obj2);

// {"food": "pizza","car":"ford"}{"animal":"dog","car":"chevy"}

objMerge = objMerge.replace(/\}\{/, ","); //  \_ replace with comma for valid JSON

objMerge = JSON.parse(objMerge); // { food: 'pizza', animal: 'dog', car: 'chevy'}
// Of same keys in both objects, the last object's value is retained_/

Mind you that in this example "}{" must not occur within a string!

How do I parse JSON from a Java HTTPResponse?

Use JSON Simple,

http://code.google.com/p/json-simple/

Which has a small foot-print, no dependencies so it's perfect for Android.

You can do something like this,

Object obj=JSONValue.parse(buffer.tString());
JSONArray finalResult=(JSONArray)obj;

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

It's a kludge, but assuming there's a minimum length for SEARCHSTRING, for example 2 characters, substring the SEARCHSTRING parameter at the second character and pass it as two parameters instead: SEARCHSTRING1 ("Nu") and SEARCHSTRING2 ("ll"). Concatenate them back together when executing the query to the database.

Convert Promise to Observable

You may also use defer. The main difference is that the promise is not going to resolve or reject eagerly.

align textbox and text/labels in html?

I like to set the 'line-height' in the css for the divs to get them to line up properly. Here is an example of how I do it using asp and css:

ASP:

<div id="profileRow1">
    <div id="profileRow1Col1" class="righty">
        <asp:Label ID="lblCreatedDateLabel" runat="server" Text="Date Created:"></asp:Label><br />
        <asp:Label ID="lblLastLoginDateLabel" runat="server" Text="Last Login Date:"></asp:Label><br />
        <asp:Label ID="lblUserIdLabel" runat="server" Text="User ID:"></asp:Label><br />
        <asp:Label ID="lblUserNameLabel" runat="server" Text="Username:"></asp:Label><br />
        <asp:Label ID="lblFirstNameLabel" runat="server" Text="First Name:"></asp:Label><br />
        <asp:Label ID="lblLastNameLabel" runat="server" Text="Last Name:"></asp:Label><br />
    </div>
    <div id="profileRow1Col2">
        <asp:Label ID="lblCreatedDate" runat="server" Text="00/00/00 00:00:00"></asp:Label><br />
        <asp:Label ID="lblLastLoginDate" runat="server" Text="00/00/00 00:00:00"></asp:Label><br />
        <asp:Label ID="lblUserId" runat="server" Text="UserId"></asp:Label><br />
        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br />
        <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox><br />
        <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox><br />
    </div>
</div>

And here is the code in the CSS file to make all of the above fields look nice and neat:

#profileRow1{width:100%;line-height:40px;}
#profileRow1Col1{float:left; width:25%; margin-right:20px;}
#profileRow1Col2{float:left; width:25%;}
.righty{text-align:right;}

you can basically pull everything but the DIV tags and replace with your own content.

Trust me when I say it looks aligned the way the image in the original post does!

I would post a screenshot but Stack wont let me: Oops! Your edit couldn't be submitted because: We're sorry, but as a spam prevention mechanism, new users aren't allowed to post images. Earn more than 10 reputation to post images.

:)

Java get String CompareTo as a comparator object

Ok this is a few years later but with java 8 you can use Comparator.naturalOrder():

http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#naturalOrder--

From javadoc:

static <T extends Comparable<? super T>> Comparator<T> naturalOrder()

Returns a comparator that compares Comparable objects in natural order. The returned comparator is serializable and throws NullPointerException when comparing null.

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

I got the same error while using other one entity, He was annotating the class wrongly by using the table name inside the @Entity annotation without using the @Table annotation

The correct format should be

@Entity //default name similar to class name 'FooBar' OR @Entity( name = "foobar" ) for differnt entity name
@Table( name = "foobar" ) // Table name 
public class FooBar{

How to do a JUnit assert on a message in a logger

There are two things that you might be trying to test.

  • When there is an event of interest to the operator of my program, does my program perform an appropriate logging operation, which can inform the operator of that event.
  • When my program performs a logging operation, does the log message it produces have the correct text.

Those two things are actually different things, and so could be tested separately. However, testing the second (the text of messages) is so problematic, I recommend against doing it at all. A test of a message text will ultimately consist of checking that one text string (the expected message text) is the same as, or can be trivially derived from, the text string used in your logging code.

  • Those tests do not test program logic at all, they only test that one resource (a string) is equivalent to another resource.
  • The tests are fragile; even a minor tweak to the formatting of a log message breaks your tests.
  • The tests are incompatible with internationalisation (translation) of your logging interface.The tests assume there is only one possible message text, and thus only one possible human language.

Note that having your program code (implementing some business logic, perhaps) directly calling the text logging interface is poor design (but unfortunately very commom). Code that is responsible for business logic is also deciding some logging policy and the text of log messages. It mixes business logic with user interface code (yes, log messages are part of your program's user interface). Those things should be separate.

I therefore recommend that business logic does not directly generate the text of log messages. Instead have it delegate to a logging object.

  • The class of the logging object should provide a suitable internal API, which your business object can use to express the event that has occurred using objects of your domain model, not text strings.
  • The implementation of your logging class is responsible for producing text representations of those domain objects, and rendering a suitable text description of the event, then forwarding that text message to the low level logging framework (such as JUL, log4j or slf4j).
  • Your business logic is responsible only for calling the correct methods of the internal API of your logger class, passing the correct domain objects, to describe the actual events that occurred.
  • Your concrete logging class implements an interface, which describes the internal API your business logic may use.
  • Your class(es) that implements business logic and must perform logging has a reference to the logging object to delegate to. The class of the reference is the abstract interface.
  • Use dependency injection to set up the reference to the logger.

You can then test that your business logic classes correctly tell the logging interface about events, by creating a mock logger, which implements the internal logging API, and using dependency injection in the set up phase of your test.

Like this:

 public class MyService {// The class we want to test
    private final MyLogger logger;

    public MyService(MyLogger logger) {
       this.logger = Objects.requireNonNull(logger);
    }

    public void performTwiddleOperation(Foo foo) {// The method we want to test
       ...// The business logic
       logger.performedTwiddleOperation(foo);
    }
 };

 public interface MyLogger {
    public void performedTwiddleOperation(Foo foo);
    ...
 };

 public final class MySl4jLogger: implements MyLogger {
    ...

    @Override
    public void performedTwiddleOperation(Foo foo) {
       logger.info("twiddled foo " + foo.getId());
    }
 }

 public final void MyProgram {
    public static void main(String[] argv) {
       ...
       MyLogger logger = new MySl4jLogger(...);
       MyService service = new MyService(logger);
       startService(service);// or whatever you must do
       ...
    }
 }

 public class MyServiceTest {
    ...

    static final class MyMockLogger: implements MyLogger {
       private Food.id id;
       private int nCallsPerformedTwiddleOperation;
       ...

       @Override
       public void performedTwiddleOperation(Foo foo) {
          id = foo.id;
          ++nCallsPerformedTwiddleOperation;
       }

       void assertCalledPerformedTwiddleOperation(Foo.id id) {
          assertEquals("Called performedTwiddleOperation", 1, nCallsPerformedTwiddleOperation);
          assertEquals("Called performedTwiddleOperation with correct ID", id, this.id);
       }
    };

    @Test
    public void testPerformTwiddleOperation_1() {
       // Setup
       MyMockLogger logger = new MyMockLogger();
       MyService service = new MyService(logger);
       Foo.Id id = new Foo.Id(...);
       Foo foo = new Foo(id, 1);

       // Execute
       service.performedTwiddleOperation(foo);

       // Verify
       ...
       logger.assertCalledPerformedTwiddleOperation(id);
    }
 }

What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

If you are just going to substitute it into a URL I suppose one field would do - so you can form a URL like

http://maps.google.co.uk/maps?q=12.345678,12.345678&z=6

but as it is two pieces of data I would store them in separate fields

Java: how to convert HashMap<String, Object> to array

If you have HashMap<String, SomeObject> hashMap then:

hashMap.values().toArray();

Will return an Object[]. If instead you want an array of the type SomeObject, you could use:

hashMap.values().toArray(new SomeObject[0]);

CSS Flex Box Layout: full-width row and columns

Just use another container to wrap last two divs. Don't forget to use CSS prefixes.

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
   display: flex;_x000D_
   flex-direction: column;_x000D_
   height: 600px;_x000D_
   width: 580px;_x000D_
   background-color: rgb(240, 240, 240);_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
   height: 100px;_x000D_
   background-color: rgb(200, 200, 200);_x000D_
}_x000D_
_x000D_
#anotherContainer{_x000D_
   display: flex;_x000D_
   height: 100%;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
   background-color: red;_x000D_
   flex: 4;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
   background-color: blue;_x000D_
   flex: 1;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
   <div id="productShowcaseTitle">1</div>_x000D_
   <div id="anotherContainer">_x000D_
      <div id="productShowcaseDetail">2</div>_x000D_
      <div id="productShowcaseThumbnailContainer">3</div>_x000D_
   </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I access the $scope variable in browser's console using AngularJS?

I've used angular.element($(".ng-scope")).scope(); in the past and it works great. Only good if you have only one app scope on the page, or you can do something like:

angular.element($("div[ng-controller=controllerName]")).scope(); or angular.element(document.getElementsByClassName("ng-scope")).scope();

How to read all of Inputstream in Server Socket JAVA

You can read your BufferedInputStream like this. It will read data till it reaches end of stream which is indicated by -1.

inputS = new BufferedInputStream(inBS);
byte[] buffer = new byte[1024];    //If you handle larger data use a bigger buffer size
int read;
while((read = inputS.read(buffer)) != -1) {
    System.out.println(read);
    // Your code to handle the data
}

MYSQL query between two timestamps

@Amaynut Thanks

SELECT * 
FROM eventList 
WHERE date BETWEEN UNIX_TIMESTAMP('2017-08-01') AND UNIX_TIMESTAMP('2017/08/01');

above mention, code works and my problem solved.

How do I capture SIGINT in Python?

If you want to ensure that your cleanup process finishes I would add on to Matt J's answer by using a SIG_IGN so that further SIGINT are ignored which will prevent your cleanup from being interrupted.

import signal
import sys

def signal_handler(signum, frame):
    signal.signal(signum, signal.SIG_IGN) # ignore additional signals
    cleanup() # give your process a chance to clean up
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler) # register the signal with the signal handler first
do_stuff()

Prevent screen rotation on Android

User "portrait" in your AndroidManifest.xml file might seem like a good solution. But it forces certain devices (that work best in landscape) to go into portrait, not getting the proper orientation. On the latest Android version, you will get wearing an error. So my suggestion it's better to use "nosensor".

<activity
        ...
        ...
        android:screenOrientation="nosensor">

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

In php 7 there is the php ini option opcache.file_cache that saves the bytecode in a specific folder. In could be useful to in php cli script that are "compiled" and saved in a specific folder for a optimized reuse.

Opcache it is not compiling but is something similar.

How to fix HTTP 404 on Github Pages?

I was following this YT video. So, when I ran the command in my terminal, it pushed the code to gh-pages branch already. Then I pushed to the master branch. It was giving me 404 error.

Then I swapped the branch to master and then again reverted to gh-pages and now the error is gone. It's pointing to the index.html even if it's not in the URL.

How to use setInterval and clearInterval?

clearInterval is one option:

var interval = setInterval(doStuff, 2000); // 2000 ms = start after 2sec 
function doStuff() {
  alert('this is a 2 second warning');
  clearInterval(interval);
}

git push says "everything up-to-date" even though I have local changes

I had multiple remotes. All but one pushed correctly, so I knew I didn't have a detached HEAD or commit issues.

Instead, I had accidentally given two remotes the same URL. The remote with the duplicated URL failed because I was pushing to a URL that had already been pushed to!

Using git remote -v showed my list of remotes and their URLs, where I realized the issue.

Resetting the failing remote to its correct URL fixed the issue:
git remote set-url <remote-name> <correct-url>

List Git aliases

As other answers mentioned, git config -l lists all your configuration details from your config file. Here's a partial example of that output for my configuration:

...
alias.force=push -f
alias.wd=diff --color-words
alias.shove=push -f
alias.gitignore=!git ls-files -i --exclude-from=.gitignore | xargs git rm --cached
alias.branches=!git remote show origin | grep \w*\s*(new^|tracked) -E
core.repositoryformatversion=0
core.filemode=false
core.bare=false
...

So we can grep out the alias lines, using git config -l | grep alias:

alias.force=push -f
alias.wd=diff --color-words
alias.shove=push -f
alias.gitignore=!git ls-files -i --exclude-from=.gitignore | xargs git rm --cached
alias.branches=!git remote show origin | grep \w*\s*(new^|tracked) -E

We can make this prettier by just cutting out the alias. part of each line, leaving us with this command:

git config -l | grep alias | cut -c 7-

Which prints:

force=push -f
wd=diff --color-words
shove=push -f
gitignore=!git ls-files -i --exclude-from=.gitignore | xargs git rm --cached
branches=!git remote show origin | grep \w*\s*(new^|tracked) -E

Lastly, don't forget to add this as an alias:

git config --global alias.la "!git config -l | grep alias | cut -c 7-"

Enjoy!

how to loop through each row of dataFrame in pyspark

Give A Try Like this

    result = spark.createDataFrame([('SpeciesId','int'), ('SpeciesName','string')],["col_name", "data_type"]); 
    for f in result.collect(): 
        print (f.col_name)

Detect whether Office is 32bit or 64bit via the registry

You can search the registry for {90140000-0011-0000-0000-0000000FF1CE}. If the bold numbers start with 0 its x86, 1 is x64

For me it was in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Registration{90140000-0057-0000-0000-0000000FF1CE}

Source

oracle.jdbc.driver.OracleDriver ClassNotFoundException

Method 1: Download ojdbc.jar

add ojdbc6.jar to deployment assembly. Right click on project->properties->select deployment assembly->click on 'Add' ->select 'Archives from File System'->browse to the folder where ojdbc6.jar is saved.->add the jar->click finish->Apply/OK.

Method 2:

if you want to add ojdbc.jar to your maven dependencies you follow this link: http://www.mkyong.com/maven/how-to-add-oracle-jdbc-driver-in-your-maven-local-repository/ . . Even if you're using a maven project it is not necessary to add ojdbc to maven dependencies(method 2), method 1 (adding directly to deployment assembly) works just fine.