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.
Problem was solved by myself using tutorial of weheartswift
This worked for me, May help you too :
Swift 4+ :
self.tableView.register(UITableViewCell.self, forCellWithReuseIdentifier: "cell")
Swift 3 :
self.tableView.register(UITableViewCell.classForKeyedArchiver(), forCellReuseIdentifier: "Cell")
Swift 2.2 :
self.tableView.registerClass(UITableViewCell.classForKeyedArchiver(), forCellReuseIdentifier: "Cell")
We have to Set Identifier property to Table View Cell as per below image,
in Swift 4
in cellForRowAt indexPath:
cell.prescriptionButton.addTarget(self, action: Selector("onClicked:"), for: .touchUpInside)
function that run after user pressed button:
@objc func onClicked(sender: UIButton){
let tag = sender.tag
}
If you are looking for Swift 3, Follow the steps to achieve this:
func viewDidLoad() {
//Define Layout here
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
//Get device width
let width = UIScreen.main.bounds.width
//set section inset as per your requirement.
layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
//set cell item size here
layout.itemSize = CGSize(width: width / 2, height: width / 2)
//set Minimum spacing between 2 items
layout.minimumInteritemSpacing = 0
//set minimum vertical line spacing here between two lines in collectionview
layout.minimumLineSpacing = 0
//apply defined layout to collectionview
collectionView!.collectionViewLayout = layout
}
This is verified on Xcode 8.0 with Swift 3.
I just ran into this problem on a UICollectionView and the way that i solved it similar to the answer above but in a pure UICollectionView way.
Create a custom UICollectionViewCell that contains whatever you will be filling it with to make it dynamic. I created its own .xib for it as it seems like the easiest approach.
Add constraints in that .xib that allow for the cell to be calculated from top to bottom. The re-sizing won't work if you haven't accounted for all of the height. Say you have a view on top, then a label underneath it, and another label underneath that. You would need to connect constraints to the top of the cell to the top of that view, then the bottom of the view to the top of the first label, bottom of first label to the top of the second label, and bottom of second label to bottom of cell.
Load the .xib into the viewcontroller and register it with the collectionView on viewDidLoad
let nib = UINib(nibName: CustomCellName, bundle: nil)
self.collectionView!.registerNib(nib, forCellWithReuseIdentifier: "customCellID")`
Load a second copy of that xib into the class and store it as a property so you can use it to determine the size of what that cell should be
let sizingNibNew = NSBundle.mainBundle().loadNibNamed(CustomCellName, owner: CustomCellName.self, options: nil) as NSArray
self.sizingNibNew = (sizingNibNew.objectAtIndex(0) as? CustomViewCell)!
Implement the UICollectionViewFlowLayoutDelegate
in your view controller. The method that matters is called sizeForItemAtIndexPath
. Inside that method you will need to pull the data from the datasource that is associated with that cell from the indexPath. Then configure the sizingCell and call preferredLayoutSizeFittingSize
. The method returns a CGSize which will consist of the width minus the content insets and the height that is returned from self.sizingCell.preferredLayoutSizeFittingSize(targetSize)
.
override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
guard let data = datasourceArray?[indexPath.item] else {
return CGSizeZero
}
let sectionInset = self.collectionView?.collectionViewLayout.sectionInset
let widthToSubtract = sectionInset!.left + sectionInset!.right
let requiredWidth = collectionView.bounds.size.width
let targetSize = CGSize(width: requiredWidth, height: 0)
sizingNibNew.configureCell(data as! CustomCellData, delegate: self)
let adequateSize = self.sizingNibNew.preferredLayoutSizeFittingSize(targetSize)
return CGSize(width: (self.collectionView?.bounds.width)! - widthToSubtract, height: adequateSize.height)
}
In the class of the custom cell itself you will need to override awakeFromNib
and tell the contentView
that its size needs to be flexible
override func awakeFromNib() {
super.awakeFromNib()
self.contentView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight]
}
In the custom cell override layoutSubviews
override func layoutSubviews() {
self.layoutIfNeeded()
}
In the class of the custom cell implement preferredLayoutSizeFittingSize
. This is where you will need to do any trickery on the items that are being laid out. If its a label you will need to tell it what its preferredMaxWidth should be.
func preferredLayoutSizeFittingSize(_ targetSize: CGSize)-> CGSize {
let originalFrame = self.frame
let originalPreferredMaxLayoutWidth = self.label.preferredMaxLayoutWidth
var frame = self.frame
frame.size = targetSize
self.frame = frame
self.setNeedsLayout()
self.layoutIfNeeded()
self.label.preferredMaxLayoutWidth = self.questionLabel.bounds.size.width
// calling this tells the cell to figure out a size for it based on the current items set
let computedSize = self.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
let newSize = CGSize(width:targetSize.width, height:computedSize.height)
self.frame = originalFrame
self.questionLabel.preferredMaxLayoutWidth = originalPreferredMaxLayoutWidth
return newSize
}
All those steps should give you the correct sizes. If your getting 0 or other funky numbers than you haven't set up your constraints properly.
You have to use implicitly unwrapped optionals so that Swift can cope with circular dependencies (parent <-> child of the UI components in this case) during the initialization phase.
@IBOutlet var imgBook: UIImageView!
@IBOutlet var titleBook: UILabel!
@IBOutlet var pageBook: UILabel!
Read this doc, they explain it all nicely.
You did not register your nib as below:
tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")
Check if the cell is being registered with self.collectionView.registerClass(cellClass: AnyClass?, forCellWithReuseIdentifier identifier: String)
. If so, then remove that line of code.
See this answer for more info: Why is UICollectionViewCell's outlet nil?
"If you are using a storyboard you don't want to call this. It will overwrite what you have in your storyboard."
From Swift 5.3
, you do not have to unwrap self
in closure if you pass [self]
before in
in closure.
Refer someFunctionWithEscapingClosure { [self] in x = 100 }
in this swift doc
Tested with Xcode 9 (edit also tested on 11 / 12 Beta 2) and Swift 4 (edit: also tested on 5.2)
The asker of the original question has solved their problem. I am adding this answer as a mini self contained example project for others who are trying to do the same thing.
The finished project should look like this:
It can be just a Single View Application.
Add a new Swift file to your project. Name it MyCustomCell.swift. This class will hold the outlets for the views that you add to your cell in the storyboard.
import UIKit
class MyCustomCell: UITableViewCell {
@IBOutlet weak var myView: UIView!
@IBOutlet weak var myCellLabel: UILabel!
}
We will connect these outlets later.
Open ViewController.swift and make sure you have the following content:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// These strings will be the data for the table view cells
let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
// These are the colors of the square views in our table view cells.
// In a real project you might use UIImages.
let colors = [UIColor.blue, UIColor.yellow, UIColor.magenta, UIColor.red, UIColor.brown]
// Don't forget to enter this in IB also
let cellReuseIdentifier = "cell"
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell
cell.myView.backgroundColor = self.colors[indexPath.row]
cell.myCellLabel.text = self.animals[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
Add a Table View to your view controller and use auto layout to pin it to the four sides of the View Controller. Then drag a Table View Cell onto the Table View. And then drag a View and a Label onto the Prototype cell. (You may need to select the Table View Cell and manually set the Row Height to something taller in the Size inspector so that you have more room to work with.) Use auto layout to fix the View and the Label how you want them arranged within the content view of the Table View Cell. For example, I made my View be 100x100.
Custom class name and Identifier
Select the Table View Cell and set the custom class to be MyCustomCell
(the name of the class in the Swift file we added). Also set the Identifier to be cell
(the same string that we used for the cellReuseIdentifier
in the code above.
Hook Up the Outlets
tableView
variable in the ViewController
code.myView
and myCellLabel
variables in the MyCustomCell
class.That's it. You should be able to run your project now.
UIImageView
.All the calls to UI should be asynchronous, anything you change on the UI like updating table or changing text label should be done from main thread. using DispatchQueue.main will add your operation to the queue on the main thread.
Swift 4
DispatchQueue.main.async{
self.tableView.reloadData()
}
@available(iOS 11.0, *)
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let editAction = UIContextualAction.init(style: UIContextualAction.Style.normal, title: "Edit", handler: { (action, view, completion) in
//TODO: Edit
completion(true)
self.popUpViewPresent(index:indexPath.row)
})
let deleteAction = UIContextualAction.init(style: UIContextualAction.Style.destructive, title: "Delete", handler: { (action, view, completion) in
//TODO: Delete
completion(true)
self.deleteTagAction(senderTag:indexPath.row)
})
editAction.image = UIImage(named: "Edit-white")
deleteAction.image = UIImage(named: "Delete-white")
editAction.backgroundColor = UIColor.gray
deleteAction.backgroundColor = UIColor.red
let config = UISwipeActionsConfiguration(actions: [deleteAction, editAction])
config.performsFirstActionWithFullSwipe = false
return config
}
This way I solved my problem. Hope it helps others. In my case I created a class, a field, their getter & setter and then provide the object instead of string.
Use this
public static class EncryptedData {
private String encryptedData;
public String getEncryptedData() {
return encryptedData;
}
public void setEncryptedData(String encryptedData) {
this.encryptedData = encryptedData;
}
}
@PutMapping(value = MY_IP_ADDRESS)
public ResponseEntity<RestResponse> updateMyIpAddress(@RequestBody final EncryptedData encryptedData) {
try {
Path path = Paths.get(PUBLIC_KEY);
byte[] bytes = Files.readAllBytes(path);
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(base64.decode(bytes));
PrivateKey privateKey = KeyFactory.getInstance(CRYPTO_ALGO_RSA).generatePrivate(ks);
Cipher cipher = Cipher.getInstance(CRYPTO_ALGO_RSA);
cipher.init(Cipher.PRIVATE_KEY, privateKey);
String decryptedData = new String(cipher.doFinal(encryptedData.getEncryptedData().getBytes()));
String[] dataArray = decryptedData.split("|");
Method updateIp = Class.forName("com.cuanet.client.helper").getMethod("methodName", String.class,String.class);
updateIp.invoke(null, dataArray[0], dataArray[1]);
} catch (Exception e) {
LOG.error("Unable to update ip address for encrypted data: "+encryptedData, e);
}
return null;
Instead of this
@PutMapping(value = MY_IP_ADDRESS)
public ResponseEntity<RestResponse> updateMyIpAddress(@RequestBody final EncryptedData encryptedData) {
try {
Path path = Paths.get(PUBLIC_KEY);
byte[] bytes = Files.readAllBytes(path);
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(base64.decode(bytes));
PrivateKey privateKey = KeyFactory.getInstance(CRYPTO_ALGO_RSA).generatePrivate(ks);
Cipher cipher = Cipher.getInstance(CRYPTO_ALGO_RSA);
cipher.init(Cipher.PRIVATE_KEY, privateKey);
String decryptedData = new String(cipher.doFinal(encryptedData.getBytes()));
String[] dataArray = decryptedData.split("|");
Method updateIp = Class.forName("com.cuanet.client.helper").getMethod("methodName", String.class,String.class);
updateIp.invoke(null, dataArray[0], dataArray[1]);
} catch (Exception e) {
LOG.error("Unable to update ip address for encrypted data: "+encryptedData, e);
}
return null;
}
to make UITableView sections header not sticky or sticky:
change the table view's style - make it grouped for not sticky & make it plain for sticky section headers - do not forget: you can do it from storyboard without writing code. (click on your table view and change it is style from the right Side/ component menu)
if you have extra components such as custom views or etc. please check the table view's margins to create appropriate design. (such as height of header for sections & height of cell at index path, sections)
In my case, it wasn't due to image caching (Used SDWebImage). It was because of custom cell's tag mismatch with indexPath.row.
On cellForRowAtIndexPath :
1) Assign an index value to your custom cell. For instance,
cell.tag = indexPath.row
2) On main thread, before assigning the image, check if the image belongs the corresponding cell by matching it with the tag.
dispatch_async(dispatch_get_main_queue(), ^{
if(cell.tag == indexPath.row) {
UIImage *tmpImage = [[UIImage alloc] initWithData:imgData];
thumbnailImageView.image = tmpImage;
}});
});
Enqueue means to add an element, dequeue to remove an element.
var stackInput= []; // First stack
var stackOutput= []; // Second stack
// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
return stackInput.push(item);
}
function dequeue(stackInput, stackOutput) {
// Reverse the stack such that the first element of the output stack is the
// last element of the input stack. After that, pop the top of the output to
// get the first element that was ever pushed into the input stack
if (stackOutput.length <= 0) {
while(stackInput.length > 0) {
var elementToOutput = stackInput.pop();
stackOutput.push(elementToOutput);
}
}
return stackOutput.pop();
}
I also had problem in Ubuntu 15.10 while installing gulp-preetify.
The problem was:
Registry returned 404 for GET on http://registry.npmjs.org/gulp-preetify
I tried by using npm install gulp-preetify
but it didn't worked.
npm i gulp-preetify
and it just got installed. I cannot guarantee that it will solve your problem but it won't harm with a single try.
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.
This is probably how you should do it:
void push(std::string&& filename)
{
{
std::lock_guard<std::mutex> lock(qMutex);
q.push(std::move(filename));
}
populatedNotifier.notify_one();
}
bool try_pop(std::string& filename, std::chrono::milliseconds timeout)
{
std::unique_lock<std::mutex> lock(qMutex);
if(!populatedNotifier.wait_for(lock, timeout, [this] { return !q.empty(); }))
return false;
filename = std::move(q.front());
q.pop();
return true;
}
I'll just add that Xcode 4.5 includes the new dequeueReusableCellWithIdentifier:forIndexPath:
in its default template code - a potential gotcha for developers expecting the older dequeueReusableCellWithIdentifier:
method.
Yes we can check the length of queue object created from collections.
from collections import deque
class Queue():
def __init__(self,batchSize=32):
#self.batchSie = batchSize
self._queue = deque(maxlen=batchSize)
def enqueue(self, items):
''' Appending the items to the queue'''
self._queue.append(items)
def dequeue(self):
'''remoe the items from the top if the queue becomes full '''
return self._queue.popleft()
Creating an object of class
q = Queue(batchSize=64)
q.enqueue([1,2])
q.enqueue([2,3])
q.enqueue([1,4])
q.enqueue([1,22])
Now retrieving the length of the queue
#check the len of queue
print(len(q._queue))
#you can print the content of the queue
print(q._queue)
#Can check the content of the queue
print(q.dequeue())
#Check the length of retrieved item
print(len(q.dequeue()))
check the results in attached screen shot
Hope this helps...
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.
Based on acheron55 answer I posted a possible implementation here.
Here is a brief summery of it:
All you have to do, is to keep track of the path through which the target has been reached.
A simple way to do it, is to push into the Queue
the whole path used to reach a node, rather than the node itself.
The benefit of doing so is that when the target has been reached the queue holds the path used to reach it.
This is also applicable to cyclic graphs, where a node can have more than one parent.
The best way to add different objects into same container is to use make_shared, vector, and range based loop and you will have a nice, clean and "readable" code!
typedef std::shared_ptr<gate> Ptr
vector<Ptr> myConatiner;
auto andGate = std::make_shared<ANDgate>();
myConatiner.push_back(andGate );
auto orGate= std::make_shared<ORgate>();
myConatiner.push_back(orGate);
for (auto& element : myConatiner)
element->run();
You are reinventing the wheel.
If you need persistence and other enterprise features use JMS (I'd suggest ActiveMq).
If you need fast in-memory queues use one of the impementations of java's Queue.
If you need to support java 1.4 or earlier, use Doug Lea's excellent concurrent package.
you can use the tag pattern:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = @"identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
[cell autorelelase];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 40, 20)];
[button addTarget:self action:@selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
[button setTag:[indexPath row]]; //use the row as the current tag
[cell.contentView addSubview:button];
[button release];
}
UIButton *button = (UIButton *)[cell viewWithTag:[indexPath row]]; //use [indexPath row]
[button setTitle:@"Edit" forState:UIControlStateNormal];
return cell;
}
- (void)buttonPressedAction:(id)sender
{
UIButton *button = (UIButton *)sender;
//button.tag has the row number (you can convert it to indexPath)
}
Also you can use guppy module.
>>> from guppy import hpy; hp=hpy()
>>> hp.heap()
Partition of a set of 25853 objects. Total size = 3320992 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 11731 45 929072 28 929072 28 str
1 5832 23 469760 14 1398832 42 tuple
2 324 1 277728 8 1676560 50 dict (no owner)
3 70 0 216976 7 1893536 57 dict of module
4 199 1 210856 6 2104392 63 dict of type
5 1627 6 208256 6 2312648 70 types.CodeType
6 1592 6 191040 6 2503688 75 function
7 199 1 177008 5 2680696 81 type
8 124 0 135328 4 2816024 85 dict of class
9 1045 4 83600 3 2899624 87 __builtin__.wrapper_descriptor
<90 more rows. Type e.g. '_.more' to view.>
And:
>>> hp.iso(1, [1], "1", (1,), {1:1}, None)
Partition of a set of 6 objects. Total size = 560 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 1 17 280 50 280 50 dict (no owner)
1 1 17 136 24 416 74 list
2 1 17 64 11 480 86 tuple
3 1 17 40 7 520 93 str
4 1 17 24 4 544 97 int
5 1 17 16 3 560 100 types.NoneType
In short: No.
There is a hack, use vector as underlaid container, so queue::front
will return valid reference, convert it to pointer an iterate until <= queue::back
To understand queue method, you have to understand how jQuery does animation. If you write multiple animate method calls one after the other, jQuery creates an 'internal' queue and adds these method calls to it. Then it runs those animate calls one by one.
Consider following code.
function nonStopAnimation()
{
//These multiple animate calls are queued to run one after
//the other by jQuery.
//This is the reason that nonStopAnimation method will return immeidately
//after queuing these calls.
$('#box').animate({ left: '+=500'}, 4000);
$('#box').animate({ top: '+=500'}, 4000);
$('#box').animate({ left: '-=500'}, 4000);
//By calling the same function at the end of last animation, we can
//create non stop animation.
$('#box').animate({ top: '-=500'}, 4000 , nonStopAnimation);
}
The 'queue'/'dequeue' method gives you control over this 'animation queue'.
By default the animation queue is named 'fx'. I have created a sample page here which has various examples which will illustrate how the queue method could be used.
http://jsbin.com/zoluge/1/edit?html,output
Code for above sample page:
$(document).ready(function() {
$('#nonStopAnimation').click(nonStopAnimation);
$('#stopAnimationQueue').click(function() {
//By default all animation for particular 'selector'
//are queued in queue named 'fx'.
//By clearning that queue, you can stop the animation.
$('#box').queue('fx', []);
});
$('#addAnimation').click(function() {
$('#box').queue(function() {
$(this).animate({ height : '-=25'}, 2000);
//De-queue our newly queued function so that queues
//can keep running.
$(this).dequeue();
});
});
$('#stopAnimation').click(function() {
$('#box').stop();
});
setInterval(function() {
$('#currentQueueLength').html(
'Current Animation Queue Length for #box ' +
$('#box').queue('fx').length
);
}, 2000);
});
function nonStopAnimation()
{
//These multiple animate calls are queued to run one after
//the other by jQuery.
$('#box').animate({ left: '+=500'}, 4000);
$('#box').animate({ top: '+=500'}, 4000);
$('#box').animate({ left: '-=500'}, 4000);
$('#box').animate({ top: '-=500'}, 4000, nonStopAnimation);
}
Now you may ask, why should I bother with this queue? Normally, you wont. But if you have a complicated animation sequence which you want to control, then queue/dequeue methods are your friend.
Also see this interesting conversation on jQuery group about creating a complicated animation sequence.
Demo of the animation:
http://www.exfer.net/test/jquery/tabslide/
Let me know if you still have questions.
For those who are not PYTHON expert ,the same code in C++
//@Author :Ritesh Kumar Gupta
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
vector<vector<int> >GRAPH(100);
inline void print_path(vector<int>path)
{
cout<<"[ ";
for(int i=0;i<path.size();++i)
{
cout<<path[i]<<" ";
}
cout<<"]"<<endl;
}
bool isadjacency_node_not_present_in_current_path(int node,vector<int>path)
{
for(int i=0;i<path.size();++i)
{
if(path[i]==node)
return false;
}
return true;
}
int findpaths(int source ,int target ,int totalnode,int totaledge )
{
vector<int>path;
path.push_back(source);
queue<vector<int> >q;
q.push(path);
while(!q.empty())
{
path=q.front();
q.pop();
int last_nodeof_path=path[path.size()-1];
if(last_nodeof_path==target)
{
cout<<"The Required path is:: ";
print_path(path);
}
else
{
print_path(path);
}
for(int i=0;i<GRAPH[last_nodeof_path].size();++i)
{
if(isadjacency_node_not_present_in_current_path(GRAPH[last_nodeof_path][i],path))
{
vector<int>new_path(path.begin(),path.end());
new_path.push_back(GRAPH[last_nodeof_path][i]);
q.push(new_path);
}
}
}
return 1;
}
int main()
{
//freopen("out.txt","w",stdout);
int T,N,M,u,v,source,target;
scanf("%d",&T);
while(T--)
{
printf("Enter Total Nodes & Total Edges\n");
scanf("%d%d",&N,&M);
for(int i=1;i<=M;++i)
{
scanf("%d%d",&u,&v);
GRAPH[u].push_back(v);
}
printf("(Source, target)\n");
scanf("%d%d",&source,&target);
findpaths(source,target,N,M);
}
//system("pause");
return 0;
}
/*
Input::
1
6 11
1 2
1 3
1 5
2 1
2 3
2 4
3 4
4 3
5 6
5 4
6 3
1 4
output:
[ 1 ]
[ 1 2 ]
[ 1 3 ]
[ 1 5 ]
[ 1 2 3 ]
The Required path is:: [ 1 2 4 ]
The Required path is:: [ 1 3 4 ]
[ 1 5 6 ]
The Required path is:: [ 1 5 4 ]
The Required path is:: [ 1 2 3 4 ]
[ 1 2 4 3 ]
[ 1 5 6 3 ]
[ 1 5 4 3 ]
The Required path is:: [ 1 5 6 3 4 ]
*/
Let S1 and S2 be the two Stacks to be used in the implementation of queues.
struct Stack
{ struct Queue *Q1;
struct Queue *Q2;
}
We make sure that one queue is empty always.
Push operation : Whichever queue is not empty, insert the element in it.
Push (struct Stack *S, int data)
{
if(isEmptyQueue(S->Q1)
EnQueue(S->Q2, data);
else EnQueue(S->Q1, data);
}
Time Complexity: O(1)
Pop Operation: Transfer n-1 elements to other queue and delete last from queue for performing pop operation.
`
int Pop(struct Stack *S){
int i, size;
if(IsEmptyQueue(S->Q2))
{
size=size(S->Q1);
i=0;
while(i<size-1)
{ EnQueue(S->Q2, Dequeue(S->Q1)) ;
i++;
}
return DeQueue(S->Q1);
}
else{
size=size(S->Q2);
while(i<size-1)
EnQueue(S->Q1, Dequeue(S->Q2)) ;
i++;
}
return DeQueue(S->Q2);
} }
Time Complexity: Running Time of pop Operation is O(n) as each time pop is called, we are transferring all the elements from one queue to oter.
Loading UITableViewCells from XIBs saves a lot of code, but usually results in horrible scrolling speed (actually, it's not the XIB but the excessive use of UIViews that cause this).
I suggest you take a look at this: Link reference
Another quick lookup table is available at this github page
Note : This does not consider all the containers such as, unordered_map etc. but is still great to look at. It is just a cleaner version of this
In the menu go to : - File - Import - as the filter select 'Existing Projects into Workspace' - click next - browse to the project directory at 'select root directory' - click on 'finish'
Google Play services has two APIs you can use to streamline the SMS-based verification process
Provides a fully automated user experience, without requiring the user to manually type verification codes and without requiring any extra app permissions and should be used when possible. It does, however, require you to place a custom hash code in the message body, so you must have control over server side as well.
Request SMS Verification in an Android App
Perform SMS Verification on a Server
Does not require the custom hash code, however require the user to approve your app's request to access the message containing the verification code. In order to minimize the chances of surfacing the wrong message to the user, SMS User Consent
will filter out messages from senders in the user's Contacts list.
The SMS User Consent API
is part of Google Play Services. To use it you’ll need at least version 17.0.0
of these libraries:
implementation "com.google.android.gms:play-services-auth:17.0.0"
implementation "com.google.android.gms:play-services-auth-api-phone:17.1.0"
Step 1: Start listening for SMS messages
SMS User Consent will listen for incoming SMS messages that contain a one-time-code for up to five minutes. It won’t look at any messages that are sent before it’s started. If you know the phone number that will send the one-time-code, you can specify the senderPhoneNumber
, or if you don’t null
will match any number.
smsRetriever.startSmsUserConsent(senderPhoneNumber /* or null */)
Step 2: Request consent to read a message
Once your app receives a message containing a one-time-code, it’ll be notified by a broadcast. At this point, you don’t have consent to read the message — instead you’re given an Intent
that you can start to prompt the user for consent. Inside your BroadcastReceiver
, you show the prompt using the Intent
in the extras
.
When you start that intent, it will prompt the user for permission to read a single message. They’ll be shown the entire text that they will share with your app.
val consentIntent = extras.getParcelable<Intent>(SmsRetriever.EXTRA_CONSENT_INTENT)
startActivityForResult(consentIntent, SMS_CONSENT_REQUEST)
Step 3: Parse the one-time-code and complete SMS Verification
When the user clicks “Allow”
— it’s time to actually read the message! Inside of onActivityResult
you can get the full text of the SMS Message from the data:
val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
You then parse the SMS message and pass the one-time-code to your backend!
In many cases you're better off using CSS transitions for this, and in old browsers the easing will simply be instant. Most animations (like fade in/out) are very trivial to implement and the browser does all the legwork for you. https://developer.mozilla.org/en/docs/Web/CSS/transition
you'd use any of these:
JSTL c:forEach varStatus properties
Property Getter Description
current getCurrent() The item (from the collection) for the current round of iteration.
index getIndex() The zero-based index for the current round of iteration.
count getCount() The one-based count for the current round of iteration
last isLast() Flag indicating whether the current round is the last pass through the iteration
begin getBegin() The value of the begin attribute
end getEnd() The value of the end attribute
step getStep() The value of the step attribute
If you are looking for answer in string values , try this
var check = moment('date/utc format');
day = check.format('dddd') // => ('Monday' , 'Tuesday' ----)
month = check.format('MMMM') // => ('January','February.....)
year = check.format('YYYY') // => ('2012','2013' ...)
The following solution works for all the test cases.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
for (int i = 0; i < testCases; i++)
{
int totalNodes = sc.nextInt();
int totalEdges = sc.nextInt();
Map<Integer, List<Integer>> adjacencyList = new HashMap<Integer, List<Integer>>();
for (int j = 0; j < totalEdges; j++)
{
int src = sc.nextInt();
int dest = sc.nextInt();
if (adjacencyList.get(src) == null)
{
List<Integer> neighbours = new ArrayList<Integer>();
neighbours.add(dest);
adjacencyList.put(src, neighbours);
} else
{
List<Integer> neighbours = adjacencyList.get(src);
neighbours.add(dest);
adjacencyList.put(src, neighbours);
}
if (adjacencyList.get(dest) == null)
{
List<Integer> neighbours = new ArrayList<Integer>();
neighbours.add(src);
adjacencyList.put(dest, neighbours);
} else
{
List<Integer> neighbours = adjacencyList.get(dest);
neighbours.add(src);
adjacencyList.put(dest, neighbours);
}
}
int start = sc.nextInt();
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
int[] costs = new int[totalNodes + 1];
Arrays.fill(costs, 0);
costs[start] = 0;
Map<String, Integer> visited = new HashMap<String, Integer>();
while (!queue.isEmpty())
{
int node = queue.remove();
if(visited.get(node +"") != null)
{
continue;
}
visited.put(node + "", 1);
int nodeCost = costs[node];
List<Integer> children = adjacencyList.get(node);
if (children != null)
{
for (Integer child : children)
{
int total = nodeCost + 6;
String key = child + "";
if (visited.get(key) == null)
{
queue.add(child);
if (costs[child] == 0)
{
costs[child] = total;
} else if (costs[child] > total)
{
costs[child] = total;
}
}
}
}
}
for (int k = 1; k <= totalNodes; k++)
{
if (k == start)
{
continue;
}
System.out.print(costs[k] == 0 ? -1 : costs[k]);
System.out.print(" ");
}
System.out.println();
}
}
}
For Swift 3, Swift 4 (working with cellular and Wi-Fi):
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
/* Only Working for WIFI
let isReachable = flags == .reachable
let needsConnection = flags == .connectionRequired
return isReachable && !needsConnection
*/
// Working for Cellular and WIFI
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
let ret = (isReachable && !needsConnection)
return ret
}
}
Usage:
if Reachability.isConnectedToNetwork(){
print("Internet Connection Available!")
}else{
print("Internet Connection not Available!")
}
I also faced the same problem while working with eclips Neon. It got fixed after editing the .ini file with following content:
> -Dhttp.proxyPort=8080
> -Dhttp.proxyHost=myproxy
> -Dhttp.proxyUser=mydomain\myusername
> -Dhttp.proxyPassword=mypassword
> -Dhttp.nonProxyHosts=localhost|127.0.0.1
> -Djava.net.preferIPv4Stack=true
Note: Sometime it may also caused due to the issue with your Network configuration and device. So conform first that your windows firewall is allowing to connect your eclips to the outer world (internet). (Turn off the windows firewall for the instance of time that your computer take to install the file).
Although I've used Eclipse for years, this "answer" is only conjecture (which I'm going to try tonight). If it gets down-voted out of existence, then obviously I'm wrong.
Oracle relies on CMake to generate a Visual Studio "Solution" for their MySQL Connector C source code. Within the Solution are "Projects" that can be compiled individually or collectively (by the Solution). Each Project has its own makefile, compiling its portion of the Solution with settings that are different than the other Projects.
Similarly, I'm hoping an Eclipse Workspace can hold my related makefile Projects (Eclipse), with a master Project whose dependencies compile the various unique-makefile Projects as pre-requesites to building its "Solution". (My folder structure would be as @Rafael describes).
So I'm hoping a good way to use Workspaces is to emulate Visual Studio's ability to combine dissimilar Projects into a Solution.
I just used this, but I don't know if it works across all browsers.
It works in Firefox:
<a href="myfile.pdf" download>Click to Download</a>
Example: A house is worth $100,000
, and it is appreciating at $1000
per year.
To keep track of the current house value, you would use a database as the value would change every year.
Three years later, you would be able to see the value of the house which is $103,000.
To keep track of the historical house value, you would use a data warehouse as the value of the house should be
$100,000 on year 0,
$101,000 on year 1,
$102,000 on year 2,
$103,000 on year 3.
Use the string's .replace
method with a regex of \D
, which is a shorthand character class that matches all non-digits:
myString = myString.replace(/\D/g,'');
Although a set is the easiest way, you could also use a dict and use some_dict.has(key)
to populate a dictionary with only unique keys and values.
Assuming you have already populated words[]
with input from the user, create a dict mapping the unique words in the list to a number:
word_map = {}
i = 1
for j in range(len(words)):
if not word_map.has_key(words[j]):
word_map[words[j]] = i
i += 1
num_unique_words = len(new_map) # or num_unique_words = i, however you prefer
Something I came upon while trying to work a spinner was to allow for flexibility within the script without the use of a ton of if statements.
Since this is a simpler solution than iterating through an array to check for a single instance of a class present it keeps the script cleaner. Any suggestions for cleaning the code further are welcome.
$('.next').click(function(){
var imageToSlide = $('#imageSprite'); // Get id of image
switch(true) {
case (imageToSlide.hasClass('pos1')):
imageToSlide.removeClass('pos1').addClass('pos2');
break;
case (imageToSlide.hasClass('pos2')):
imageToSlide.removeClass('pos2').addClass('pos3');
break;
case (imageToSlide.hasClass('pos3')):
imageToSlide.removeClass('pos3').addClass('pos4');
break;
case (imageToSlide.hasClass('pos4')):
imageToSlide.removeClass('pos4').addClass('pos1');
}
}); `
Note: This answer was written for Laravel 3. Thus might or might not works well in more recent version of Laravel.
You can delete all related photos before actually deleting the user.
<?php
class User extends Eloquent
{
public function photos()
{
return $this->has_many('Photo');
}
public function delete()
{
// delete all related photos
$this->photos()->delete();
// as suggested by Dirk in comment,
// it's an uglier alternative, but faster
// Photo::where("user_id", $this->id)->delete()
// delete the user
return parent::delete();
}
}
Hope it helps.
Click volumes, then explore, and then that should open lampp which has htdocs in it.
On ng-build, file not found(404) error occur. So we can use below code
<ng-include src="'views/transaction/test.html'"></ng-include>
insted of,
<div ng-include="'views/transaction/test.html'"></div>
You can use the blade template engine:
@include('view.name')
'view.name' would live in your main views folder:
// for laravel 4.X
app/views/view/name.blade.php
// for laravel 5.X
resources/views/view/name.blade.php
Another example
@include('hello.world');
would display the following view
// for laravel 4.X
app/views/hello/world.blade.php
// for laravel 5.X
resources/views/hello/world.blade.php
Another example
@include('some.directory.structure.foo');
would display the following view
// for Laravel 4.X
app/views/some/directory/structure/foo.blade.php
// for Laravel 5.X
resources/views/some/directory/structure/foo.blade.php
So basically the dot notation defines the directory hierarchy that your view is in, followed by the view name, relative to app/views
folder for laravel 4.x or your resources/views
folder in laravel 5.x
ADDITIONAL
If you want to pass parameters: @include('view.name', array('paramName' => 'value'))
You can then use the value in your views like so <p>{{$paramName}}</p>
If you have changed innodb_log_file_size
recently, try to restore the previous value which worked.
You can set 'url' => 'https://youDomain.com'
in config/app.php
or you could use a middleware class Laravel 5 - redirect to HTTPS.
I'm not certain when this was implemented, but currently you can use http://api.jquery.com/jQuery.isNumeric/
if($('#Field').val() != "")
{
if($.isNumeric($('#Field').val()) {
errors+= "Field must be numeric.<br/>";
success = false;
}
}
Use org.springframework.web.context.request.WebRequest
as a parameter in your controller method, it provides the method getParameterMap()
, the advantage is that you do not tight your application to the Servlet API, the WebRequest is a example of JavaEE pattern Context Object.
private void parseExceptionContents(
final Exception exception,
final OutputStream out)
{
final StackTraceElement[] stackTrace = exception.getStackTrace();
int index = 0;
for (StackTraceElement element : stackTrace)
{
final String exceptionMsg =
"Exception thrown from " + element.getMethodName()
+ " in class " + element.getClassName() + " [on line number "
+ element.getLineNumber() + " of file " + element.getFileName() + "]";
try
{
out.write((headerLine + newLine).getBytes());
out.write((headerTitlePortion + index++ + newLine).getBytes() );
out.write((headerLine + newLine).getBytes());
out.write((exceptionMsg + newLine + newLine).getBytes());
out.write(
("Exception.toString: " + element.toString() + newLine).getBytes());
}
catch (IOException ioEx)
{
System.err.println(
"IOException encountered while trying to write "
+ "StackTraceElement data to provided OutputStream.\n"
+ ioEx.getMessage() );
}
}
}
Perhaps not in the context that you have it, but you could use
SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA
You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.
Try:
psql -U role_name -d database -h hostname..com -W
Here's a one liner. It assumes the item will be in the array.
var items = [523, 3452, 334, 31, 5346]_x000D_
var replace = (arr, oldVal, newVal) => (arr[arr.indexOf(oldVal)] = newVal, arr)_x000D_
console.log(replace(items, 3452, 1010))
_x000D_
unset()
and initialization:unset($_POST);
$_POST = array();
Or in a single statement:
unset($_POST) ? $_POST = array() : $_POST = array();
But what is the reason you want to do this?
Import your csv or sql to sqlite with phpLiteAdmin, it is excellent.
Create
trigger `[dbo].[mytrigger]` on `[dbo].[Patients]` after update , insert as
begin
--Sql logic
print 'Hello world'
end
You don't need to call ValidateForm()
twice, as you are above. You can just do
if(!ValidateForm()){
..
} else ...
I think that will solve the issue as above it looks like your comparing true/false
to the string equivalent 'false'
.
As mentioned in several places, I'm also not able to get the req.session.destroy() function to work correctly.
This is my work around .. seems to do the trick, and still allows req.flash to be used
req.session = {};
If you delete or set req.session = null; , seems then you can't use req.flash
You need a special type of function known as a table valued function. Below is a somewhat long-winded example that builds a date dimension for a data warehouse. Note the returns
clause that defines a table structure. You can insert anything into the table variable (@DateHierarchy
in this case) that you want, including building a temporary table and copying the contents into it.
if object_id ('ods.uf_DateHierarchy') is not null
drop function ods.uf_DateHierarchy
go
create function ods.uf_DateHierarchy (
@DateFrom datetime
,@DateTo datetime
) returns @DateHierarchy table (
DateKey datetime
,DisplayDate varchar (20)
,SemanticDate datetime
,MonthKey int
,DisplayMonth varchar (10)
,FirstDayOfMonth datetime
,QuarterKey int
,DisplayQuarter varchar (10)
,FirstDayOfQuarter datetime
,YearKey int
,DisplayYear varchar (10)
,FirstDayOfYear datetime
) as begin
declare @year int
,@quarter int
,@month int
,@day int
,@m1ofqtr int
,@DisplayDate varchar (20)
,@DisplayQuarter varchar (10)
,@DisplayMonth varchar (10)
,@DisplayYear varchar (10)
,@today datetime
,@MonthKey int
,@QuarterKey int
,@YearKey int
,@SemanticDate datetime
,@FirstOfMonth datetime
,@FirstOfQuarter datetime
,@FirstOfYear datetime
,@MStr varchar (2)
,@QStr varchar (2)
,@Ystr varchar (4)
,@DStr varchar (2)
,@DateStr varchar (10)
-- === Previous ===================================================
-- Special placeholder date of 1/1/1800 used to denote 'previous'
-- so that naive date calculations sort and compare in a sensible
-- order.
--
insert @DateHierarchy (
DateKey
,DisplayDate
,SemanticDate
,MonthKey
,DisplayMonth
,FirstDayOfMonth
,QuarterKey
,DisplayQuarter
,FirstDayOfQuarter
,YearKey
,DisplayYear
,FirstDayOfYear
) values (
'1800-01-01'
,'Previous'
,'1800-01-01'
,180001
,'Prev'
,'1800-01-01'
,18001
,'Prev'
,'1800-01-01'
,1800
,'Prev'
,'1800-01-01'
)
-- === Calendar Dates =============================================
-- These are generated from the date range specified in the input
-- parameters.
--
set @today = @Datefrom
while @today <= @DateTo begin
set @year = datepart (yyyy, @today)
set @month = datepart (mm, @today)
set @day = datepart (dd, @today)
set @quarter = case when @month in (1,2,3) then 1
when @month in (4,5,6) then 2
when @month in (7,8,9) then 3
when @month in (10,11,12) then 4
end
set @m1ofqtr = @quarter * 3 - 2
set @DisplayDate = left (convert (varchar, @today, 113), 11)
set @SemanticDate = @today
set @MonthKey = @year * 100 + @month
set @DisplayMonth = substring (convert (varchar, @today, 113), 4, 8)
set @Mstr = right ('0' + convert (varchar, @month), 2)
set @Dstr = right ('0' + convert (varchar, @day), 2)
set @Ystr = convert (varchar, @year)
set @DateStr = @Ystr + '-' + @Mstr + '-01'
set @FirstOfMonth = convert (datetime, @DateStr, 120)
set @QuarterKey = @year * 10 + @quarter
set @DisplayQuarter = 'Q' + convert (varchar, @quarter) + ' ' +
convert (varchar, @year)
set @QStr = right ('0' + convert (varchar, @m1ofqtr), 2)
set @DateStr = @Ystr + '-' + @Qstr + '-01'
set @FirstOfQuarter = convert (datetime, @DateStr, 120)
set @YearKey = @year
set @DisplayYear = convert (varchar, @year)
set @DateStr = @Ystr + '-01-01'
set @FirstOfYear = convert (datetime, @DateStr)
insert @DateHierarchy (
DateKey
,DisplayDate
,SemanticDate
,MonthKey
,DisplayMonth
,FirstDayOfMonth
,QuarterKey
,DisplayQuarter
,FirstDayOfQuarter
,YearKey
,DisplayYear
,FirstDayOfYear
) values (
@today
,@DisplayDate
,@SemanticDate
,@Monthkey
,@DisplayMonth
,@FirstOfMonth
,@QuarterKey
,@DisplayQuarter
,@FirstOfQuarter
,@YearKey
,@DisplayYear
,@FirstOfYear
)
set @today = dateadd (dd, 1, @today)
end
-- === Specials ===================================================
-- 'Ongoing', 'Error' and 'Not Recorded' set two years apart to
-- avoid accidental collisions on 'Next Year' calculations.
--
insert @DateHierarchy (
DateKey
,DisplayDate
,SemanticDate
,MonthKey
,DisplayMonth
,FirstDayOfMonth
,QuarterKey
,DisplayQuarter
,FirstDayOfQuarter
,YearKey
,DisplayYear
,FirstDayOfYear
) values (
'9000-01-01'
,'Ongoing'
,'9000-01-01'
,900001
,'Ong.'
,'9000-01-01'
,90001
,'Ong.'
,'9000-01-01'
,9000
,'Ong.'
,'9000-01-01'
)
insert @DateHierarchy (
DateKey
,DisplayDate
,SemanticDate
,MonthKey
,DisplayMonth
,FirstDayOfMonth
,QuarterKey
,DisplayQuarter
,FirstDayOfQuarter
,YearKey
,DisplayYear
,FirstDayOfYear
) values (
'9100-01-01'
,'Error'
,null
,910001
,'Error'
,null
,91001
,'Error'
,null
,9100
,'Err'
,null
)
insert @DateHierarchy (
DateKey
,DisplayDate
,SemanticDate
,MonthKey
,DisplayMonth
,FirstDayOfMonth
,QuarterKey
,DisplayQuarter
,FirstDayOfQuarter
,YearKey
,DisplayYear
,FirstDayOfYear
) values (
'9200-01-01'
,'Not Recorded'
,null
,920001
,'N/R'
,null
,92001
,'N/R'
,null
,9200
,'N/R'
,null
)
return
end
go
the best way for me :
$data=[
'var1'=>'something',
'var2'=>'something',
'var3'=>'something',
];
return View::make('view',$data);
Using the DISTINCT flag will remove duplicate rows.
SELECT DISTINCT
C.Content_ID,
C.Content_Title,
M.Media_Id
FROM tbl_Contents C
LEFT JOIN tbl_Media M ON M.Content_Id = C.Content_Id
ORDER BY C.Content_DatePublished ASC
(Jun-Dec 2016) Most answers here are now out-of-date as: 1) GData APIs are the previous generation of Google APIs, and that's why it was hard for @Josh Brown to find that old GData Docs API documentation. While not all GData APIs have been deprecated, all newer Google APIs do not use the Google Data protocol; and 2) Google released a new Google Sheets API (not GData). In order to use the new API, you need to get the Google APIs Client Library for Python (it's as easy as pip install -U google-api-python-client
[or pip3
for Python 3]) and use the latest Sheets API v4+, which is much more powerful & flexible than older API releases.
Here's one code sample from the official docs to help get you kickstarted. However, here are slightly longer, more "real-world" examples of using the API you can learn from (videos plus blog posts):
The latest Sheets API provides features not available in older releases, namely giving developers programmatic access to a Sheet as if you were using the user interface (create frozen rows, perform cell formatting, resizing rows/columns, adding pivot tables, creating charts, etc.), but NOT as if it was some database that you could perform searches on and get selected rows from. You'd basically have to build a querying layer on top of the API that does this. One alternative is to use the Google Charts Visualization API query language, which does support SQL-like querying. You can also query from within the Sheet itself. Be aware that this functionality existed before the v4 API, and that the security model was updated in Aug 2016. To learn more, check my G+ reshare to a full write-up from a Google Developer Expert.
Also note that the Sheets API is primarily for programmatically accessing spreadsheet operations & functionality as described above, but to perform file-level access such as imports/exports, copy, move, rename, etc., use the Google Drive API instead. Examples of using the Drive API:
(*) - TL;DR: upload plain text file to Drive, import/convert to Google Docs format, then export that Doc as PDF. Post above uses Drive API v2; this follow-up post describes migrating it to Drive API v3, and here's a developer video combining both "poor man's converter" posts.
To learn more about how to use Google APIs with Python in general, check out my blog as well as a variety of Google developer videos (series 1 and series 2) I'm producing.
ps. As far as Google Docs goes, there isn't a REST API available at this time, so the only way to programmatically access a Doc is by using Google Apps Script (which like Node.js is JavaScript outside of the browser, but instead of running on a Node server, these apps run in Google's cloud; also check out my intro video.) With Apps Script, you can build a Docs app or an add-on for Docs (and other things like Sheets & Forms).
UPDATE Jul 2018: The above "ps." is no longer true. The G Suite developer team pre-announced a new Google Docs REST API at Google Cloud NEXT '18. Developers interested in getting into the early access program for the new API should register at https://developers.google.com/docs.
UPDATE Feb 2019: The Docs API launched to preview last July is now available generally to all... read the launch post for more details.
UPDATE Nov 2019: In an effort to bring G Suite and GCP APIs more inline with each other, earlier this year, all G Suite code samples were partially integrated with GCP's newer (lower-level not product) Python client libraries. The way auth is done is similar but (currently) requires a tiny bit more code to manage token storage, meaning rather than our libraries manage storage.json
, you'll store them using pickle
(token.pickle
or whatever name you prefer) instead, or choose your own form of persistent storage. For you readers here, take a look at the updated Python quickstart example.
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.
signingConfigs should be before buildTypes
signingConfigs {
debug {
storeFile file("debug.keystore")
}
myConfig {
storeFile file("other.keystore")
storePassword "android"
keyAlias "androidotherkey"
keyPassword "android"
}
}
buildTypes {
bar {
debuggable true
jniDebugBuild true
signingConfig signingConfigs.debug
}
foo {
debuggable false
jniDebugBuild false
signingConfig signingConfigs.myConfig
}
}
Like this:
int counts[26];
memset(counts, 0, sizeof(counts));
char *p = string;
while (*p) {
counts[tolower(*p++) - 'a']++;
}
This code assumes that the string is null-terminated, and that it contains only characters a
through z
or A
through Z
, inclusive.
To understand how this works, recall that after conversion tolower
each letter has a code between a
and z
, and that the codes are consecutive. As the result, tolower(*p) - 'a'
evaluates to a number from 0
to 25
, inclusive, representing the letter's sequential number in the alphabet.
This code combines ++
and *p
to shorten the program.
Kirk's answer is right on. As a rule, you're not going to have any luck with type inference when your method signature has fewer types of parameters than it has generic type parameters.
In your particular case, it seems you could possibly move the T
type parameter to the class level and then get type inference on your Get
method:
class ServiceGate<T>
{
public IAccess<S, T> Get<S>(S sig) where S : ISignatur<T>
{
throw new NotImplementedException();
}
}
Then the code you posted with the CS0411 error could be rewritten as:
static void Main()
{
// Notice: a bit more cumbersome to write here...
ServiceGate<SomeType> service = new ServiceGate<SomeType>();
// ...but at least you get type inference here.
IAccess<Signatur, SomeType> access = service.Get(new Signatur());
}
From the pyspark.sql.DataFrame.save documentation (currently at 1.3.1), you can specify mode='overwrite'
when saving a DataFrame:
myDataFrame.save(path='myPath', source='parquet', mode='overwrite')
I've verified that this will even remove left over partition files. So if you had say 10 partitions/files originally, but then overwrote the folder with a DataFrame that only had 6 partitions, the resulting folder will have the 6 partitions/files.
See the Spark SQL documentation for more information about the mode options.
I think there is a better solution. Make your div to print cover the entire document, but only when it's printed:
@media print {
.myDivToPrint {
background-color: white;
height: 100%;
width: 100%;
position: fixed;
top: 0;
left: 0;
margin: 0;
padding: 15px;
font-size: 14px;
line-height: 18px;
}
}
SELECT DATEADD(m,DATEDIFF(m,0,GETDATE())-1,0) AS PreviousMonthStart
SELECT DATEADD(ms,-2,DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)) AS PreviousMonthEnd
I suddenly got an error like in any directory I tried to run any git command from:
fatal: Not a git repository: /Users/me/Desktop/../../.git/modules/some-submodule
For me, turned out I had a hidden file .git
on my Desktop with the content:
gitdir: ../../.git/modules/some-module
Removed that file and fixed.
I use following setenv.bat
contents:
==============setenv.bat============
set JAVA_OPTS=-XX:MaxPermSize=256m -Xms256M -Xmx768M -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=7777,server=y,suspend=n %JAVA_OPTS%
====================================
It also enables debugging and sets debug port to 7777, and appends previous content of JAVA_OPTS
.
Basend on the example of Gary Kerr and as proposed here one may create empty circles related to specified values with following code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.markers import MarkerStyle
x = np.random.randn(60)
y = np.random.randn(60)
z = np.random.randn(60)
g=plt.scatter(x, y, s=80, c=z)
g.set_facecolor('none')
plt.colorbar()
plt.show()
Thanks a ton for Bhaskar Karambelkar's answer which explains in detail and fixed my issue. But also I would like to re phrase the answer in three simple steps for someone who is in a hurry to fix
wsdlLocation= "http://localhost/wsdl/yourwsdlname.wsdl"
Create an xml file jax-ws-catalog.xml under META-INF as below
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog"
prefer="system">
<system systemId="http://localhost/wsdl/yourwsdlname.wsdl" uri="wsdl/yourwsdlname.wsdl" />
</catalog>
Now package your jar. No more reference to the local directory, it's all packaged and referenced within
In general software terms, an "artifact" is something produced by the software development process, whether it be software related documentation or an executable file.
In Maven terminology, the artifact is the resulting output of the maven build, generally a jar
or war
or other executable file. Artifacts in maven are identified by a coordinate system of groupId, artifactId, and version. Maven uses the groupId
, artifactId
, and version
to identify dependencies (usually other jar files) needed to build and run your code.
Prints all the rows with NA data:
tmp <- data.frame(c(1,2,3),c(4,NA,5));
tmp[round(which(is.na(tmp))/ncol(tmp)),]
A much more simple solution (thanks to http://daniel.fone.net.nz/blog/2014/12/01/fixing-connection-errors-after-upgrading-postgres/) . I had upgraded to postgres 9.4. In my case, all I needed to do (after a day of googling and not succeeding)
gem uninstall pg
gem uninstall activerecord-postgresql-adapter
bundle install
Restart webrick, and done!
Try opening the localhost in your browser. Just type: localhost:3000
in the address bar.
If the app opens-up, it means your previous npm run
is still active. Now, you can just make changes to the code and see the effects if you are designing the same app, or if you wanna run another app, just tweak the code (in index.js of previously running app) a little-bit and (probably refresh the browser tab) to make it crash ;)..... Now go run npm run start
again from your new app directory. Hope this helps! :)
or
You can open the Task Manager (WINDOWS_KEY+X > Task Manager) and you'll see the "Node.js:Server-side JavaScript" row. Select that and end task....It should work now!!
If not, change the .env
file of your app to include port:3002
and run the new app. This will allow you to run two separate apps on different ports. Cheers!!
If the below statment is present in your class then your log4j.properties should be in java source(src) folder , if it is jar executable it should be packed in jar not a seperate file.
static Logger log = Logger.getLogger(MyClass.class);
Thanks,
While I haven't found a good way to specify proxy network credentials in the web.config, you might find that you can still use a non-coding solution, by including this in your web.config:
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy proxyaddress="proxyAddress" usesystemdefault="True"/>
</defaultProxy>
</system.net>
The key ingredient in getting this going, is to change the IIS settings, ensuring the account that runs the process has access to the proxy server. If your process is running under LocalService, or NetworkService, then this probably won't work. Chances are, you'll want a domain account.
You can use the template syntax of ngFor
on groups
and the usual syntax inside it for the actual rows like:
<table>
<template let-group ngFor [ngForOf]="groups">
<tr *ngFor="let row of group.items">{{row}}</tr>
</template>
</table>
Even though @Ignacio gave you a straightforward solution, I thought I might add an answer that gives you some more details about the issues with your code...
# You are not saving this result into a variable to reuse
os.path.join(src_dir, f)
# Should be
src_path = os.path.join(src_dir, f)
# you open the file but you dont again use a variable to reference
with open(f)
# should be
with open(src_path) as fh
# this is actually just looping over each character
# in each result of your os.listdir
for line in f
# you should loop over lines in the open file handle
for line in fh
# write? Is this a method you wrote because its not a python builtin function
write(line)
# write to the file
fh.write(line)
Even better... one liner in Kotlin...
// gets your previous attributes in XML, plus adds AllCaps filter
<your_edit_text>.setFilters(<your_edit_text>.getFilters() + InputFilter.AllCaps())
Done!
Use heroku's fork
Use the new "heroku fork" command! It will copy all the environment and you have to update the github repo after!
heroku fork -a sourceapp targetapp
Clone it local
git clone [email protected]:youamazingapp.git
Make a new repo on github and add it
git remote add origin https://github.com/yourname/your_repo.git
Push on github
git push origin master
sudo dscl . -append /Groups/wheel wheel $(whoami)
chmod -R 775 ${this_is_your_python_package_path}
pip3 install requests
and got:File "/usr/local/python3/lib/python3.6/os.py", line 220, in makedirs
mkdir(name, mode)
PermissionError: [Errno 13] Permission denied:
'/usr/local/python3/lib/python3.6/site-packages/requests'
cd /usr/local/python3/lib/python3.6/site-packages
,
then ls -al
and got:drwxr-xr-x 6 root wheel 192B 2 27 18:06 requests/
when i saw this, i understood, makedirs is an action of write,
but the requests mode drwxrwxr-x
displaied only user root
can write the requests file.
If add yutou(whoami
) to the group wheel, and modify the package
to the group wheel can write, then i can write, and the problem solved.
How to add yutou to group wheel?
+ detect group wheel, sudo dscl . -list /groups GroupMembership
, you will find:
wheel root
the group wheel only one member root.
+ add yutou to group wheel, sudo dscl . -append /Groups/wheel wheel yutou
.
+ check, sudo dscl . -list /groups GroupMembership
:
wheel root yutou
modify the python package mode
chmod -R 775 /usr/local/python3/lib/python3.6
In my case, I modified hibernate-core source code, well, to introduce a new annotation @DefaultValue
:
commit 34199cba96b6b1dc42d0d19c066bd4d119b553d5
Author: Lenik <xjl at 99jsj.com>
Date: Wed Dec 21 13:28:33 2011 +0800
Add default-value ddl support with annotation @DefaultValue.
diff --git a/hibernate-core/src/main/java/org/hibernate/annotations/DefaultValue.java b/hibernate-core/src/main/java/org/hibernate/annotations/DefaultValue.java
new file mode 100644
index 0000000..b3e605e
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/annotations/DefaultValue.java
@@ -0,0 +1,35 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+
+/**
+ * Specify a default value for the column.
+ *
+ * This is used to generate the auto DDL.
+ *
+ * WARNING: This is not part of JPA 2.0 specification.
+ *
+ * @author ???
+ */
[email protected]({ FIELD, METHOD })
+@Retention(RUNTIME)
+public @interface DefaultValue {
+
+ /**
+ * The default value sql fragment.
+ *
+ * For string values, you need to quote the value like 'foo'.
+ *
+ * Because different database implementation may use different
+ * quoting format, so this is not portable. But for simple values
+ * like number and strings, this is generally enough for use.
+ */
+ String value();
+
+}
diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java
index b289b1e..ac57f1a 100644
--- a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java
+++ b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java
@@ -29,6 +29,7 @@ import org.hibernate.AnnotationException;
import org.hibernate.AssertionFailure;
import org.hibernate.annotations.ColumnTransformer;
import org.hibernate.annotations.ColumnTransformers;
+import org.hibernate.annotations.DefaultValue;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.cfg.annotations.Nullability;
import org.hibernate.mapping.Column;
@@ -65,6 +66,7 @@ public class Ejb3Column {
private String propertyName;
private boolean unique;
private boolean nullable = true;
+ private String defaultValue;
private String formulaString;
private Formula formula;
private Table table;
@@ -175,7 +177,15 @@ public class Ejb3Column {
return mappingColumn.isNullable();
}
- public Ejb3Column() {
+ public String getDefaultValue() {
+ return defaultValue;
+ }
+
+ public void setDefaultValue(String defaultValue) {
+ this.defaultValue = defaultValue;
+ }
+
+ public Ejb3Column() {
}
public void bind() {
@@ -186,7 +196,7 @@ public class Ejb3Column {
}
else {
initMappingColumn(
- logicalColumnName, propertyName, length, precision, scale, nullable, sqlType, unique, true
+ logicalColumnName, propertyName, length, precision, scale, nullable, sqlType, unique, defaultValue, true
);
log.debug( "Binding column: " + toString());
}
@@ -201,6 +211,7 @@ public class Ejb3Column {
boolean nullable,
String sqlType,
boolean unique,
+ String defaultValue,
boolean applyNamingStrategy) {
if ( StringHelper.isNotEmpty( formulaString ) ) {
this.formula = new Formula();
@@ -217,6 +228,7 @@ public class Ejb3Column {
this.mappingColumn.setNullable( nullable );
this.mappingColumn.setSqlType( sqlType );
this.mappingColumn.setUnique( unique );
+ this.mappingColumn.setDefaultValue(defaultValue);
if(writeExpression != null && !writeExpression.matches("[^?]*\\?[^?]*")) {
throw new AnnotationException(
@@ -454,6 +466,11 @@ public class Ejb3Column {
else {
column.setLogicalColumnName( columnName );
}
+ DefaultValue _defaultValue = inferredData.getProperty().getAnnotation(DefaultValue.class);
+ if (_defaultValue != null) {
+ String defaultValue = _defaultValue.value();
+ column.setDefaultValue(defaultValue);
+ }
column.setPropertyName(
BinderHelper.getRelativePath( propertyHolder, inferredData.getPropertyName() )
diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java
index e57636a..3d871f7 100644
--- a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java
+++ b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java
@@ -423,6 +424,7 @@ public class Ejb3JoinColumn extends Ejb3Column {
getMappingColumn() != null ? getMappingColumn().isNullable() : false,
referencedColumn.getSqlType(),
getMappingColumn() != null ? getMappingColumn().isUnique() : false,
+ null, // default-value
false
);
linkWithValue( value );
@@ -502,6 +504,7 @@ public class Ejb3JoinColumn extends Ejb3Column {
getMappingColumn().isNullable(),
column.getSqlType(),
getMappingColumn().isUnique(),
+ null, // default-value
false //We do copy no strategy here
);
linkWithValue( value );
Well, this is a hibernate-only solution.
echo -e ' \t '
will echo 'space tab space newline' (-e
means 'enable interpretation of backslash escapes'):
$ echo -e ' \t ' | hexdump -C
00000000 20 09 20 0a | . .|
Bjarne Stroustrup's FAQ answer on this matter says:
I don't like garbage. I don't like littering. My ideal is to eliminate the need for a garbage collector by not producing any garbage. That is now possible.
The situation, for code written these days (C++17 and following the official Core Guidelines) is as follows:
Indeed, you could just disregard all of the guidelines and write leaky application code - and it will compile and run (and leak), same as always.
But it's not a "just don't do that" situation, where the developer is expected to be virtuous and exercise a lot of self control; it's just not simpler to write non-conforming code, nor is it faster to write, nor is it better-performing. Gradually it will also become more difficult to write, as you would face an increasing "impedance mismatch" with what conforming code provides and expects.
reintrepret_cast
? Or do complex pointer arithmetic? Or other such hacks?"Indeed, if you put your mind to it, you can write code that messes things up despite playing nice with the guidelines. But:
If you're a C++ library developer then you do write unsafe code involving raw pointers, and you are required to code carefully and responsibly - but these are self-contained pieces of code written by experts (and more importantly, reviewed by experts).
So, it's just like Bjarne said: There's really no motivation to collect garbage generally, as you all but make sure not to produce garbage. GC is becoming a non-problem with C++.
That is not to say GC isn't an interesting problem for certain specific applications, when you want to employ custom allocation and de-allocations strategies. For those you would want custom allocation and de-allocation, not a language-level GC.
I'am trying to install SQL SERVER developer 2008 R2 alongside SQL SERVER 2005 EXPRESS,
i went to program features, clicked on unistall SQL SERVER 2005 EXPRESS, and only checked, WORKSTATION COMPONENTS, it unistalled: support files, sql mngmt studio
After that installation of sql 2008 r2 developer went ok....
Hopes this helps somebody
If you'd prefer a more direct approach, one that does NOT mess with symlinking between /etc/nginx/sites-available
and /etc/nginx/sites-enabled
, do the following:
/etc/nginx/nginx.conf
include /etc/nginx/conf.d/*.conf;
This tells nginx to pull in any files in the conf.d
directory that end in .conf
. (I know: it's weird that a directory can have a .
in it.)conf.d
directory if it doesn't already exist (per the path in step 3). Be sure to give it the right permissions/ownership. Likely root or www-data. /etc/nginx/sites-available
) into the directory conf.d
.Any .conf
files that you put into the conf.d
directory from here on out will become active as long as you reload/restart nginx after.
Note: You can use the conf.d
and sites-enabled
+ sites-available
method concurrently if you wish. I like to test on my dev box using conf.d
. Feels faster than symlinking and unsymlinking.
Routes
export const MyRoutes: Routes = [
{ path: '/items/:id', component: MyComponent }
]
Component
import { ActivatedRoute } from '@angular/router';
public id: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
}
To @R.. I think it's not enough to check errno
for error detection in strtol
call.
long strtol (const char *String, char **EndPointer, int Base)
You'll also need to check EndPointer
for errors.
FormsModule
should be added at imports array
not declarations array
.
BrowserModule
, FormsModule
, HttpModule
Components
, Pipes
, Directives
refer below change:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
Neither. You set the isolation level to READ UNCOMMITTED
which is always better than giving individual lock hints. Or, better still, if you care about details like consistency, use snapshot isolation.
Create bitmap from file path:
File sd = Environment.getExternalStorageDirectory();
File image = new File(sd+filePath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
imageView.setImageBitmap(bitmap);
If you want to scale the bitmap to the parent's height and width then use Bitmap.createScaledBitmap
function.
I think you are giving the wrong file path. :) Hope this helps.
Create for the input a click event and a change event. The click event empties the input and the change event contains the code you want to execute.
So the click event will empty when you click the input button(before the select file windows opens), therefor the change event will always trigger when you select a file.
$("#input").click(function() {_x000D_
$("#input").val("")_x000D_
});_x000D_
_x000D_
$("#input").change(function() {_x000D_
//Your code you want to execute!_x000D_
});
_x000D_
<input id="input" type="file">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">_x000D_
</script>
_x000D_
Use the Responsive Design Tool using Ctrl + Shift + M.
I was trying to achieve something similar, but without any external dependency. The application was already using DOM to format just for logging the XMLs!
Here is my sample snippet
public void formatXML(final String unformattedXML) {
final int length = unformattedXML.length();
final int indentSpace = 3;
final StringBuilder newString = new StringBuilder(length + length / 10);
final char space = ' ';
int i = 0;
int indentCount = 0;
char currentChar = unformattedXML.charAt(i++);
char previousChar = currentChar;
boolean nodeStarted = true;
newString.append(currentChar);
for (; i < length - 1;) {
currentChar = unformattedXML.charAt(i++);
if(((int) currentChar < 33) && !nodeStarted) {
continue;
}
switch (currentChar) {
case '<':
if ('>' == previousChar && '/' != unformattedXML.charAt(i - 1) && '/' != unformattedXML.charAt(i) && '!' != unformattedXML.charAt(i)) {
indentCount++;
}
newString.append(System.lineSeparator());
for (int j = indentCount * indentSpace; j > 0; j--) {
newString.append(space);
}
newString.append(currentChar);
nodeStarted = true;
break;
case '>':
newString.append(currentChar);
nodeStarted = false;
break;
case '/':
if ('<' == previousChar || '>' == unformattedXML.charAt(i)) {
indentCount--;
}
newString.append(currentChar);
break;
default:
newString.append(currentChar);
}
previousChar = currentChar;
}
newString.append(unformattedXML.charAt(length - 1));
System.out.println(newString.toString());
}
You can also use:
Get-WmiObject -Class "Win32_computersystem" | Select *
This will show the same result as Format-List * used in the other answers here.
You can try this for webview in a fragment:
private lateinit var webView: WebView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_name, container, false)
webView = root!!.findViewById(R.id.home_web_view)
var url: String = "http://yoururl.com"
webView.settings.javaScriptEnabled = true
webView.webViewClient = WebViewClient()
webView.loadUrl(url)
webView.canGoBack()
webView.setOnKeyListener{ v, keyCode, event ->
if(keyCode == KeyEvent.KEYCODE_BACK && event.action == MotionEvent.ACTION_UP
&& webView.canGoBack()){
webView.goBack()
return@setOnKeyListener true
}
false
}
return root
}
you need to take 2 (hex) chars at the same time... then calculate the int value and after that make the char conversion like...
char d = (char)intValue;
do this for every 2chars in the hex string
this works if the string chars are only 0-9A-F:
#include <stdio.h>
#include <string.h>
int hex_to_int(char c){
int first = c / 16 - 3;
int second = c % 16;
int result = first*10 + second;
if(result > 9) result--;
return result;
}
int hex_to_ascii(char c, char d){
int high = hex_to_int(c) * 16;
int low = hex_to_int(d);
return high+low;
}
int main(){
const char* st = "48656C6C6F3B";
int length = strlen(st);
int i;
char buf = 0;
for(i = 0; i < length; i++){
if(i % 2 != 0){
printf("%c", hex_to_ascii(buf, st[i]));
}else{
buf = st[i];
}
}
}
0 [main] us 0 init_cheap: VirtualAlloc pointer is null, Win32 error 487
AllocationBase 0x0, BaseAddress 0x68570000, RegionSize 0x2A0000, State 0x10000
PortableGit\bin\bash.exe: *** Couldn't reserve space for cygwin's heap, Win32 error 0
This symptom by itself has nothing to do with image bases of executables, corrupted Cygwin's shared memory sections, conflicting versions of DLLs etc.
It's Cygwin code failing to allocate a ~5 MB large chunk of memory for its heap at this fixed address 0x68570000, while only a hole ~2.5 MB large was apparently available there. The relevant code can be seen in msysgit source.
There can be many reasons. In my case it was some other modules loaded at a conflicting address:
The last address would be around 0x68570000 + 5 MB = 0x68C50000, but there are these WOW64-related DLLs loaded from 0x68810000 upwards, which block the allocation.
Whenever there is some shared DLL, Windows in general tries to load it at the same virtual address in all processes to save some relocation processing. It's just a matter of bad luck that these system components got somehow loaded at a conflicting address this time.
Because Git is a rich suite consisting of some low level commands and a lot of helpful utilities, and mostly developed on Unix-like systems. In order to be able to build it and run it without massive rewriting, it need at least a partial Unix-like environment.
To accomplish that, people have invented MinGW and MSYS - a minimal set of build tools to develop programs on Windows in an Unix-like fashion. MSYS also contains a shared library, this msys-1.0.dll
, which helps with some of the compatibility issues between the two platforms during runtime. And many parts of that have been taken from Cygwin, because someone already had to solve the same problems there.
So it's not Cygwin, it's MinGW's runtime DLL what's behaving weird here.
In Cygwin, this code has actually changed a lot since what's in MSYS 1.0 - the last commit message for that file says "Import Cygwin 1.3.4", which is from 2001!
Both current Cygwin and the new version of MSYS - MSYS2 - already have different logic in place, which is hopefully more robust. It's only old versions of Git for Windows which have been still built using the old broken MSYS system.
PATH
can sometimes work because there might be different versions of msys-1.0.dll
in different versions of Git or other MSYS-based applications, which perhaps use different address, different size of this heap etc.msys-1.0.dll
might be a waste of time, because 1) being a DLL, it already has relocation information and 2) "in any version of Windows OS there is no guarantee that a (...) DLL will always load at same address space" anyway (source). The only way this can help is if the msys-1.0.dll
itself loads at the conflicting address it's then trying to use. Apparently that's the case sometimes, as this is what the Git for Windows guys are doing automatically on 32-bit systems.msys-1.0.dll
binary to use a different value for _cygheap_start
and that resolved the problem immediately.As firefox does not stringify some object as screen object ; if you want to have the same result such as : JSON.stringify(obj)
:
function objToString (obj) {
var tabjson=[];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
tabjson.push('"'+p +'"'+ ':' + obj[p]);
}
} tabjson.push()
return '{'+tabjson.join(',')+'}';
}
To answer your extra question
:
You can set which rows should be repeated on every page using:
$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);
Now, row 1, 2, 3, 4 and 5 will be repeated.
Not sure about solutions but a temporary workaround is to ask eslint to ignore it by adding the following on top of the problem line.
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
Place this at the beginning of your script.rb
#!/usr/bin/env ruby
Then mark it as executable:
chmod +x script.rb
If you want to check syntax error for any nginx files, you can use the -c option.
[root@server ~]# sudo nginx -t -c /etc/nginx/my-server.conf
nginx: the configuration file /etc/nginx/my-server.conf syntax is ok
nginx: configuration file /etc/nginx/my-server.conf test is successful
[root@server ~]#
Before going into these three option one must understand 3 things.
1) History/HEAD
2) Stage/index
3) Working directory
reset --soft : History changed, HEAD changed, Working directory is not changed.
reset --mixed : History changed, HEAD changed, Working directory changed with unstaged data.
reset --hard : History changed, HEAD changed, Working directory is changed with lost data.
It is always safe to go with Git --soft. One should use other option in complex requirement.
Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result)
to see what you really got.
Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.
No there's not and developers still don't know why google doesn't pay attention to this request!
As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!
In addition to the other answers, I ran across this because I'm a C# programmer primarily, but trying to keep fresh in Java. I noticed that when I tried to use StringUtils
my IDE (Eclipse) imported it from com.mysql.jdbc.StringUtils
which actually has an isNullOrEmpty(myStringObject)
method.
ex.
import com.mysql.jdbc.StringUtils;
StringUtils.isNullOrEmpty(host)
Just another alternative for those who already have the MySQL connector referenced in your project, but not the other StringUtils
library.
Modify to suit your specifics, or make more generic as needed:
Private Sub CopyItOver()
Set NewBook = Workbooks.Add
Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub
this code runs permanently!!! created by diko(Turkey)
public void mysql() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
thrd1 = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
}
if (con == null) {
try {
con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");
} catch (SQLException e) {
e.printStackTrace();
con = null;
}
if ((thrd2 != null) && (!thrd2.isAlive()))
thrd2.start();
}
}
}
});
if ((thrd1 != null) && (!thrd1.isAlive())) thrd1.start();
thrd2 = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
if (con != null) {
try {
// con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");
Statement st = con.createStatement();
String ali = "'fff'";
st.execute("INSERT INTO deneme (name) VALUES(" + ali + ")");
// ResultSet rs = st.executeQuery("select * from deneme");
// ResultSetMetaData rsmd = rs.getMetaData();
// String result = new String();
// while (rs.next()) {
// result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
// result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
// }
} catch (SQLException e) {
e.printStackTrace();
con = null;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
}
It may be nicer one to use slice like :
string.slice(1, -1)
For Windows:
C:\Program Files\java\jdk\bin
after a semicolon. If you need to target multiple classes use:
#main_text .title, #main_text .title2 {
/* Properties */
}
COALESCE(field, 'default')
For example:
SELECT
t.id,
COALESCE(d.field, 'default')
FROM
test t
LEFT JOIN
detail d ON t.id = d.item
Also, you can use multiple columns to check their NULL
by COALESCE function.
For example:
mysql> SELECT COALESCE(NULL, 1, NULL);
-> 1
mysql> SELECT COALESCE(0, 1, NULL);
-> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
-> NULL
michal.kreuzman nice one I will have to say. It was useful.
However, the above works only for single digits: if you are going to use more than one digit, the structure is going to get misplaced since you are using spaces and not tabs.
As for my later codes I needed more digits than only 2, so I made a program myself.
It has some bugs now, again right now I am feeling lazy to correct them but it prints very beautifully and the nodes can take a larger number of digits.
The tree is not going to be as the question mentions but it is 270 degrees rotated :)
public static void printBinaryTree(TreeNode root, int level){
if(root==null)
return;
printBinaryTree(root.right, level+1);
if(level!=0){
for(int i=0;i<level-1;i++)
System.out.print("|\t");
System.out.println("|-------"+root.val);
}
else
System.out.println(root.val);
printBinaryTree(root.left, level+1);
}
Place this function with your own specified TreeNode and keep the level initially 0, and enjoy!
Here are some of the sample outputs:
| | |-------11
| |-------10
| | |-------9
|-------8
| | |-------7
| |-------6
| | |-------5
4
| |-------3
|-------2
| |-------1
| | | |-------10
| | |-------9
| |-------8
| | |-------7
|-------6
| |-------5
4
| |-------3
|-------2
| |-------1
Only problem is with the extending branches; I will try to solve the problem as soon as possible but till then you can use it too.
I work a lot with CSS panel and it's too slow in Safari Web Inspector. Apple knows about this problem and promise to fix this bug with freezes, except this thing web tools is much more powerful and convenient than firebug in mozilla, so waiting for fix.
You can redefine/overwrite the default font-awesome sizes and also add you own sizes
.fa-1x{
font-size:0.8em;
}
.fa-2x{
font-size:1em;
}
.fa-3x{
font-size:1.2em;
}
.fa-4x{
font-size:1.4em;
}
.fa-5x{
font-size:1.6em;
}
.fa-mycustomx{
font-size:3.2em;
}
Since you have wiped out your computer and want to checkout your project again, you could start by doing the below initial settings:
git config --global user.name "Your Name"
git config --global user.email [email protected]
Login to your github account, go to the repository you want to clone, and copy the URL under "Clone with HTTPS".
You can clone the remote repository by using HTTPS, even if you had setup SSH the last time:
git clone https://github.com/username/repo-name.git
NOTE:
If you had setup SSH for your remote repository previously, you will have to add that key to the known hosts ssh file on your PC; if you don't and try to do git clone [email protected]:username/repo-name.git
, you will see an error similar to the one below:
Cloning into 'repo-name'...
The authenticity of host 'github.com (192.30.255.112)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXDoJWGl7E1IGOCspZomTxdCARLviMw6E5SY8.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'github.com,192.30.255.112' (RSA) to the list of known hosts.
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
Using HTTPS is a easier than SSH in this case.
Design patterns aren't trivially reusable solutions.
Design patterns are reusable, by definition. They're patterns you detect in other good solutions.
A pattern is not trivially reusable. You can implement your down design following the pattern however.
Relational design patters include things like:
One-to-Many relationships (master-detail, parent-child) relationships using a foreign key.
Many-to-Many relationships with a bridge table.
Optional one-to-one relationships managed with NULLs in the FK column.
Star-Schema: Dimension and Fact, OLAP design.
Fully normalized OLTP design.
Multiple indexed search columns in a dimension.
"Lookup table" that contains PK, description and code value(s) used by one or more applications. Why have code? I don't know, but when they have to be used, this is a way to manage the codes.
Uni-table. [Some call this an anti-pattern; it's a pattern, sometimes it's bad, sometimes it's good.] This is a table with lots of pre-joined stuff that violates second and third normal form.
Array table. This is a table that violates first normal form by having an array or sequence of values in the columns.
Mixed-use database. This is a database normalized for transaction processing but with lots of extra indexes for reporting and analysis. It's an anti-pattern -- don't do this. People do it anyway, so it's still a pattern.
Most folks who design databases can easily rattle off a half-dozen "It's another one of those"; these are design patterns that they use on a regular basis.
And this doesn't include administrative and operational patterns of use and management.
You can do this using additional effects as a part of jQuery-ui
$('.show_hide').click(function () {
$(".slidingDiv").toggle("slide");
});
There is no elegant way of getting the last element of a list in Java (compared to e.g. items[-1]
in Python).
You have to use list.get(list.size()-1)
.
When working with lists obtained by complicated method calls, the workaround lies in temporary variable:
List<E> list = someObject.someMethod(someArgument, anotherObject.anotherMethod());
return list.get(list.size()-1);
This is the only option to avoid ugly and often expensive or even not working version:
return someObject.someMethod(someArgument, anotherObject.anotherMethod()).get(
someObject.someMethod(someArgument, anotherObject.anotherMethod()).size() - 1
);
It would be nice if fix for this design flaw was introduced to Java API.
What's wrong with this?
foo.replace(" ", "")[:-3].upper()
Your convention seems to be reasonable. If I were searching for your framework in the Maven repo, I would look for awesome-inhouse-framework-x.y.jar
in com.mycompany.awesomeinhouseframework
group directory. And I would find it there according to your convention.
Two simple rules work for me:
The python seaborn module is based on matplotlib, and produces a very nice heatmap.
Below is an implementation with seaborn, designed for the ipython/jupyter notebook.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# import the data directly into a pandas dataframe
nba = pd.read_csv("http://datasets.flowingdata.com/ppg2008.csv", index_col='Name ')
# remove index title
nba.index.name = ""
# normalize data columns
nba_norm = (nba - nba.mean()) / (nba.max() - nba.min())
# relabel columns
labels = ['Games', 'Minutes', 'Points', 'Field goals made', 'Field goal attempts', 'Field goal percentage', 'Free throws made',
'Free throws attempts', 'Free throws percentage','Three-pointers made', 'Three-point attempt', 'Three-point percentage',
'Offensive rebounds', 'Defensive rebounds', 'Total rebounds', 'Assists', 'Steals', 'Blocks', 'Turnover', 'Personal foul']
nba_norm.columns = labels
# set appropriate font and dpi
sns.set(font_scale=1.2)
sns.set_style({"savefig.dpi": 100})
# plot it out
ax = sns.heatmap(nba_norm, cmap=plt.cm.Blues, linewidths=.1)
# set the x-axis labels on the top
ax.xaxis.tick_top()
# rotate the x-axis labels
plt.xticks(rotation=90)
# get figure (usually obtained via "fig,ax=plt.subplots()" with matplotlib)
fig = ax.get_figure()
# specify dimensions and save
fig.set_size_inches(15, 20)
fig.savefig("nba.png")
The output looks like this: I used the matplotlib Blues color map, but personally find the default colors quite beautiful. I used matplotlib to rotate the x-axis labels, as I couldn't find the seaborn syntax. As noted by grexor, it was necessary to specify the dimensions (fig.set_size_inches) by trial and error, which I found a bit frustrating.
As noted by Paul H, you can easily add the values to heat maps (annot=True), but in this case I didn't think it improved the figure. Several code snippets were taken from the excellent answer by joelotz.
If you are using sagemath cloud version, you can simply go to the left corner,
select File --> Download as --> Pdf via LaTeX (.pdf)
Check the screenshot if you want.
Screenshot Convert ipynb to pdf
If it dosn't work for any reason, you can try another way.
select File --> Print Preview and then on the preview
right click --> Print and then select save as pdf.
Actually, you can use two phases to translate your texts in Swift projects:
1) The first phase is using the old way to create all your translatable strings:
NSLocalisedString("Text to translate", comment: "Comment to comment")
1.1) Then you should use genstrings to generate Localizable.strings:
$ genstrings *swift
2) Afterwards, you should use this answer.
2.1) Use your XCode "Find and Replace" option based on the regular expression. As for the given example (if you have no comments) the regular expression will be:
NSLocalizedString\((.*)\, comment:\ \"\"\)
and replace it with
$1.localized
or (if you have comments)
NSLocalizedString\((.*)\, comment:\ (.*)\)
and replace it with
$1.localizedWithComment(comment: $2)
You are free to play with regex and different extension combinations as you wish. The general way is splitting the whole process in two phases. Hope that helps.
You have not specified the schema location of the context namespace, that is the reason for this specific error:
<beans .....
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
Normally, if you look up any software issue on stackoverflow, you quickly find a clear answer. But in CSS, even something as simple as "center a form" leads to a long discussion, and lots of failed solutions.
Correction: orfdorf's solution (above) works.
The Github application for Windows shows all remote branches of a repository. If you have deleted the branch locally with $ git branch -d [branch_name]
, the remote branch still exists in your Github repository and will appear regardless in the Windows Github application.
If you want to delete the branch completely (remotely as well), use the above command in combination with $ git push origin :[name_of_your_new_branch]
. Warning: this command erases all existing branches and may cause loss of code. Be careful, I do not think this is what you are trying to do.
However every time you delete the local branch changes, the remote branch will still appear in the application. If you do not want to keep making changes, just ignore it and do not click, otherwise you may clone the repository. If you had any more questions, please let me know.
No, Google Chrome does not work with Selenium IDE. As Selenium IDE is a Firefox plugin it works only with FF.
According to your last portion of question: Or is there any alternative tool which can work with Chrome? The possible answer is as follows:
You can use Sahi with Chrome. Sahi Test Automation tool supports Chrome, Firefox and IE. You can visit for details:
Try this:
int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);
String weekday = new DateFormatSymbols().getShortWeekdays()[dayOfWeek];
I got the same problem and my solution was to remove webconfig file from the directory.. then it works..
How about the PATINDEX function?
The pattern matching in TSQL is not a complete regex library, but it gives you the basics.
(From Books Online)
Wildcard Meaning
% Any string of zero or more characters.
_ Any single character.
[ ] Any single character within the specified range
(for example, [a-f]) or set (for example, [abcdef]).
[^] Any single character not within the specified range
(for example, [^a - f]) or set (for example, [^abcdef]).
Once app is published once it cannot be deleted from the listing in your console, but rather you can unpublish it only and if you want you can use the filters to hide it from the listing, but the draft apps you can delete them or hide them.
If you are looking for something very accurate, you need to use some better tool than tf-idf. Universal sentence encoder is one of the most accurate ones to find the similarity between any two pieces of text. Google provided pretrained models that you can use for your own application without a need to train from scratch anything. First, you have to install tensorflow and tensorflow-hub:
pip install tensorflow
pip install tensorflow_hub
The code below lets you convert any text to a fixed length vector representation and then you can use the dot product to find out the similarity between them
import tensorflow_hub as hub
module_url = "https://tfhub.dev/google/universal-sentence-encoder/1?tf-hub-format=compressed"
# Import the Universal Sentence Encoder's TF Hub module
embed = hub.Module(module_url)
# sample text
messages = [
# Smartphones
"My phone is not good.",
"Your cellphone looks great.",
# Weather
"Will it snow tomorrow?",
"Recently a lot of hurricanes have hit the US",
# Food and health
"An apple a day, keeps the doctors away",
"Eating strawberries is healthy",
]
similarity_input_placeholder = tf.placeholder(tf.string, shape=(None))
similarity_message_encodings = embed(similarity_input_placeholder)
with tf.Session() as session:
session.run(tf.global_variables_initializer())
session.run(tf.tables_initializer())
message_embeddings_ = session.run(similarity_message_encodings, feed_dict={similarity_input_placeholder: messages})
corr = np.inner(message_embeddings_, message_embeddings_)
print(corr)
heatmap(messages, messages, corr)
and the code for plotting:
def heatmap(x_labels, y_labels, values):
fig, ax = plt.subplots()
im = ax.imshow(values)
# We want to show all ticks...
ax.set_xticks(np.arange(len(x_labels)))
ax.set_yticks(np.arange(len(y_labels)))
# ... and label them with the respective list entries
ax.set_xticklabels(x_labels)
ax.set_yticklabels(y_labels)
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right", fontsize=10,
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
for i in range(len(y_labels)):
for j in range(len(x_labels)):
text = ax.text(j, i, "%.2f"%values[i, j],
ha="center", va="center", color="w",
fontsize=6)
fig.tight_layout()
plt.show()
as you can see the most similarity is between texts with themselves and then with their close texts in meaning.
IMPORTANT: the first time you run the code it will be slow because it needs to download the model. if you want to prevent it from downloading the model again and use the local model you have to create a folder for cache and add it to the environment variable and then after the first time running use that path:
tf_hub_cache_dir = "universal_encoder_cached/"
os.environ["TFHUB_CACHE_DIR"] = tf_hub_cache_dir
# pointing to the folder inside cache dir, it will be unique on your system
module_url = tf_hub_cache_dir+"/d8fbeb5c580e50f975ef73e80bebba9654228449/"
embed = hub.Module(module_url)
More information: https://tfhub.dev/google/universal-sentence-encoder/2
You can clear the error state and empty the stringstream all in one line
std::stringstream().swap(m); // swap m with a default constructed stringstream
This effectively resets m to a default constructed state
You need a regular expression like "\\s+"
, which means: split whenever at least one whitespace is encountered. The full Java code is:
try {
String[] splitArray = input.split("\\s+");
} catch (PatternSyntaxException ex) {
//
}
Since your script is in <head>
, you need to wrap it in window.onload
:
window.onload = function () {
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
};
You can also do it in this way
<body onload="addList()">
When we use CommandObj.Parameter.Add()
it takes 2 parameters, the first is procedure parameter and the second is its data type, while .AddWithValue()
takes 2 parameters, the first is procedure parameter and the second is the data variable
CommandObj.Parameter.Add("@ID",SqlDbType.Int).Value=textBox1.Text;
for .AddWithValue
CommandObj.Parameter.AddWitheValue("@ID",textBox1.Text);
where ID
is the parameter of stored procedure which data type is Int
I believe this is probably faster than any other way if you don't care about the lists order, if you do take care about the final order store the indexes from the original and resort by that.
category_ids.sort()
ones_last_index = category_ids.count('1')
del category_ids[0:ones_last_index]
There is no way to do so. Either use an HTML table, or put the same text on several cells.
like this:
| Can Reorder | 2nd operation |2nd operation |2nd operation |
| :---: | --- |
|1st operation|Normal Load <br/>Normal Store| Volatile Load <br/>MonitorEnter|Volatile Store<br/> MonitorExit|
|Normal Load <br/> Normal Store| | | No|
|Volatile Load <br/> MonitorEnter| No|No|No|
|Volatile store <br/> MonitorExit| | No|No|
which looks like
This trick also suitable, but in this case align properties (middle, bottom etc.) won't be working.
<td style="display: block; position: relative;">
</td>
First step is to find out which ruby is being called:
$ which ruby
Your system says:
/usr/bin/ruby
This is NOT the shim used by rbenv, which (on MacOS) should look like:
/Users/<username>/.rbenv/shims/ruby
The shim is actually a script that acts like a redirect to the version of ruby you set.
I recommend that for trouble shooting you unset the project specific "local" version, and the shell specific "shell" version and just test using the "global" version setting which is determined in a plain text file in ~/.rbenv/version which will just be the version number "1.9.3" in your case.
$ rbenv global 1.9.3
$ rbenv local --unset
$ rbenv shell --unset
You can do ls -laG
in the root of your project folder (not the home folder) to make sure there is no longer a ".ruby-version" file there.
You can use rbenv versions
to identify which version rbenv is set to use (and the location and name of the file that is setting that):
$ rbenv versions
NONE OF THAT MATTERS until you set the path correctly.
Use this to make sure your *MacOS will obey you:
$ rbenv init -
Followed by:
$ which ruby
To make sure it looks like:
/Users/<username>/.rbenv/shims/ruby
Then run this to add the line to your profile so it runs each time you open a new terminal window:
$ echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
There are other ways to modify the path, feel free to substitute any of them instead of running the rbenv init.
NOTE: reinstall Rails with:
$ gem install rails
If you were trying to run Ruby on Rails, then you need to have this all working first, then install the rails gem again. A previous install of Rails will use a hard coded path to the wrong ruby and several other things will be in the wrong place, so just install the gem again.
P. S. If your MacOS won't obey you (*mentioned above) then you may have to find another way to modify your path, but that's unlikely to be a problem because "Macs just work" ;)
maybe a little bit late, but I come to this situation recently and found a simple solution, 2 functions are needed.
load the image.
function getImgFromUrl(logo_url, callback) {
var img = new Image();
img.src = logo_url;
img.onload = function () {
callback(img);
};
}
in onload event on first step, make a callback to use the jspdf doc.
function generatePDF(img){
var options = {orientation: 'p', unit: 'mm', format: custom};
var doc = new jsPDF(options);
doc.addImage(img, 'JPEG', 0, 0, 100, 50);}
use the above functions.
var logo_url = "/images/logo.jpg";
getImgFromUrl(logo_url, function (img) {
generatePDF(img);
});
The fastest way, to get a hash string for password store purposes, is a following code:
internal static string GetStringSha256Hash(string text)
{
if (String.IsNullOrEmpty(text))
return String.Empty;
using (var sha = new System.Security.Cryptography.SHA256Managed())
{
byte[] textData = System.Text.Encoding.UTF8.GetBytes(text);
byte[] hash = sha.ComputeHash(textData);
return BitConverter.ToString(hash).Replace("-", String.Empty);
}
}
Remarks:
sha
variable should be refactored into a class field;this is a kind of brief solution,that add a row to local exclude file.
echo YOURFILE_OR_DIRECTOY >> .git/info/exclude
You can use the below addEvent() function to add events for most things but note that for XMLHttpRequest if (el.attachEvent)
will fail in IE8, because it doesn't support XMLHttpRequest.attachEvent()
so you have to use XMLHttpRequest.onload = function() {}
instead.
function addEvent(el, e, f) {
if (el.attachEvent) {
return el.attachEvent('on'+e, f);
}
else {
return el.addEventListener(e, f, false);
}
}
var ajax = new XMLHttpRequest();
ajax.onload = function(e) {
}
I use matplotlib for reading TIFF files:
import matplotlib.pyplot as plt
I = plt.imread(tiff_file)
and I
will be of type ndarray
.
According to the documentation though it is actually PIL that works behind the scenes when handling TIFFs as matplotlib only reads PNGs natively, but this has been working fine for me.
There's also a plt.imsave
function for saving.
If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share. If you haven't already setup a share, you could use the default administrative shares. Example:
\\localhost\c$\my_dir
... accesses a folder called "my_dir" via UNC on your C: drive. By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.
Everyone says about inflate()
, but what if we want to use it in onViewCreated()
?
You can use bind(view)
method of concrete binding class to get ViewDataBinding
instance for the view
.
Usually we write BaseFragment something like this (simplified):
// BaseFragment.kt
abstract fun layoutId(): Int
override fun onCreateView(inflater, container, savedInstanceState) =
inflater.inflate(layoutId(), container, false)
And use it in child fragment.
// ConcreteFragment.kt
override fun layoutId() = R.layout.fragment_concrete
override fun onViewCreated(view, savedInstanceState) {
val binding = FragmentConcreteBinding.bind(view)
// or
val binding = DataBindingUtil.bind<FragmentConcreteBinding>(view)
}
If all Fragments uses data binding, you can even make it simpler using type parameter.
abstract class BaseFragment<B: ViewDataBinding> : Fragment() {
abstract fun onViewCreated(binding: B, savedInstanceState: Bundle?)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
onViewCreated(DataBindingUtil.bind<B>(view)!!, savedInstanceState)
}
}
I don't know it's okay to assert non-null there, but.. you get the idea. If you want it to be nullable, you can do it.
This is my working version. Note that the resolvers code is not shown but are a spin on my implementation which allows columns to be resolved even though they are named slightly differently in each worksheet.
public static IEnumerable<T> ToArray<T>(this ExcelWorksheet worksheet, List<PropertyNameResolver> resolvers) where T : new()
{
// List of all the column names
var header = worksheet.Cells.GroupBy(cell => cell.Start.Row).First();
// Get the properties from the type your are populating
var properties = typeof(T).GetProperties().ToList();
var start = worksheet.Dimension.Start;
var end = worksheet.Dimension.End;
// Resulting list
var list = new List<T>();
// Iterate the rows starting at row 2 (ie start.Row + 1)
for (int row = start.Row + 1; row <= end.Row; row++)
{
var instance = new T();
for (int col = start.Column; col <= end.Column; col++)
{
object value = worksheet.Cells[row, col].Text;
// Get the column name zero based (ie col -1)
var column = (string)header.Skip(col - 1).First().Value;
// Gets the corresponding property to set
var property = properties.Property(resolvers, column);
try
{
var propertyName = property.PropertyType.IsGenericType
? property.PropertyType.GetGenericArguments().First().FullName
: property.PropertyType.FullName;
// Implement setter code as needed.
switch (propertyName)
{
case "System.String":
property.SetValue(instance, Convert.ToString(value));
break;
case "System.Int32":
property.SetValue(instance, Convert.ToInt32(value));
break;
case "System.DateTime":
if (DateTime.TryParse((string) value, out var date))
{
property.SetValue(instance, date);
}
property.SetValue(instance, FromExcelSerialDate(Convert.ToInt32(value)));
break;
case "System.Boolean":
property.SetValue(instance, (int)value == 1);
break;
}
}
catch (Exception e)
{
// instance property is empty because there was a problem.
}
}
list.Add(instance);
}
return list;
}
// Utility function taken from the above post's inline function.
public static DateTime FromExcelSerialDate(int excelDate)
{
if (excelDate < 1)
throw new ArgumentException("Excel dates cannot be smaller than 0.");
var dateOfReference = new DateTime(1900, 1, 1);
if (excelDate > 60d)
excelDate = excelDate - 2;
else
excelDate = excelDate - 1;
return dateOfReference.AddDays(excelDate);
}
I know that this question is old but i would like to contribute too:
The main difference between others responses is the hashmap return.
@GetMapping("...")
@ResponseBody
public Map<String, Object> endPointExample(...) {
Map<String, Object> rtn = new LinkedHashMap<>();
rtn.put("pic", image);
rtn.put("potato", "King Potato");
return rtn;
}
This will return:
{"pic":"a17fefab83517fb...beb8ac5a2ae8f0449","potato":"King Potato"}
It will look like this
<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
var step=1;
function slideit()
{
document.images.slide.src = eval("image"+step+".src");
if(step<2)
step++;
else
step=1;
setTimeout("slideit()",2500);
}
slideit();
</script>
</body>
In numpy
, index and dimension numbering starts with 0. So axis 0
means the 1st dimension. Also in numpy
a dimension can have length (size) 0. The simplest case is:
In [435]: x = np.zeros((0,), int)
In [436]: x
Out[436]: array([], dtype=int32)
In [437]: x[0]
...
IndexError: index 0 is out of bounds for axis 0 with size 0
I also get it if x = np.zeros((0,5), int)
, a 2d array with 0 rows, and 5 columns.
So someplace in your code you are creating an array with a size 0 first axis.
When asking about errors, it is expected that you tell us where the error occurs.
Also when debugging problems like this, the first thing you should do is print the shape
(and maybe the dtype
) of the suspected variables.
pandas
pandas
, when sending a Series
or DataFrame
to a numpy.array
, as with the following:
try-except
blockif x.size != 0:
:
is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]
[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"
Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.
Works with tuples and strings, too.
This is the most important thing to know about the Tuple type. Tuple is a class, not a struct. It thus will be allocated upon the managed heap. Each class instance that is allocated adds to the burden of garbage collection.
Note: The properties Item1, Item2, and further do not have setters. You cannot assign them. The Tuple is immutable once created in memory.
I’m going to hold the unpopular on SO selenium tag opinion that XPath is preferable to CSS in the longer run.
This long post has two sections - first I'll put a back-of-the-napkin proof the performance difference between the two is 0.1-0.3 milliseconds (yes; that's 100 microseconds), and then I'll share my opinion why XPath is more powerful.
Let's first tackle "the elephant in the room" – that xpath is slower than css.
With the current cpu power (read: anything x86 produced since 2013), even on browserstack/saucelabs/aws VMs, and the development of the browsers (read: all the popular ones in the last 5 years) that is hardly the case. The browser's engines have developed, the support of xpath is uniform, IE is out of the picture (hopefully for most of us). This comparison in the other answer is being cited all over the place, but it is very contextual – how many are running – or care about – automation against IE8?
If there is a difference, it is in a fraction of a millisecond.
Yet, most higher-level frameworks add at least 1ms of overhead over the raw selenium call anyways (wrappers, handlers, state storing etc); my personal weapon of choice – RobotFramework – adds at least 2ms, which I am more than happy to sacrifice for what it provides. A network roundtrip from an AWS us-east-1 to BrowserStack's hub is usually 11 milliseconds.
So with remote browsers if there is a difference between xpath and css, it is overshadowed by everything else, in orders of magnitude.
There are not that many public comparisons (I've really seen only the cited one), so – here's a rough single-case, dummy and simple one.
It will locate an element by the two strategies X times, and compare the average time for that.
The target – BrowserStack's landing page, and its "Sign Up" button; a screenshot of the html as writing this post:
Here's the test code (python):
from selenium import webdriver
import timeit
if __name__ == '__main__':
xpath_locator = '//div[@class="button-section col-xs-12 row"]'
css_locator = 'div.button-section.col-xs-12.row'
repetitions = 1000
driver = webdriver.Chrome()
driver.get('https://www.browserstack.com/')
css_time = timeit.timeit("driver.find_element_by_css_selector(css_locator)",
number=repetitions, globals=globals())
xpath_time = timeit.timeit('driver.find_element_by_xpath(xpath_locator)',
number=repetitions, globals=globals())
driver.quit()
print("css total time {} repeats: {:.2f}s, per find: {:.2f}ms".
format(repetitions, css_time, (css_time/repetitions)*1000))
print("xpath total time for {} repeats: {:.2f}s, per find: {:.2f}ms".
format(repetitions, xpath_time, (xpath_time/repetitions)*1000))
For those not familiar with Python – it opens the page, and finds the element – first with the css locator, then with the xpath; the find operation is repeated 1,000 times. The output is the total time in seconds for the 1,000 repetitions, and average time for one find in milliseconds.
The locators are:
Deliberately chosen not to be over-tuned; also, the class selector is cited for the css as "the second fastest after an id".
The environment – Chrome v66.0.3359.139, chromedriver v2.38, cpu: ULV Core M-5Y10 usually running at 1.5GHz (yes, a "word-processing" one, not even a regular i7 beast).
Here's the output:
css total time 1000 repeats: 8.84s, per find: 8.84ms xpath total time for 1000 repeats: 8.52s, per find: 8.52ms
Obviously the per find timings are pretty close; the difference is 0.32 milliseconds. Don't jump "the xpath is faster" – sometimes it is, sometimes it's css.
Let's try with another set of locators, a tiny-bit more complicated – an attribute having a substring (common approach at least for me, going after an element's class when a part of it bears functional meaning):
xpath_locator = '//div[contains(@class, "button-section")]'
css_locator = 'div[class~=button-section]'
The two locators are again semantically the same – "find a div element having in its class attribute this substring".
Here are the results:
css total time 1000 repeats: 8.60s, per find: 8.60ms xpath total time for 1000 repeats: 8.75s, per find: 8.75ms
Diff of 0.15ms.
As an exercise - the same test as done in the linked blog in the comments/other answer - the test page is public, and so is the testing code.
They are doing a couple of things in the code - clicking on a column to sort by it, then getting the values, and checking the UI sort is correct.
I'll cut it - just get the locators, after all - this is the root test, right?
The same code as above, with these changes in:
The url is now http://the-internet.herokuapp.com/tables
; there are 2 tests.
The locators for the first one - "Finding Elements By ID and Class" - are:
css_locator = '#table2 tbody .dues'
xpath_locator = "//table[@id='table2']//tr/td[contains(@class,'dues')]"
And here is the outcome:
css total time 1000 repeats: 8.24s, per find: 8.24ms xpath total time for 1000 repeats: 8.45s, per find: 8.45ms
Diff of 0.2 milliseconds.
The "Finding Elements By Traversing":
css_locator = '#table1 tbody tr td:nth-of-type(4)'
xpath_locator = "//table[@id='table1']//tr/td[4]"
The result:
css total time 1000 repeats: 9.29s, per find: 9.29ms xpath total time for 1000 repeats: 8.79s, per find: 8.79ms
This time it is 0.5 ms (in reverse, xpath turned out "faster" here).
So 5 years later (better browsers engines) and focusing only on the locators performance (no actions like sorting in the UI, etc), the same testbed - there is practically no difference between CSS and XPath.
So, out of xpath and css, which of the two to choose for performance? The answer is simple – choose locating by id.
Long story short, if the id of an element is unique (as it's supposed to be according to the specs), its value plays an important role in the browser's internal representation of the DOM, and thus is usually the fastest.
Yet, unique and constant (e.g. not auto-generated) ids are not always available, which brings us to "why XPath if there's CSS?"
With the performance out of the picture, why do I think xpath is better? Simple – versatility, and power.
Xpath is a language developed for working with XML documents; as such, it allows for much more powerful constructs than css.
For example, navigation in every direction in the tree – find an element, then go to its grandparent and search for a child of it having certain properties.
It allows embedded boolean conditions – cond1 and not(cond2 or not(cond3 and cond4))
; embedded selectors – "find a div having these children with these attributes, and then navigate according to it".
XPath allows searching based on a node's value (its text) – however frowned upon this practice is, it does come in handy especially in badly structured documents (no definite attributes to step on, like dynamic ids and classes - locate the element by its text content).
The stepping in css is definitely easier – one can start writing selectors in a matter of minutes; but after a couple of days of usage, the power and possibilities xpath has quickly overcomes css.
And purely subjective – a complex css is much harder to read than a complex xpath expression.
Finally, again very subjective - which one to chose?
IMO, there is no right or wrong choice - they are different solutions to the same problem, and whatever is more suitable for the job should be picked.
Being "a fan" of XPath I'm not shy to use in my projects a mix of both - heck, sometimes it is much faster to just throw a CSS one, if I know it will do the work just fine.
I'm not really sure what I did to get this error, but doing:
git remote set-url origin https://...
didn't work for me. However:
git remote set-url origin [email protected]:user/repo
somehow worked.
You need to escape the backslash \
:
println yourString.replace("\\", "/")
If you just want to know the position of one specific user after order by field score, you can simply select all row from your table where field score is higher than the current user score. And use row number returned + 1 to know which position of this current user.
Assuming that your table is league_girl
and your primary field is id
, you can use this:
SELECT count(id) + 1 as rank from league_girl where score > <your_user_score>
Make sure your oracle services are running automatically. Just press Win+R. Type services.msc in textbox then press O to find oracle services.
In your PC name might be like OracleserviceXYZ. Right click on highlighted services.
Somehow, this fix the issue out of no reason.
./gradlew clean assemble
and then install the app.
I believe you are looking for setInterval()
If you need to remove text inside nested parentheses, too, then:
var prevStr;
do {
prevStr = str;
str = str.replace(/\([^\)\(]*\)/, "");
} while (prevStr != str);
You could get a JavaScript object containing the parameters with something like this:
var regex = /[?&]([^=#]+)=([^&#]*)/g,
url = window.location.href,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by =
characters, and pairs themselves separated by &
characters (or an =
character for the first one). For your example, the above would result in:
{v: "123", p: "hello"}
Here's a working example.
As of CSS3, the spec has changed, allowing for only a single font-style
. A comma-separated list (per CSS2) will be treated as if it were normal
and override any earlier (default) entry. This will make fonts defined in this way appear italic permanently.
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans.ttf");
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Bold.ttf");
font-weight: bold;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Oblique.ttf");
font-style: italic;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-BoldOblique.ttf");
font-weight: bold;
font-style: italic;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Oblique.ttf");
font-style: oblique;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-BoldOblique.ttf");
font-weight: bold;
font-style: oblique;
}
In most cases, italic will probably be sufficient and oblique rules won't be necessary if you take care to define whichever you will use and stick to it.
From the discussion here, and especially this answer, this is the function I currently use:
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
My own tiny benchmarks (a million bytes a thousand times, 256 bytes 10 million times) showed it to be much faster than any other alternative, about half the time on long arrays. Compared to the answer I took it from, switching to bitwise ops --- as suggested in the discussion --- cut about 20% off of the time for long arrays. (Edit: When I say it's faster than the alternatives, I mean the alternative code offered in the discussions. Performance is equivalent to Commons Codec, which uses very similar code.)
2k20 version, with respect to Java 9 compact strings:
private static final byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
public static String bytesToHex(byte[] bytes) {
byte[] hexChars = new byte[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars, StandardCharsets.UTF_8);
}
I agree with Paolo that we need to see more code. I tested this overly simplified example and it worked. This means that it is able to change the form action on the fly.
<script type="text/javascript">
function submitForm(){
var form_url = $("#openid_form").attr("action");
alert("Before - action=" + form_url);
//changing the action to google.com
$("#openid_form").attr("action","http://google.com");
alert("After - action = "+$("#openid_form").attr("action"));
//submit the form
$("#openid_form").submit();
}
</script>
<form id="openid_form" action="test.html">
First Name:<input type="text" name="fname" /><br/>
Last Name: <input type="text" name="lname" /><br/>
<input type="button" onclick="submitForm()" value="Submit Form" />
</form>
EDIT: I tested the updated code you posted and found a syntax error in the declaration of providers_large
. There's an extra comma. Firefox ignores the issue, but IE8 throws an error.
var providers_large = {
google: {
name: 'Google',
url: 'https://www.google.com/accounts/o8/id'
},
facebook: {
name: 'Facebook',
form_url: 'http://wikipediamaze.rpxnow.com/facebook/start?token_url=http://www.wikipediamaze.com/Accounts/Logon'
}, //<-- Here's the problem. Remove that comma
};
An API is ready-made source code library.
In Java for example APIs are a set of related classes and interfaces that come in packages. This picture illustrates the libraries included in the Java Standard Edition API. Packages are denoted by their color.
$('#myForm').on('change', 'input[type=checkbox]', function() {
this.checked ? this.value = 'apple' : this.value = 'pineapple';
});
This is just the XML Name Space declaration. We use this Name Space in order to specify that the attributes listed below, belongs to Android. Thus they starts with "android:"
You can actually create your own custom attributes. So to prevent the name conflicts where 2 attributes are named the same thing, but behave differently, we add the prefix "android:" to signify that these are Android attributes.
Thus, this Name Space declaration must be included in the opening tag of the root view of your XML file.
Yes you can.
Multiple document ready sections are particularly useful if you have other modules haging off the same page that use it. With the old window.onload=func
declaration, every time you specified a function to be called, it replaced the old.
Now all functions specified are queued/stacked (can someone confirm?) regardless of which document ready section they are specified in.
select *
from blah
where DatetimeField between '22/02/2009 09:00:00.000' and '23/05/2009 10:30:00.000'
Depending on the country setting for the login, the month/day may need to be swapped around.
<input type="password" autocomplete="off" />
I'd just like to add that as a user I think this is very annoying and a hassle to overcome. I strongly recommend against using this as it will more than likely aggravate your users.
Passwords are already not stored in the MRU, and correctly configured public machines will not even save the username.
You've specifically mentioned a "variable-length array" in your question, so neither of the existing two answers (as I write this) are quite right.
Java doesn't have any concept of a "variable-length array", but it does have Collections, which serve in this capacity. Any collection (technically any "Iterable", a supertype of Collections) can be looped over as simply as this:
Collection<Thing> things = ...;
for (Thing t : things) {
System.out.println(t);
}
EDIT: it's possible I misunderstood what he meant by 'variable-length'. He might have just meant it's a fixed length but not every instance is the same fixed length. In which case the existing answers would be fine. I'm not sure what was meant.
You need to change your text to 'Plain text' before pasting into the HTML document. This looks like an error I've had before by pasting straight from MS word.
MS word and other rich text editors often place hidden or invalid chars into your code. Try using —
for your dashes, or ’
for apostrophes (etc), to eliminate the need for relying on your char encoding.
Your pattern is fine. But you shouldn't be split()
ting it away, you should find()
it. Following code gives the output you are looking for:
String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
TL;DR;
Set "Build Active Architecture Only (ONLY_ACTIVE_ARCH
)" to Yes for your libraries/apps, even for release mode.
While trying to identify the root cause of the issue I realized some fun facts about Xcode 12.
Xcode 12 is actually the stepping stone for Apple Silicon which unfortunately is not yet available (when the answer was written). But with that platform we are gonna get arm64 based macOS where simulators will also run on arm64 architecture unlike the present Intel based x86_64 architecture.
Xcode usually depends on the "Run Destination" to build its libraries/apps. So when a simulator is chosen as the "Run Destination", it builds the app for available simulator architectures and when a device is chosen as the "Run Destination" it builds for the architecture that the device supports (arm*
).
xcodebuild
, in the Xcode 12+ build system considers arm64
as a valid architecture for simulator to support Apple Silicon. So when a simulator is chosen as the run destination, it can potentially try to compile/link your libs/apps against arm64
based simulators, as well. So it sends clang(++)
some -target flag like arm64-apple-ios13.0-simulator
in <architecture>-<os>-<sdk>-<destination> format and clang tries to build/link against arm64 based simulator that eventually fails on Intel based mac.
But xcodebuild
tries this only for Release builds. Why? Because, "Build Active Architecture Only (ONLY_ACTIVE_ARCH
)" build settings is usually set to "No" for the "Release" configuration only. And that means xcodebuild
will try to build all architectural variants of your libs/apps for the selected run destination for release builds. And for the Simulator run destination, it will includes both x86_64
and arm64
now on, since arm64
in Xcode 12+ is also a supported architecture for simulators to support Apple Silicon.
Simply putting, Xcode will fail to build your app anytime it tries the command line, xcodebuild
, (which defaults to release build, see the general tab of your project setting) or otherwise and tries to build all architectural variants supported by the run destination. So a simple workaround to this issue is to set "Build Active Architecture Only (ONLY_ACTIVE_ARCH
)" to Yes in your libraries/apps, even for release mode.
If the libraries are included as Pods and you have access to .podspec
you can simply set:
spec.pod_target_xcconfig = { 'ONLY_ACTIVE_ARCH' => 'YES' }
spec.user_target_xcconfig = { 'ONLY_ACTIVE_ARCH' => 'YES' } # not recommended
I personally don't like the second line since pods shouldn't pollute the target project and it could be overridden in the target settings, itself. So it should be the responsibility of the consumer project to override the setting by some means. However, this could be necessary for successful linting of podspecs.
However, if you don't have access to the .podspec
, you can always update the settings during installation of the pods:
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings["ONLY_ACTIVE_ARCH"] = "YES"
end
end
end
One thing I was concerned about that what will be the impact of this when we actually archive the libs/apps. During archiving apps usually take the "Release" configuration and since this will be creating a release build considering only the active architecture of the current run destination, with this approach, we may lose the slices for armv7, armv7s, etc from target build. However, I noticed the documentation says (highlighted in the attached picture) that this setting will be ignored when we choose "Generic iOS Device/Any Device" as the run destination, since it doesn't define any specific architecture. So I guess we should be good if we archive our app choosing that as a run destination.
Figure sizes are specified in inches and can be included as a global option of the document output format. For example:
---
title: "My Document"
output:
html_document:
fig_width: 6
fig_height: 4
---
And the plot's size in the graphic device can be increased at the chunk level:
```{r, fig.width=14, fig.height=12} #Expand the plot width to 14 inches
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You can also use the out.width
and out.height
arguments to directly define the size of the plot in the output file:
```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You will need to get a DateTime
object from your TimeSpan
and then you can format it easily.
One possible solution is adding the timespan to any date with zero time value.
var timespan = new TimeSpan(3, 0, 0);
var output = new DateTime().Add(timespan).ToString("hh:mm tt");
The output value will be "03:00 AM"
(for english locale).
Just came acreoss this, and since I had the same issue, I'd just post the results I came up with
when parsing, you could update the offset (ie I am parsing a data (1.1.2014) and I only want the date, 1st Jan 2014. On GMT+1 I'd get 31.12.2013. So I offset the value first.
moment(moment.utc('1.1.2014').format());
Well, came in handy for me to support across timezones
B
For next/return events on multiple UITextfield inside UITableViewCell in this method I had taken UITextField in storyboard.
@interface MyViewController () {
NSInteger currentTxtRow;
}
@end
@property (strong, nonatomic) NSIndexPath *currentIndex;//Current Selected Row
@implementation MyViewController
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UITextField *txtDetails = (UITextField *)[cell.contentView viewWithTag:100];
txtDetails.delegate = self;
txtDetails.placeholder = self.arrReciversDetails[indexPath.row];
return cell;
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
CGPoint point = [textField convertPoint:CGPointZero toView:self.tableView];
self.currentIndex = [self.tableView indexPathForRowAtPoint:point];//Get Current UITableView row
currentTxtRow = self.currentIndex.row;
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
currentTxtRow += 1;
self.currentIndex = [NSIndexPath indexPathForRow:currentTxtRow inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.currentIndex];
UITextField *currentTxtfield = (UITextField *)[cell.contentView viewWithTag:100];
if (currentTxtRow < 3) {//Currently I have 3 Cells each cell have 1 UITextfield
[currentTxtfield becomeFirstResponder];
} else {
[self.view endEditing:YES];
[currentTxtfield resignFirstResponder];
}
}
To grab the text from textfield-
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
switch (self.currentIndex.row) {
case 0:
NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
break;
case 1:
NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
break;
case 2:
NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
break;
default:
break;
}
}
.outer {_x000D_
overflow-y: auto;_x000D_
height: 300px;_x000D_
}_x000D_
_x000D_
.outer {_x000D_
width: 100%;_x000D_
-layout: fixed;_x000D_
}_x000D_
_x000D_
.outer th {_x000D_
text-align: left;_x000D_
top: 0;_x000D_
position: sticky;_x000D_
background-color: white;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
<meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
<title>MYCRUD</title>_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container-fluid col-md-11">_x000D_
<div class="row">_x000D_
_x000D_
<div class="col-lg-12">_x000D_
_x000D_
_x000D_
<div class="card-body">_x000D_
<div class="outer">_x000D_
_x000D_
<table class="table table-hover bg-light">_x000D_
<thead>_x000D_
<tr>_x000D_
<th scope="col">ID</th>_x000D_
<th scope="col">Marca</th>_x000D_
<th scope="col">Editar</th>_x000D_
<th scope="col">Eliminar</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
_x000D_
_x000D_
<tr>_x000D_
<td>4</td>_x000D_
<td>Toyota</td>_x000D_
<td> <a class="btn btn-success" href="#">_x000D_
<i class="fa fa-edit"></i>_x000D_
</a>_x000D_
</td>_x000D_
<td> <a class="btn btn-danger" href="#">_x000D_
<i class="fa fa-trash"></i>_x000D_
</a>_x000D_
</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>Honda </td>_x000D_
<td> <a class="btn btn-success" href="#">_x000D_
<i class="fa fa-edit"></i>_x000D_
</a>_x000D_
</td>_x000D_
<td> <a class="btn btn-danger" href="#">_x000D_
<i class="fa fa-trash"></i>_x000D_
</a>_x000D_
</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>5</td>_x000D_
<td>Myo</td>_x000D_
<td> <a class="btn btn-success" href="#">_x000D_
<i class="fa fa-edit"></i>_x000D_
</a>_x000D_
</td>_x000D_
<td> <a class="btn btn-danger" href="#">_x000D_
<i class="fa fa-trash"></i>_x000D_
</a>_x000D_
</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>6</td>_x000D_
<td>Acer</td>_x000D_
<td> <a class="btn btn-success" href="#">_x000D_
<i class="fa fa-edit"></i>_x000D_
</a>_x000D_
</td>_x000D_
<td> <a class="btn btn-danger" href="#">_x000D_
<i class="fa fa-trash"></i>_x000D_
</a>_x000D_
</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>7</td>_x000D_
<td>HP</td>_x000D_
<td> <a class="btn btn-success" href="#">_x000D_
<i class="fa fa-edit"></i>_x000D_
</a>_x000D_
</td>_x000D_
<td> <a class="btn btn-danger" href="#">_x000D_
<i class="fa fa-trash"></i>_x000D_
</a>_x000D_
</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>8</td>_x000D_
<td>DELL</td>_x000D_
<td> <a class="btn btn-success" href="#">_x000D_
<i class="fa fa-edit"></i>_x000D_
</a>_x000D_
</td>_x000D_
<td> <a class="btn btn-danger" href="#">_x000D_
<i class="fa fa-trash"></i>_x000D_
</a>_x000D_
</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>9</td>_x000D_
<td>LOGITECH</td>_x000D_
<td> <a class="btn btn-success" href="#">_x000D_
<i class="fa fa-edit"></i>_x000D_
</a>_x000D_
</td>_x000D_
<td> <a class="btn btn-danger" href="#">_x000D_
<i class="fa fa-trash"></i>_x000D_
</a>_x000D_
</td>_x000D_
</tr>_x000D_
_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
According to Html5 specs you should use -- element.options[e.selectedIndex].text
e.g. if you have select box like below :
<select id="selectbox1">
<option value="1">First</option>
<option value="2" selected="selected">Second</option>
<option value="3">Third</option>
</select>
<br/>
<button onClick="GetItemValue('selectbox1');">Get Item</button>
you can get value using following script :
<script>
function GetItemValue(q) {
var e = document.getElementById(q);
var selValue = e.options[e.selectedIndex].text ;
alert("Selected Value: "+selValue);
}
</script>
Tried and tested.
By default TortoiseSVN always has a GUI (Graphical User Interface) associated with it. But on the installer (of version 1.7 and later) you can select the "command line client tools" option so you can call svn commands (like svn commit and svn update) from the command line.
Here's a screenshot of the "command line client tools" option in the installer, you need to make sure you select it:
There's nothing wrong with saving the whole history in the database, they are prepared for that kind of tasks.
Actually you can find here in Stack Overflow a link to an example schema for a chat: example
If you are still worried for the size, you could apply some optimizations to group messages, like adding a buffer to your application that you only push after some time (like 1 minute or so); that way you would avoid having only 1 line messages
I think you will find that if your web app is performing a complex operation then provided feedback is given to the user, they won't mind (too much).
For example: Loading Google Mail.
Th easiest way to this is var id = $(this).val(); from inside an event like on change.
in your view blade change to
{{ Form::open(['action' => 'postcontroller@edit', 'method' => 'PUT', 'class' = 'your class here']) }}
<div>
{{ Form::textarea('textareanamehere', 'default value here', ['placeholder' => 'your place holder here', 'class' => 'your class here']) }}
</div>
<div>
{{ Form::submit('Update', ['class' => 'btn class here'])}}
</div>
{{ Form::close() }}
actually you can use raw form like your question. but i dont recomended it. dan itulah salah satu alasan agan belajar framework, simple, dan cepat. so kenapa pake raw form kalo ada yang lebih mudah. hehe. proud to be indonesian.
reference: Laravel Blade Form
First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
> z <- factor(letters[c(3, 2, 3, 4)])
# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d
# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"
here, z
has 4 elements.
The index is 2, 1, 2, 3
in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then, as.numeric
converts simply the index part of factor into numeric.
as.character
handles the index and levels, and generates character vector expressed by its level.
?as.numeric
says that Factors are handled by the default method.
Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".
Credits : AngularJS Post - Igor Minar
If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super
to call the parent method, inside the body of the child method.
public class PolyTest{
public static void main(String args[]){
new Child().foo();
}
}
class Parent{
public void foo(){
System.out.println("I'm the parent.");
}
}
class Child extends Parent{
@Override
public void foo(){
//super.foo();
System.out.println("I'm the child.");
}
}
This would print:
I'm the child.
Uncomment the commented line and it would print:
I'm the parent.
I'm the child.
You should look for the concept of Polymorphism.
Swift 5 or above# make route view controller by this simple code.
If you are using xcode 11 or above first initialise var window: UIWindow?
in AppDelegate
let rootVC = mainStoryboard.instantiateViewController(withIdentifier: "YOURCONTROLLER") as! YOURCONTROLLER
navigationController.setNavigationBarHidden(true, animated: true)
UIApplication.shared.windows.first?.rootViewController = UINavigationController.init(rootViewController: rootVC)
UIApplication.shared.windows.first?.makeKeyAndVisible()
Example 2012:
library("xlsx")
FirstTable <- read.xlsx("MyExcelFile.xlsx", 1 , stringsAsFactors=F)
SecondTable <- read.xlsx("MyExcelFile.xlsx", 2 , stringsAsFactors=F)
Example 2015:
library("readxl")
FirstTable <- read_excel("MyExcelFile.xlsx", 1)
SecondTable <- read_excel("MyExcelFile.xlsx", 2)
readxl
and have made good experience with it.the instanceOf
statement is often used in implementation of equals.
This is a popular pitfall !
The problem is that using instanceOf
violates the rule of symmetry:
(object1.equals(object2) == true)
if and only if (object2.equals(object1))
if the first equals is true, and object2 is an instance of a subclass of the class where obj1 belongs to, then the second equals will return false!
if the regarded class where ob1 belongs to is declared as final, then this problem can not arise, but in general, you should test as follows:
this.getClass() != otherObject.getClass();
if not, return false, otherwise test
the fields to compare for equality!
You can upgrade your compiler to support C++11 and your code would work perfectly.
Use initialization list in constructor.
T1() : t( 100 )
{
}
with your VARCHAR, you may also need to specify the length, or its usually good to
What about grabbing the text, making a sting of it, then putting it into the query witrh
String TableName = "ComplicatedTableNameHere";
EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere);
String editTextString1 = editText1.getText().toString();
BROKEN DOWN
String TableName = "ComplicatedTableNameHere";
//sets the table name as a string so you can refer to TableName instead of writing out your table name everytime
EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere);
//gets the text from your edit text fieldfield
//editText1 = your edit text name
//EditTextIDhere = the id of your text field
String editTextString1 = editText1.getText().toString();
//sets the edit text as a string
//editText1 is the name of the Edit text from the (EditText) we defined above
//editTextString1 = the string name you will refer to in future
then use
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ TableName
+ " (Column_Name, Column_Name2, Column_Name3, Column_Name4)"
+ " VALUES ( "+EditTextString1+", 'Column_Value2','Column_Value3','Column_Value4');");
Hope this helps some what...
NOTE each string is within
'"+stringname+"'
its the 'and' that enable the multi line element of the srting, without it you just get the first line, not even sure if you get the whole line, it may just be the first word
CSS selector:
Use a CSS selector of img[src='images/toolbar/b_edit.gif']
This says select element(s) with img
tag with attribute src
having value of 'images/toolbar/b_edit.gif'
CSS query:
VBA:
You can apply the selector with the .querySelector
method of document
.
IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click
I would like to add an updated answer - now I have been using git for a while, I find that I am often using the following commands to do any pushing (using the original question as the example):
git push origin amd_qlp_tester
- push to the branch located in the remote called origin
on remote-branch called amd_qlp_tester
.git push -u origin amd_qlp_tester
- same as last one, but sets the upstream linking the local branch to the remote branch so that next time you can just use git push/pull
if not already linked (only need to do it once).git push
- Once you have set the upstream you can just use this shorter version.Note -u
option is the short version of --set-upstream
- they are the same.
If you don't have the source code and API documentation, the machine code is all there is, you need to disassemble the dll library using something like IDA Pro , another option is use the trial version of PE Explorer.
PE Explorer provides a Disassembler. There is only one way to figure out the parameters: run the disassembler and read the disassembly output. Unfortunately, this task of reverse engineering the interface cannot be automated.
PE Explorer comes bundled with descriptions for 39 various libraries, including the core Windows® operating system libraries (eg. KERNEL32, GDI32, USER32, SHELL32, WSOCK32), key graphics libraries (DDRAW, OPENGL32) and more.
(source: heaventools.com)
I've taken a more flexible approach inspired by functools.partial
function:
DO_ONCE_MEMORY = []
def do_once(id, func, *args, **kwargs):
if id not in DO_ONCE_MEMORY:
DO_ONCE_MEMORY.append(id)
return func(*args, **kwargs)
else:
return None
With this approach you are able to have more complex and explicit interactions:
do_once('foobar', print, "first try")
do_once('foo', print, "first try")
do_once('bar', print, "second try")
# first try
# second try
The exciting part about this approach it can be used anywhere and does not require factories - it's just a small memory tracker.
You can't... an array's size is always fixed in Java. Typically instead of using an array, you'd use an implementation of List<T>
here - usually ArrayList<T>
, but with plenty of other alternatives available.
You can create an array from the list as a final step, of course - or just change the signature of the method to return a List<T>
to start with.
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
Use
=SUBSTITUTE(A1,",",CHAR(10) & CHAR(13))
This will replace each comma with a new line. Change A1
to the cell you are referencing.
To avoid all jQuery version complications, I honestly recommend using one of these really simple javascript functions...
function setSelectByValue(eID,val)
{ //Loop through sequentially//
var ele=document.getElementById(eID);
for(var ii=0; ii<ele.length; ii++)
if(ele.options[ii].value==val) { //Found!
ele.options[ii].selected=true;
return true;
}
return false;
}
function setSelectByText(eID,text)
{ //Loop through sequentially//
var ele=document.getElementById(eID);
for(var ii=0; ii<ele.length; ii++)
if(ele.options[ii].text==text) { //Found!
ele.options[ii].selected=true;
return true;
}
return false;
}
goto begin and end of all parents closures
var foo=false;
var loop1=true;
LABEL1: do {var LABEL1GOTO=false;
console.log("here be 2 times");
if (foo==false){
foo=true;
LABEL1GOTO=true;continue LABEL1;// goto up
}else{
break LABEL1; //goto down
}
console.log("newer go here");
} while(LABEL1GOTO);
If you pass the -v
flag to the ansible-playbook command, then ansible will show the output on your terminal.
For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.
Go to cmd and type this:
for x64 O.S: %windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir
for x32 O.S: %windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
This will install the right version and IIS will understand the MVC directory browsing
I had a . in my database name, and the query didn't work because of that (saying Incorrect syntax near '.') Then I realized that I need a bracket for the name:
RESTORE DATABASE [My.DB.Name] WITH RECOVERY
Enable this option in VS: Just My Code option
Tools -> Options -> Debugging -> General -> Enable Just My Code (Managed only)
In my case, I was getting this error on the same machine, in my test client-server application. But this problem was resolved by "Update Service Reference".
After i tried Android official Autosizing TextView, i found if your Android version is prior to Android 8.0 (API level 26), you need use android.support.v7.widget.AppCompatTextView
, and make sure your support library version is above 26.0.0. Example:
<android.support.v7.widget.AppCompatTextView
android:layout_width="130dp"
android:layout_height="32dp"
android:maxLines="1"
app:autoSizeMaxTextSize="22sp"
app:autoSizeMinTextSize="12sp"
app:autoSizeStepGranularity="2sp"
app:autoSizeTextType="uniform" />
update:
According to @android-developer's reply, i check the AppCompatActivity
source code, and found these two lines in onCreate
final AppCompatDelegate delegate = getDelegate();
delegate.installViewFactory();
and in AppCompatDelegateImpl
's createView
if (mAppCompatViewInflater == null) {
mAppCompatViewInflater = new AppCompatViewInflater();
}
it use AppCompatViewInflater
inflater view, when AppCompatViewInflater
createView it will use AppCompatTextView for "TextView".
public final View createView(){
...
View view = null;
switch (name) {
case "TextView":
view = new AppCompatTextView(context, attrs);
break;
case "ImageView":
view = new AppCompatImageView(context, attrs);
break;
case "Button":
view = new AppCompatButton(context, attrs);
break;
...
}
In my project i don't use AppCompatActivity
, so i need use <android.support.v7.widget.AppCompatTextView>
in xml.
If someone is looking how to represent the GMT as a float number representing hour offset
(for example "GMT-0530" to -5.5), you can use this:
Calendar calendar = new GregorianCalendar();
TimeZone timeZone = calendar.getTimeZone();
int offset = timeZone.getRawOffset();
long hours = TimeUnit.MILLISECONDS.toHours(offset);
float minutes = (float)TimeUnit.MILLISECONDS.toMinutes(offset - TimeUnit.HOURS.toMillis(hours)) / MINUTES_IN_HOUR;
float gmt = hours + minutes;
npm install http-server -g
http-server . -o
If you are in main app form try to use
System.Diagnostics.Process.Start( Application.ExecutablePath); // to start new instance of application
this.Close(); //to turn off current app
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress = wInfo.getMacAddress();
Also, add below permission in your manifest file
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Please refer to Android 6.0 Changes.
To provide users with greater data protection, starting in this release, Android removes programmatic access to the device’s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs. The WifiInfo.getMacAddress() and the BluetoothAdapter.getAddress() methods now return a constant value of 02:00:00:00:00:00.
To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions.
I solved my problem using
git checkout -m old
git checkout -b new B
git merge -s ours old
I think you cannot just delete the tables property what if this is actual production data, just delete the contents that dont affect the table schema.
Using dtype
will give you desired column's data type:
dataframe['column1'].dtype
if you want to know data types of all the column at once, you can use plural of dtype
as dtypes:
dataframe.dtypes