I had this problem too. It turned out I forgot to include one of the components in app.module.ts
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.
You should implement didSelect function.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("User touched on \(indexpath) row")
}
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.
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:
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):
@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);
}
}
}
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)
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
}
}
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!
If you want repeatable fade animation you can do that by using CABasicAnimation
like below :
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)
}
}
// 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)
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]
}
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
}
add parameter nativeQuery = true
ex: @Query(value="Update user set user_name =:user_name,password =:password where user_id =:user_id",nativeQuery = true)
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.
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();
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.
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.
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
}()
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')
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.
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.
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.
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.
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"));
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'}"
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;
}
}
val() is more like a shortcut for attr('value'). For your usage use text() or html() instead
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
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; }
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
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
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)
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
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.
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).
public static bool Contains(Array a, object val)
{
return Array.IndexOf(a, val) != -1;
}
you do not need to know pts number, just type:
ps all | grep bash
then:
kill pid1 pid2 pid3 ...
@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.
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);
<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.
you can right click on the project select "set configuration" then "Customize", from there you can choose your main class.
Below active and activemenu are classes and itemCount and ShowCart is expression/boolean values.
ng-class="{'active' : itemCount, 'activemenu' : showCart}"
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.
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;
}
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);
}
}
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.
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
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.
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)
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
button2.Enabled == true ;
must be button2.Enabled = true ;
.
You have a compare ==
where you should have an assign =
.
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
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
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
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 TB1, TB2
FROM customer_details
LEFT JOIN customer_booking on TB1.cust_id = TB2.fk_cust_id
WHERE TB1.cust_id = $id
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
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:
Press the Windows + R keys to open the Run dialog, type
eventvwr.msc
, and press Enter.If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).
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.
Do either step 5 or 6 below for what shutdown events you would like to see.
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.
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.
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;
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.
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.if(sender is TextBox) {
var text = (sender as TextBox).Text;
}
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.
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
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:
id
.required
, validator
and converter
attributes and nest a <f:converter>
and <f:validator>
in it like as with <h:inputText>
)#{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" />
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.
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.
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).
double r2()
{
return (rand() % 10001) / 10000.0;
}
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
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.
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
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
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.
You can raise a notice in Postgres
as follows:
raise notice 'Value: %', deletedContactId;
Read here
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
}
});
submit
event with librariesIf 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:
jQuery
$(ele).submit(callback);
Where ele
is the form element reference, and callback
being the callback function reference. Reference
<iframe width="100%" height="100%" src="http://jsfiddle.net/DerekL/wnbo1hq0/show" frameborder="0"></iframe>
_x000D_
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
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
Other frameworks/libraries
Refer to the documentation of your framework.
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.
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.
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>
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)
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...!
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
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.
####################### && 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.
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" />
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
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 :)!
//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;
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.
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
.
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.
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");
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')
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");
}
}
#include<stdio.h>
int main(){
char ch='"';
printf("%c",ch);
return 0;
}
Output: "
You could do the following:
.interrupt
the working threads if they wait for data in some blocking call)writeBatch
in your case) to finish, by calling the Thread.join()
method on the working threads.Some sketchy code:
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.
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).
You can use Threadf#join method for this purpose.
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:
3# Simple scrolling library on Github
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>
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.
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"
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)
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.
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');
}
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
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
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.
<build>
<finalName>log-enrichment</finalName>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
mvn clean compile assembly:single
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/
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.
Integer.parseInt
will take a string and return a int.
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
Try this:
print ("Enter the Five Numbers with Comma")
k=[x for x in input("Enter Number:").split(',')]
for l in k:
print (l)
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.
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 Integer
and Double
.
From the documentation of compareTo
:
Compares this
BigDecimal
with the specifiedBigDecimal
.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.
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.
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);
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';
}
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);
});
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')()
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()
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");
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)
read about the lists() method
$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()
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.
i have updated both fiddles. i hope it will make your work done.
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;
}
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;
}
You want to do $arrayOfString[0].Title -eq $myPbiject.item(0).Title
-match
is for regex matching ( the second argument is a regex )
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.
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.
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]
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.
it worked for me after deleting and adding the server back.
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;
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")
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);
$("#yourbuttonid").click(function(){ document.location = "<%= Url.Action("Youraction") %>";})
Usually with printf
(or one of its cousins) using the %x
format specifier.
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>
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'
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.
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...
'''
}
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:
obj= "foo"
is correct; obj="foo"
is not.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:
window.addEventListener("beforeunload", function() { debugger; }, false)
This will pause chrome before loading the new page by hitting a breakpoint.
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>
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>
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.
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.
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.
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.
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.
You can put content with `` around it, like
var hi = `I am here,
hello,
`
I have a UITableViewCell which has a text wrap label. I worked text wrapping as follows.
1) Set UILabel constraints as follows.
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
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
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)
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
If you want to clean up all your gems and start over
sudo gem clean
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
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.
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.
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.
A very simple way is to use Formatter
(see date time conversions) or more directly String.format
as in
String.format("%tR", new Date())
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 :-).
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.
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}
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();
}
}
You got a ninja ')'.
Try :
<div *ngIf="currentStatus !== 'open' || currentStatus !== 'reopen'">
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).
Update 2020 - Bootstrap 4, Bootstrap 5 beta
There are 3 rules to follow when overriding Bootstrap CSS..
bootstrap.css
before your CSS rules (overrides)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
.
JIT-Just in time the word itself says when it's needed (on demand)
The source code is completely converted into machine code
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.
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.
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);
});
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) );
Set the DataGridView property
gridView1.AutoGenerateColumns = true;
And make sure the list of objects your are binding, those object properties should be public.
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.
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.
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 @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.
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(*)
.
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
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
After having tried all of the above solutions, I found that on mac os x :
Then restart your android emulator, it should work.
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.
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
}
);
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)
}
}
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:
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.
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:
root
) own the file?(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:
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
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
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
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
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
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
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.
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.
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;
}
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.
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!
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;
}
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 * 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
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
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.
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();
On the Button:
CommandArgument='<%# Eval("myKey")%>'
On the Server Event
e.CommandArgument
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.
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;
}
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.
@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;
}
String
has a charAt
method that returns the character at the specified position. Like arrays and List
s, 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
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).
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);
};
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
^
- start of string[-+]?
- an optional (this is what ?
means) minus or plus sign[0-9]+
- one or more digits (the plus means "one or more" and [0-9]
is another way to say \d
)$
- end of stringNote: 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.
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
Other, alternative is to open the "Find in Files" window via the "Standard Toolbars" button as highlighted in the below screen-short:
For this type of thing you should use Google Fusion Tables. The API is designed for that purpose.
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);
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.
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!
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;
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.
You may also use defer. The main difference is that the promise is not going to resolve or reject eagerly.
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.
:)
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.
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{
There are two things that you might be trying to test.
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.
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.
implements
an interface
, which describes the internal API your business logic may use.interface
.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);
}
}
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
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]);
Just use another container to wrap last two divs. Don't forget to use CSS prefixes.
#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_
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();
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
}
@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.
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()
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">
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.
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.
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);
}
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>
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 cut
ting 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!
result = spark.createDataFrame([('SpeciesId','int'), ('SpeciesName','string')],["col_name", "data_type"]);
for f in result.collect():
print (f.col_name)
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}
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.