function useOnceCall(cb, condition = true) {
const isCalledRef = React.useRef(false);
React.useEffect(() => {
if (condition && !isCalledRef.current) {
isCalledRef.current = true;
cb();
}
}, [cb, condition]);
}
and use it.
useOnceCall(()=>{
console.log('called');
})
or
useOnceCall(()=>{
console.log('isLoading');
},isLoading);
This worked for me:
let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
...
The key was adding in the URLSessionDataTask
type declaration.
Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?
You can use the --extra-vars
option. See the docs
You should just set all constraints for TOP, BOTTOM and HEIGHT for each object on cell view/views and remove exists middle Y position if have. Because where you didn't this, puts artifacts on another views.
Just for those new to iOS buddies (like me) who decided to have multiple cells and in a different xib file, the solution is not to have identifier but to do this:
let cell = Bundle.main.loadNibNamed("newsDetails", owner: self, options: nil)?.first as! newsDetailsTableViewCell
here newsDetails is xib file name.
Also had this issue, This array was out of range:
order: [1, 'asc'],
You can try this.
func convertToJSONString(value: AnyObject) -> String? {
if JSONSerialization.isValidJSONObject(value) {
do{
let data = try JSONSerialization.data(withJSONObject: value, options: [])
if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
return string as String
}
}catch{
}
}
return nil
}
You can try this modal:https://github.com/xue2han/react-dynamic-modal It is stateless and can be rendered only when needed.So it is very easy to use.Just like this:
class MyModal extends Component{
render(){
const { text } = this.props;
return (
<Modal
onRequestClose={this.props.onRequestClose}
openTimeoutMS={150}
closeTimeoutMS={150}
style={customStyle}>
<h1>What you input : {text}</h1>
<button onClick={ModalManager.close}>Close Modal</button>
</Modal>
);
}
}
class App extends Component{
openModal(){
const text = this.refs.input.value;
ModalManager.open(<MyModal text={text} onRequestClose={() => true}/>);
}
render(){
return (
<div>
<div><input type="text" placeholder="input something" ref="input" /></div>
<div><button type="button" onClick={this.openModal.bind(this)}>Open Modal </button> </div>
</div>
);
}
}
ReactDOM.render(<App />,document.getElementById('main'));
Swift 4 answer based on helpful answer from @mbm29414.
Unfortunately, it requires the use of a XIB file. There doesn't appear to be an alternative.
The key parts are using a sizing cell (created only once) and registering the XIB when initializing the collection view.
Then you size each cell dynamically within the sizeForItemAt
function.
// UICollectionView Vars and Constants
let CellXIBName = YouViewCell.XIBName
let CellReuseID = YouViewCell.ReuseID
var sizingCell = YouViewCell()
fileprivate func initCollectionView() {
// Connect to view controller
collectionView.dataSource = self
collectionView.delegate = self
// Register XIB
collectionView.register(UINib(nibName: CellXIBName, bundle: nil), forCellWithReuseIdentifier: CellReuseID)
// Create sizing cell for dynamically sizing cells
sizingCell = Bundle.main.loadNibNamed(CellXIBName, owner: self, options: nil)?.first as! YourViewCell
// Set scroll direction
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
collectionView.collectionViewLayout = layout
// Set properties
collectionView.alwaysBounceVertical = true
collectionView.alwaysBounceHorizontal = false
// Set top/bottom padding
collectionView.contentInset = UIEdgeInsets(top: collectionViewTopPadding, left: collectionViewSidePadding, bottom: collectionViewBottomPadding, right: collectionViewSidePadding)
// Hide scrollers
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// Get cell data and render post
let data = YourData[indexPath.row]
sizingCell.renderCell(data: data)
// Get cell size
sizingCell.setNeedsLayout()
sizingCell.layoutIfNeeded()
let cellSize = sizingCell.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
// Return cell size
return cellSize
}
you can use this subclass of tableView:
import UIKit
protocol PullToRefreshTableViewDelegate : class {
func tableViewDidStartRefreshing(tableView: PullToRefreshTableView)
}
class PullToRefreshTableView: UITableView {
@IBOutlet weak var pullToRefreshDelegate: AnyObject?
private var refreshControl: UIRefreshControl!
private var isFirstLoad = true
override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
if (isFirstLoad) {
addRefreshControl()
isFirstLoad = false
}
}
private func addRefreshControl() {
refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: "refresh", forControlEvents: .ValueChanged)
self.addSubview(refreshControl)
}
@objc private func refresh() {
(pullToRefreshDelegate as? PullToRefreshTableViewDelegate)?.tableViewDidStartRefreshing(self)
}
func endRefreshing() {
refreshControl.endRefreshing()
}
}
1 - in interface builder change the class of your tableView to PullToRefreshTableView
or create a PullToRefreshTableView
programmatically
2 - implement the PullToRefreshTableViewDelegate
in your view controller
3 - tableViewDidStartRefreshing(tableView: PullToRefreshTableView)
will be called in your view controller when the table view starts refreshing
4 - call yourTableView.endRefreshing()
to finish the refreshing
You have just to enter:
First a IBOutlet:
@IBOutlet var appsTableView : UITableView
Then in a Action func:
self.appsTableView.reloadData()
Another way that allows you to change the text of "Delete" and add more buttons when sliding a cell is to use editActionsForRowAtIndexPath
.
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: (UITableView!), commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: (NSIndexPath!)) {
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
var deleteAction = UITableViewRowAction(style: .Default, title: "Delete") {action in
//handle delete
}
var editAction = UITableViewRowAction(style: .Normal, title: "Edit") {action in
//handle edit
}
return [deleteAction, editAction]
}
canEditRowAtIndexPath
and commitEditingStyle
are still required, but you can leave commitEditingStyle
empty since deletion is handled in editActionsForRowAtIndexPath
.
Firstly, I am not an authority on WebClient vs. HttpClient, specifically. Secondly, from your comments above, it seems to suggest that WebClient is Sync ONLY whereas HttpClient is both.
I did a quick performance test to find how WebClient (Sync calls), HttpClient (Sync and Async) perform. and here are the results.
I see that as a huge difference when thinking for future, i.e. long running processes, responsive GUI, etc. (add to the benefit you suggest by framework 4.5 - which in my actual experience is hugely faster on IIS)
You need to add query.addEntity(SwitcherServiceSource.class) before calling the .list() on query.
You can use the function getBBox() to get the bounding box for the path. This will give you the position and size of the tightest rectangle that could contain the rendered path.
An advantage of using this method over reading the x and y values is that it will work with all graphical objects. There are more objects than paths that do not have x and y, for example circles that have cx and cy instead.
If it's fixed layout you can do like that:
public void onClick(View v) {
ViewGroup parent = (ViewGroup) IdNumber.this.getParent();
EditText firstName = (EditText) parent.findViewById(R.id.display_name);
firstName.setText("Some Text");
}
If you want find the EditText in flexible layout, I will help you later. Hope this help.
At first I had problems escaping the "&" character, then diacritics and special letters were shown as question marks and ended up with the issue OP mentioned.
I looked at the answers and I used @Ringo's suggestion to try Load() method as an alternative. That made me realize that I can deal with my response in other ways not just as a string.
using System.IO.Stream instead of string solved all the issues for me.
var response = await this.httpClient.GetAsync(url);
var responseStream = await response.Content.ReadAsStreamAsync();
var xmlDocument = new XmlDocument();
xmlDocument.Load(responseStream);
The cool thing about Load() is that this method automatically detects the string format of the input XML (for example, UTF-8, ANSI, and so on). See more
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)
Pretty simple: Just put it inside a static method.
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(linkYouTube)));
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
cell.poster.image = nil; // or cell.poster.image = [UIImage imageNamed:@"placeholder.png"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://myurl.com/%@.jpg", self.myJson[indexPath.row][@"movieId"]]];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data) {
UIImage *image = [UIImage imageWithData:data];
if (image) {
dispatch_async(dispatch_get_main_queue(), ^{
MyCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath];
if (updateCell)
updateCell.poster.image = image;
});
}
}
}];
[task resume];
return cell;
}
The issue is with this line
xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text
You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.
Hence replace this with
xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text
And a UICollectionView
version, based on kolaworld's answer:
https://stackoverflow.com/a/43162226/1452758
Needs testing. Works so far on iOS 9.2, Xcode 9.2 beta 2, with scrolling a collectionView to an index, as a closure.
extension UICollectionView
{
/// Calls reloadsData() on self, and ensures that the given closure is
/// called after reloadData() has been completed.
///
/// Discussion: reloadData() appears to be asynchronous. i.e. the
/// reloading actually happens during the next layout pass. So, doing
/// things like scrolling the collectionView immediately after a
/// call to reloadData() can cause trouble.
///
/// This method uses CATransaction to schedule the closure.
func reloadDataThenPerform(_ closure: @escaping (() -> Void))
{
CATransaction.begin()
CATransaction.setCompletionBlock(closure)
self.reloadData()
CATransaction.commit()
}
}
Usage:
myCollectionView.reloadDataThenPerform {
myCollectionView.scrollToItem(at: indexPath,
at: .centeredVertically,
animated: true)
}
my datagridview is editonEnter mode . so it refresh only after i leave cell or after i revisit and exit cell twice.
to trigger this iimedately . i unfocus from datagridview . then refocus it.
this.SelectNextControl(dgv1,true,true,false,true);
Application.DoEvents(); //this does magic
dgv1.Focus();
The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:
var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");
PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.
Lots of the answers here don't honor changes of the table or are way too complicated. Using a subclass of UITableView
that will properly set intrinsicContentSize
is a far easier solution when using autolayout. No height constraints etc. needed.
class UIDynamicTableView: UITableView
{
override var intrinsicContentSize: CGSize {
self.layoutIfNeeded()
return CGSize(width: UIViewNoIntrinsicMetric, height: self.contentSize.height)
}
override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
}
}
Set the class of your TableView to UIDynamicTableView
in the interface builder and watch the magic as this TableView will change it's size after a call to reloadData()
.
I had the same requirement and I have done this in following way.You also can try out this..
Use loadData method
web.loadData("<p style='text-align:center'><img class='aligncenter size-full wp-image-1607' title='' src="+movImage+" alt='' width='240px' height='180px' /></p><p><center><U><H2>"+movName+"("+movYear+")</H2></U></center></p><p><strong>Director : </strong>"+movDirector+"</p><p><strong>Producer : </strong>"+movProducer+"</p><p><strong>Character : </strong>"+movActedAs+"</p><p><strong>Summary : </strong>"+movAnecdotes+"</p><p><strong>Synopsis : </strong>"+movSynopsis+"</p>\n","text/html", "UTF-8");
movDirector movProducer like all are my string variable.
In short i retain custom styling for my url.
To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:
In child add:
public Action UpdateProgress; // In place of event handler declaration
// declare an Action delegate
.
.
.
private LoadData() {
this.UpdateProgress(); // call to Action delegate - MyMethod in
// parent
}
In parent add:
// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod; // assigns MyMethod to child delegate
I've been wondering if there was a simple way to download a file in a more ... "generic" way. I came up with this.
It's a simple ActionResult
that will allow you to download a file from a controller call that returns an IHttpActionResult
.
The file is stored in the byte[] Content
. You can turn it into a stream if needs be.
I used this to return files stored in a database's varbinary column.
public class FileHttpActionResult : IHttpActionResult
{
public HttpRequestMessage Request { get; set; }
public string FileName { get; set; }
public string MediaType { get; set; }
public HttpStatusCode StatusCode { get; set; }
public byte[] Content { get; set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response = new HttpResponseMessage(StatusCode);
response.StatusCode = StatusCode;
response.Content = new StreamContent(new MemoryStream(Content));
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = FileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue(MediaType);
return Task.FromResult(response);
}
}
I don't suggest you just hidding the stricts errors on your project. Intead, you should turn your method to static or try to creat a new instance of the object:
$var = new YourClass();
$var->method();
You can also use the new way to do the same since PHP 5.4:
(new YourClass)->method();
I hope it helps you!
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.
I would suggest instead of trying to extract the HTML from the WebView, you extract the HTML from the URL. By this, I mean using a third party library such as JSoup to traverse the HTML for you. The following code will get the HTML from a specific URL for you
public static String getHtml(String url) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()
)
);
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
}
return result;
}
You can verify the number of visible cells using this function:
- (NSArray *)visibleCells
This method will return an array with the cells that are visible, so you can count the number of objects in this array and compare with the number of objects in your table.. if it's equal.. you can disable the scrolling using:
tableView.scrollEnabled = NO;
As @Ginny mentioned.. we would can have problems with partially visible cells, so this solution works better in this case:
tableView.scrollEnabled = (tableView.contentSize.height <= CGRectGetHeight(tableView.frame));
In case you are using autoLayout this solution do the job:
tableView.alwaysBounceVertical = NO.
EDIT 2016-05-27 - loadRequest
exposes "a universal Cross-Site Scripting vulnerability." Make sure you own every single asset that you load. If you load a bad script, it can load anything it wants.
If you need relative links to work locally, use this:
NSURL *url = [[NSBundle mainBundle] URLForResource:@"my" withExtension:@"html"];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
The bundle will search all subdirectories of the project to find my.html
. (the directory structure gets flattened at build time)
If my.html
has the tag <img src="some.png">
, the webView will load some.png
from your project.
I assume that your style-sheet "style.css" is already located in the assets-folder
load the web-page with jsoup:
doc = Jsoup.connect("http://....").get();
remove links to external style-sheets:
// remove links to external style-sheets
doc.head().getElementsByTag("link").remove();
set link to local style-sheet:
// set link to local stylesheet
// <link rel="stylesheet" type="text/css" href="style.css" />
doc.head().appendElement("link").attr("rel", "stylesheet").attr("type", "text/css").attr("href", "style.css");
make string from jsoup-doc/web-page:
String htmldata = doc.outerHtml();
display web-page in webview:
WebView webview = new WebView(this);
setContentView(webview);
webview.loadDataWithBaseURL("file:///android_asset/.", htmlData, "text/html", "UTF-8", null);
As I understand it, loadData()
simply generates a data:
URL with the data provide it.
Read the javadocs for loadData()
:
If the value of the encoding parameter is 'base64', then the data must be encoded as base64. Otherwise, the data must use ASCII encoding for octets inside the range of safe URL characters and use the standard %xx hex encoding of URLs for octets outside that range. For example, '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.
The 'data' scheme URL formed by this method uses the default US-ASCII charset. If you need need to set a different charset, you should form a 'data' scheme URL which explicitly specifies a charset parameter in the mediatype portion of the URL and call loadUrl(String) instead. Note that the charset obtained from the mediatype portion of a data URL always overrides that specified in the HTML or XML document itself.
Therefore, you should either use US-ASCII and escape any special characters yourself, or just encode everything using Base64. The following should work, assuming you use UTF-8 (I haven't tested this with latin1):
String data = ...; // the html data
String base64 = android.util.Base64.encodeToString(data.getBytes("UTF-8"), android.util.Base64.DEFAULT);
webView.loadData(base64, "text/html; charset=utf-8", "base64");
A better (IMO) one-line approach, works on ExtJS 4, not sure about 3:
store.proxy.reader.jsonData
make sure to change in ajax call
async: true,
type: "GET",
dataType: "html",
It is good practice to make sure the callback is an actual function before attempting to execute it:
if (callback && typeof(callback) === "function") {
callback();
}
Following @user2019515 answer, I needed to handle exclusions to my archive. here is the resulting function with an example.
Zip Function :
function Zip($source, $destination, $include_dir = false, $exclusions = false){
// Remove existing archive
if (file_exists($destination)) {
unlink ($destination);
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true){
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
if ($include_dir) {
$arr = explode("/",$source);
$maindir = $arr[count($arr)- 1];
$source = "";
for ($i=0; $i < count($arr) - 1; $i++) {
$source .= '/' . $arr[$i];
}
$source = substr($source, 1);
$zip->addEmptyDir($maindir);
}
foreach ($files as $file){
// Ignore "." and ".." folders
$file = str_replace('\\', '/', $file);
if(in_array(substr($file, strrpos($file, '/')+1), array('.', '..'))){
continue;
}
// Add Exclusion
if(($exclusions)&&(is_array($exclusions))){
if(in_array(str_replace($source.'/', '', $file), $exclusions)){
continue;
}
}
$file = realpath($file);
if (is_dir($file) === true){
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
} elseif (is_file($file) === true){
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
} elseif (is_file($source) === true){
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
How to use it :
function backup(){
$backup = 'tmp/backup-'.$this->site['version'].'.zip';
$exclusions = [];
// Excluding an entire directory
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('tmp/'), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file){
array_push($exclusions,$file);
}
// Excluding a file
array_push($exclusions,'config/config.php');
// Excluding the backup file
array_push($exclusions,$backup);
$this->Zip('.',$backup, false, $exclusions);
}
Actually, it's very simple:
[_tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
From the documentation:
Calling this method causes the table view to ask its data source for new cells for the specified sections. The table view animates the insertion of new cells in as it animates the old cells out.
Another option for you is a linked list. You'll need to analyze how your program will use the data structure, if you don't need random access it could be faster than reallocating.
Action y; //declared inside class
label1.Invoke(y=()=>label1.Text="text");
I got this off of here:
In my case the mapping class was not public. In other words, instead of:
public class UserMap : ClassMap<user> // note the public!
I just had:
class UserMap : ClassMap<user>
To get all indices that matches 'Smith'
>>> df[df['LastName'] == 'Smith'].index
Int64Index([1], dtype='int64')
or as a numpy array
>>> df[df['LastName'] == 'Smith'].index.to_numpy() # .values on older versions
array([1])
or if there is only one and you want the integer, you can subset
>>> df[df['LastName'] == 'Smith'].index[0]
1
You could use the same boolean expressions with .loc
, but it is not needed unless you also want to select a certain column, which is redundant when you only want the row number/index.
Selectors work only for drawables, not styles. Reference
First, to make the button background transparent use the following attribute as this will not affect the material design animations:
style="?attr/buttonBarButtonStyle"
There are many ways to style your button. Check out this tutorial.
Second, to make the text bold on pressed, use this java code:
btn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
// When the user clicks the Button
case MotionEvent.ACTION_DOWN:
btn.setTypeface(Typeface.DEFAULT_BOLD);
break;
// When the user releases the Button
case MotionEvent.ACTION_UP:
btn.setTypeface(Typeface.DEFAULT);
break;
}
return false;
}
});
Use this code to add years or months or days or hours or minutes or seconds to a given date
echo date("Y-m-d H:i:s", strtotime("+1 years", strtotime('2014-05-22 10:35:10'))); //2015-05-22 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 months", strtotime('2014-05-22 10:35:10')));//2014-06-22 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 days", strtotime('2014-05-22 10:35:10')));//2014-05-23 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 hours", strtotime('2014-05-22 10:35:10')));//2014-05-22 11:35:10
echo date("Y-m-d H:i:s", strtotime("+1 minutes", strtotime('2014-05-22 10:35:10')));//2014-05-22 10:36:10
echo date("Y-m-d H:i:s", strtotime("+1 seconds", strtotime('2014-05-22 10:35:10')));//2014-05-22 10:35:11
You can also subtract replacing + to -
Syntax
UPDATE table-name
SET column-name = value, column-name = value, ...
WHERE condition
Example
UPDATE school
SET course = 'mysqli', teacher = 'Tanzania', student = 'you'
WHERE id = 6
You can take update / pull on git branch you can use below command
git pull origin <branch-name>
The above command will take an update/pull from giving branch name
If you want to take pull from another branch, you need to go to that branch.
git checkout master
Than
git pull origin development
Hope that will work for you
You can add this line of code for shadow in card view
card_view:cardElevation="3dp"
Below you have an example
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="@android:color/white"
android:foreground="?android:attr/selectableItemBackground"
card_view:cardElevation="3dp"
card_view:cardCornerRadius="4dp">
Hope this helps!
If Debian behaves like recent Ubuntu versions regarding pip install
default target, it's dead easy: it installs to /usr/local/lib/
instead of /usr/lib
(apt
default target). Check https://askubuntu.com/questions/173323/how-do-i-detect-and-remove-python-packages-installed-via-pip/259747#259747
I am an ArchLinux user and as I experimented with pip I met this same problem. Here's how I solved it in Arch.
find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs pacman -Qo | grep 'No package'
Key here is /usr/lib/python2.7/site-packages
, which is the directory pip installs to, YMMV. pacman -Qo
is how Arch's pac kage man ager checks for ownership of the file. No package
is part of the return it gives when no package owns the file: error: No package owns $FILENAME
. Tricky workaround: I'm querying about __init__.py
because pacman -Qo
is a little bit ignorant when it comes to directories :(
In order to do it for other distros, you have to find out where pip
installs stuff (just sudo pip install
something), how to query ownership of a file (Debian/Ubuntu method is dpkg -S
) and what is the "no package owns that path" return (Debian/Ubuntu is no path found matching pattern
). Debian/Ubuntu users, beware: dpkg -S
will fail if you give it a symbolic link. Just resolve it first by using realpath
. Like this:
find /usr/local/lib/python2.7/dist-packages -maxdepth 2 -name __init__.py | xargs realpath | xargs dpkg -S 2>&1 | grep 'no path found'
Fedora users can try (thanks @eddygeek):
find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs rpm -qf | grep 'not owned by any package'
An short and easy way to change color of option menu index icon is:
<!-- android:textColorSecondary is the color of the menu overflow icon (three vertical dots) -->
<item name="android:textColorSecondary">@color/optionMenuIconColor</item>
Add above line of code into style.xml (custom theme) file, Hope you get answer,Thanks.
public static Stream ToStream(this Image image)
{
var stream = new MemoryStream();
image.Save(stream, image.RawFormat);
stream.Position = 0;
return stream;
}
position: absolute
will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static
.
Have your four divs nested inside the target div, give the target div position: relative
, and use position: absolute
on the others.
Structure your HTML similar to this:
<div id="container">
<div class="top left"></div>
<div class="top right"></div>
<div class="bottom left"></div>
<div class="bottom right"></div>
</div>
And this CSS should work:
#container {
position: relative;
}
#container > * {
position: absolute;
}
.left {
left: 0;
}
.right {
right: 0;
}
.top {
top: 0;
}
.bottom {
bottom: 0;
}
...
The reason #2 fails is because sys.modules['module']
does not exist (the import routine has its own scope, and cannot see the module
local name), and there's no module
module or package on-disk. Note that you can separate multiple imported names by commas.
from package.subpackage.module import attribute1, attribute2, attribute3
Also:
from package.subpackage import module
print module.attribute1
I added both text and icon together in a placeholder.
placeholder="Edit "
CSS :
font-family: FontAwesome,'Merriweather Sans', sans-serif;
<input type="button" value="..." onClick="fbLikeDump(); WriteCookie();" />
There could be a few things happening here. Start by first figuring out your library location:
Sys.getenv("R_LIBS_USER")
or
.libPaths()
We already know yours from the info you gave: C:\Program Files\R\R-3.0.1\library
I believe you have a file in there called: 00LOCK
. From ?install.packages
:
Note that it is possible for the package installation to fail so badly that the lock directory is not removed: this inhibits any further installs to the library directory (or for --pkglock, of the package) until the lock directory is removed manually.
You need to delete that file. If you had the pacman
package installed you could have simply used p_unlock()
and the 00LOCK
file is removed. You can't install pacman
now until the 00LOCK
file is removed.
To install pacman
use:
install.packages("pacman")
There may be a second issue. This is where you somehow corrupted MASS
. This can occur, in my experience, if you try to update a package while it is in use in another R session. I'm sure there's other ways to cause this as well. To solve this problem try:
Sys.getenv("R_LIBS_USER")
. In your case this is: C:\Program Files\R\R-3.0.1\libraryMASS
packageMASS
via install.packages("MASS")
If any of this works please let me know what worked.
You can create a GitHub repo via the command line using the GitHub API. Check out the repository API. If you scroll down about a third of the way, you'll see a section entitled "Create" that explains how to create a repo via the API (right above that is a section that explains how to fork a repo with the API, too). Obviously you can't use git
to do this, but you can do it via the command line with a tool like curl
.
Outside of the API, there's no way to create a repo on GitHub via the command line. As you noted, GitHub doesn't allow shell access, etc., so aside from the GitHub API, the only way to create a repo is through GitHub's web interface.
You can make a function:
public void playNotificationSound()
{
try
{
Uri alarmSound = `Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + MyApplication.getInstance().getApplicationContext().getPackageName() + "/raw/notification");`
Ringtone r = RingtoneManager.getRingtone(MyApplication.getInstance().getApplicationContext(), alarmSound);
r.play();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Call this function when you receive notification.
Here raw is the folder in res and the notification is the sound file in raw folder.
Assuming that the mouse cursor should return to the document after window resize, we can create a callback-like behavior with onmouseover event. Don't forget that this solution may not work for touch-enabled screens as expected.
var resizeTimer;
var resized = false;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
if(!resized) {
resized = true;
$(document).mouseover(function() {
resized = false;
// do something here
$(this).unbind("mouseover");
})
}
}, 500);
});
This method is easier and safer
var lOrders = new List<string>();
bool insertOrderNew = lOrders.Find(r => r == "1234") == null ? true : false
Edit: It's almost 6 years later, looking at this now I wouldn't recommend this solution. The accepted answer is definitely much better. Go with that!
This seems to work.
You can listen to keyboard events with jQuery and prevent the event from completing if its the key combo you are looking for. Note, check 118 and 86 (V and v)
Working example here: http://jsfiddle.net/dannylane/9pRsx/4/
$(document).ready(function(){
$(document).keydown(function(event) {
if (event.ctrlKey==true && (event.which == '118' || event.which == '86')) {
alert('thou. shalt. not. PASTE!');
event.preventDefault();
}
});
});
Update: keypress doesn't fire in IE, use keydown instead.
The problem is because of post back happens on submit button click. So while posting data on submit click again write before returning View()
ViewData["Submarkets"] = new SelectList(submarketRep.AllOrdered(), "id", "name");
Using the multicol package and embedding your list in a multicols
environment does what you want:
\documentclass{article}
\usepackage{multicol}
\begin{document}
\begin{multicols}{2}
\begin{enumerate}
\item a
\item b
\item c
\item d
\item e
\item f
\end{enumerate}
\end{multicols}
\end{document}
flask.Flask.run
accepts additional keyword arguments (**options
) that it forwards to werkzeug.serving.run_simple
- two of those arguments are threaded
(a boolean) and processes
(which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).
threaded
defaults to True
as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True
to enable this behaviour.
For example, you can do
if __name__ == '__main__':
app.run(threaded=True)
to handle multiple clients using threads in a way compatible with old Flask versions, or
if __name__ == '__main__':
app.run(threaded=False, processes=3)
to tell Werkzeug to spawn three processes to handle incoming requests, or just
if __name__ == '__main__':
app.run()
to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.
That being said, Werkzeug's serving.run_simple
wraps the standard library's wsgiref
package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).
In every distribute it has difference files so I write most common ones:
---- CentOS Linux distro
`cat /proc/version`
---- Debian Linux distro
`cat /etc/debian_version`
---- Redhat Linux distro
`cat /etc/redhat-release`
---- Ubuntu Linux distro
`cat /etc/issue` or `cat /etc/lsb-release`
in last one /etc/issue didn't exist so I tried the second one and it returned the right answer
After verifying VPC and Subnet settings, my EC2 instance still didn't have a public DNS. After a day of searching for a resolution, I finally figured it out.
I had to create a new Elastic IP address, then associate it to my instance.
From the EC2 Dashboard:
Go to Elastic IPs from the sidebar.
Click Allocate new address, then Allocate.
Go back to the EC2 Dashboard. Go to Network Interfaces.
Select the EC2 instance without a public DNS. Then Actions - Associate Address.
The Address field, select the new elastic IP address.
The Associate to private IP address field, select the private IP address with no public DNS.
Click Associate Address.
Your EC2 instance should now have a public DNS.
$('html, body').animate({scrollTop:1200},'50');
You can do this!
s = input('enter the main string: ')
p=input('enter the substring: ')
l=[]
for i in range(len(s)):
l.append(s[i:i+len(p)])
print(l.count(p))
Alternatively you could read you csv with header=None
and then add it with df.columns
:
Cov = pd.read_csv("path/to/file.txt", sep='\t', header=None)
Cov.columns = ["Sequence", "Start", "End", "Coverage"]
You could reference controls inside the master page this way:
void Page_Load()
{
ContentPlaceHolder cph;
Literal lit;
cph = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if (cph != null) {
lit = (Literal) cph.FindControl("Literal1");
if (lit != null) {
lit.Text = "Some <b>HTML</b>";
}
}
}
In this example you have to put a Literal control in your ContentPlaceholder.
You can run the tool from Microsoft in this KB http://support.microsoft.com/default.aspx?scid=kb;en-us;Q195353 to fix the licensing issues for earlier ActiveX controls. This worked for me.
I googled a bit, and found this code here:
File file = getJarFileToLoadFrom();
String lcStr = getNameOfClassToLoad();
URL jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });
Class loadedClass = cl.loadClass(lcStr);
Can anyone share opinions/comments/answers regarding this approach?
My solution:
export class DashboardManagementComponent implements OnInit {
_cols = 5;
_rows = 10;
constructor() { }
ngOnInit() {
}
get cols() {
return Array(this._cols).fill(null).map((el, index) => index);
}
get rows() {
return Array(this._rows).fill(null).map((el, index) => index);
}
In html:
<div class="charts-setup">
<div class="col" *ngFor="let col of cols; let colIdx = index">
<div class="row" *ngFor="let row of rows; let rowIdx = index">
Col: {{colIdx}}, row: {{rowIdx}}
</div>
</div>
</div>
Read-Host
is one example of a cmdlet that -Confirm
does not have an effect on.-Confirm
is one of PowerShell's Common Parameters specifically a Risk-Mitigation Parameter which is used when a cmdlet is about to make a change to the system that is outside of the Windows PowerShell environment. Many but not all cmdlets support the -Confirm
risk mitigation parameter.
As an alternative the following would be an example of using the Read-Host
cmdlet and a regular expression test to get confirmation from a user:
$reply = Read-Host -Prompt "Continue?[y/n]"
if ( $reply -match "[yY]" ) {
# Highway to the danger zone
}
The Remove-Variable
cmdlet is one example that illustrates the usage of the -confirm
switch.
Remove-Variable 'reply' -Confirm
Additional References: CommonParameters, Write-Host, Read-Host, Comparison Operators, Regular Expressions, Remove-Variable
From my little date difference calculator:
var startDate = new Date(2000, 1-1, 1); // 2000-01-01
var endDate = new Date(); // Today
// Calculate the difference of two dates in total days
function diffDays(d1, d2)
{
var ndays;
var tv1 = d1.valueOf(); // msec since 1970
var tv2 = d2.valueOf();
ndays = (tv2 - tv1) / 1000 / 86400;
ndays = Math.round(ndays - 0.5);
return ndays;
}
So you would call:
var nDays = diffDays(startDate, endDate);
(Full source at http://david.tribble.com/src/javascript/jstimespan.html.)
Addendum
The code can be improved by changing these lines:
var tv1 = d1.getTime(); // msec since 1970
var tv2 = d2.getTime();
Top to @loop answer.
We got below error for Asp.Net MVC, Unable to connect to the remote server
Fix: After adding the below code in Web.Confing issue has been resolved for us
<system.net>
<defaultProxy useDefaultCredentials="true" >
</defaultProxy>
</system.net>
Maximum is 2097151, If you try set more error occurred.
You can reference Microsoft.VisualBasic.dll
.
Then using the code below.
Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");
Alternatively, by adding a using
directive allowing for a shorter syntax in your code (which I'd personally prefer).
using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");
Or you can do what Pranay Rana suggests, that's what I would've done too...
In Chrome, right click in the console and check 'preserve log on navigation'.
The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.
For example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class DownloadPage {
public static void main(String[] args) throws IOException {
// Make a URL to the web page
URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
InputStream is =con.getInputStream();
// Once you have the Input Stream, it's just plain old Java IO stuff.
// For this case, since you are interested in getting plain-text web page
// I'll use a reader and output the text content to System.out.
// For binary content, it's better to directly read the bytes from stream and write
// to the target file.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
// read each line and write to System.out
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
Hope this helps.
I know there were lots of answers here, but the TL;DR version is this (If you're using Xamarin Studio):
Options
Android Build
Advanced
tabx86
/ armeabi-v7a
/ armeabi
)Scott Holden's blog entry on when to (and when not to) call GC.Collect is specific to the .NET Compact Framework, but the rules generally apply to all managed development.
Question : string "4.0000" can not be convert into integer using Int("4.000")?
Answer : Int() check string is integer or not if yes then give you integer and otherwise nil. but Float or Double can convert any number string to respective Float or Double without giving nil. Example if you have "45" integer string but using Float("45") gives you 45.0 float value or using Double("4567") gives you 45.0.
Solution : NSString(string: "45.000").integerValue or Int(Float("45.000")!)! to get correct result.
ansible-playbook release.yml --extra-vars "username=hello password=bye"
#you can now use the above command anywhere in the playbook as an example below:
tasks:
- name: Create a new user in Linux
shell: useradd -m -p {{username}} {{password}}"
If you're using lua with nginx/openresty you could use ngx.now() which returns a float with millisecond precision
I struggled with this problem for awhile and did several reinstalls of MySQL before discovering this.
I know that MySQL server was running OK because I could access all my DB's using the command line.
Hope this works for you.
In MySQL Workbench (5.2.47 CE)
click Mange Server Instances (bottom right corner)
click Connection
in the Connection box select:
Local Instance ($ServerName) - [email protected]:3306 '<'Standard(TCP/IP)>
click Edit Selected...
under Parameters, Hostname change localhost or 127.0.0.1 to your NetBIOS name
click Test Connection
If this works for you, great. If not change the hostname back to what it was.
Same issue. In my case I solved setting the project as the "StartUp Project".
Updating the accepted answer (can't comment yet). As of 1/12/16 using the demo jsfiddle in chrome, switch-immediate is the fastest solution.
Results: Time resolution: 1.33
25ms "if-immediate" 150878146
29ms "if-indirect" 150878146
24ms "switch-immediate" 150878146
128ms "switch-range" 150878146
45ms "switch-range2" 150878146
47ms "switch-indirect-array" 150878146
43ms "array-linear-switch" 150878146
72ms "array-binary-switch" 150878146
Finished
1.04 ( 25ms) if-immediate
1.21 ( 29ms) if-indirect
1.00 ( 24ms) switch-immediate
5.33 ( 128ms) switch-range
1.88 ( 45ms) switch-range2
1.96 ( 47ms) switch-indirect-array
1.79 ( 43ms) array-linear-switch
3.00 ( 72ms) array-binary-switch
export
is used to set environment variables. For example:
export EDITOR=pico
Will set your default text editor to be the pico
command.
I think the best option in Terms of performance (or in any terms) is to Distinct using the The IEqualityComparer interface.
Although implementing each time a new comparer for each class is cumbersome and produces boilerplate code.
So here is an extension method which produces a new IEqualityComparer on the fly for any class using reflection.
Usage:
var filtered = taskList.DistinctBy(t => t.TaskExternalId).ToArray();
Extension Method Code
public static class LinqExtensions
{
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
{
GeneralPropertyComparer<T, TKey> comparer = new GeneralPropertyComparer<T,TKey>(property);
return items.Distinct(comparer);
}
}
public class GeneralPropertyComparer<T,TKey> : IEqualityComparer<T>
{
private Func<T, TKey> expr { get; set; }
public GeneralPropertyComparer (Func<T, TKey> expr)
{
this.expr = expr;
}
public bool Equals(T left, T right)
{
var leftProp = expr.Invoke(left);
var rightProp = expr.Invoke(right);
if (leftProp == null && rightProp == null)
return true;
else if (leftProp == null ^ rightProp == null)
return false;
else
return leftProp.Equals(rightProp);
}
public int GetHashCode(T obj)
{
var prop = expr.Invoke(obj);
return (prop==null)? 0:prop.GetHashCode();
}
}
All necessary git bash commands to push and pull into Github:
git status
git pull
git add filefullpath
git commit -m "comments for checkin file"
git push origin branch/master
git remote -v
git log -2
If you want to edit a file then:
edit filename.*
To see all branches and their commits:
git show-branch
I did the Following in Kotlin
Edit the Application Class as Follows
class FTApplication: MultiDexApplication() {
override fun attachBaseContext(base: Context?) {
super.attachBaseContext(base)
MultiDex.install(this)
}
init {
instance = this
}
val mFTActivityLifecycleCallbacks = FTActivityLifecycleCallbacks()
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(mFTActivityLifecycleCallbacks)
}
companion object {
private var instance: FTApplication? = null
fun currentActivity(): Activity? {
return instance!!.mFTActivityLifecycleCallbacks.currentActivity
}
}
}
Create the ActivityLifecycleCallbacks class
class FTActivityLifecycleCallbacks: Application.ActivityLifecycleCallbacks {
var currentActivity: Activity? = null
override fun onActivityPaused(activity: Activity?) {
currentActivity = activity
}
override fun onActivityResumed(activity: Activity?) {
currentActivity = activity
}
override fun onActivityStarted(activity: Activity?) {
currentActivity = activity
}
override fun onActivityDestroyed(activity: Activity?) {
}
override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
}
override fun onActivityStopped(activity: Activity?) {
}
override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
currentActivity = activity
}
}
you can now use it in any class by calling the following: FTApplication.currentActivity()
In case you are sending a string, urlencode() it. Otherwise if array, it should be key=>value paired and the Content-type
header is automatically set to multipart/form-data
.
Also, you don't have to create extra functions to build the query for your arrays, you already have that:
$query = http_build_query($data, '', '&');
It is syntax error because you did not write parenthesis
if you write
Select datetime('now') then it will give you utc time but if you this write it query then you must add parenthesis before this so (datetime('now')) for UTC Time. for local time same Select datetime('now','localtime') for query
(datetime('now','localtime'))
using System.Diagnostics;
...
var st = new StackTrace();
var sf = st.GetFrame(0);
var currentMethodName = sf.GetMethod();
Or, if you'd like to have a helper method:
[MethodImpl(MethodImplOptions.NoInlining)]
public string GetCurrentMethod()
{
var st = new StackTrace();
var sf = st.GetFrame(1);
return sf.GetMethod().Name;
}
Updated with credits to @stusmith.
Simple example:
public function productsAction()
{
$saveFileName = 'ceneo.xml';
$filename = $this->path . $saveFileName;
if(file_exists($filename)) {
$reader = new XMLReader();
$reader->open($filename);
$countElements = 0;
while($reader->read()) {
if($reader->nodeType == XMLReader::ELEMENT) {
$nodeName = $reader->name;
}
if($reader->nodeType == XMLReader::TEXT && !empty($nodeName)) {
switch ($nodeName) {
case 'id':
var_dump($reader->value);
break;
}
}
if($reader->nodeType == XMLReader::END_ELEMENT && $reader->name == 'offer') {
$countElements++;
}
}
$reader->close();
exit(print('<pre>') . var_dump($countElements));
}
}
Ports 465 and 587 are intended for email client to email server communication - sending out email using SMTP protocol.
Port 465 is for smtps
SSL encryption is started automatically before any SMTP level communication.
Port 587 is for msa
It is almost like standard SMTP port.
MSA should accept email after authentication (e.g. after SMTP AUTH). It helps to stop outgoing spam when netmasters of DUL ranges can block outgoing connections to SMTP port (port 25).
SSL encryption may be started by STARTTLS command at SMTP level if server supports it and your ISP does not filter server's EHLO reply (reported 2014).
Port 25 is used by MTA to MTA communication (mail server to mail server). It may be used for client to server communication but it is not currently the most recommended. Standard SMTP port accepts email from other mail servers to its "internal" mailboxes without authentication.
If you want the object_name prefixed to any ID you should call form helpers on the form object:
- form_for(@message) do |f|
= f.label :email
This also makes sure any submitted data is stored in memory should there be any validation errors etc.
If you can't call the form helper method on the form object, for example if you're using a tag helper (radio_button_tag etc.) you can interpolate the name using:
= radio_button_tag "#{f.object_name}[email]", @message.email
In this case you'd need to specify the value manually to preserve any submissions.
I recently came across a case where none of these answers worked. I encountered CSV data where there were null bytes mixed in with the data, and those null bytes did not get stripped. So, my numeric string, after stripping, consisted of bytes like this:
\x00\x31\x00\x0d\x00
To counter this, I did:
countStr = fields[3].replace('\x00', '').strip()
count = int(countStr)
...where fields is a list of csv values resulting from splitting the line.
Given worked for me.
document.querySelectorAll(".widget.hover").forEach(obj=>obj.classList.remove("hover"));
As per my analysis and search on the internet also, I could not found a way to centre the image vertically centred using <div>
it was possible only using <table>
because table provides the following property:
valign="middle"
if you have http://php.net/manual/en/book.intl.php available, this solved your problem
$string = "Fóø Bår";
$transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: Lower(); :: NFC;', Transliterator::FORWARD);
echo $normalized = $transliterator->transliterate($string);
Checkout the files in https://github.com/PyCQA/pylint/tree/master/pylint/checkers. I haven't found a better way to obtain the error name from a message than either Ctrl + F-ing those files or using the GitHub search feature:
If the message is "No name ... in module ...", use the search:
No name %r in module %r repo:PyCQA/pylint/tree/master path:/pylint/checkers
Or, to get fewer results:
"No name %r in module %r" repo:PyCQA/pylint/tree/master path:/pylint/checkers
GitHub will show you:
"E0611": (
"No name %r in module %r",
"no-name-in-module",
"Used when a name cannot be found in a module.",
You can then do:
from collections import Sequence # pylint: disable=no-name-in-module
based on OP's answer to question:
Please see this link. Its having a different solution, which looks working for the person who asked the question. I'm trying to figure out a solution like this.
Paginated query using sorting on different columns using ROW_NUMBER() OVER () in SQL Server 2005
~Joseph
"method 1" is like the OP's query from the linked question, and "method 2" is like the query from the selected answer. You had to look at the code linked in this answer to see what was really going on, since the code in the selected answer was modified to make it work. Try this:
DECLARE @YourTable table (RowID int not null primary key identity, Value1 int, Value2 int, value3 int)
SET NOCOUNT ON
INSERT INTO @YourTable VALUES (1,1,1)
INSERT INTO @YourTable VALUES (1,1,2)
INSERT INTO @YourTable VALUES (1,1,3)
INSERT INTO @YourTable VALUES (1,2,1)
INSERT INTO @YourTable VALUES (1,2,2)
INSERT INTO @YourTable VALUES (1,2,3)
INSERT INTO @YourTable VALUES (1,3,1)
INSERT INTO @YourTable VALUES (1,3,2)
INSERT INTO @YourTable VALUES (1,3,3)
INSERT INTO @YourTable VALUES (2,1,1)
INSERT INTO @YourTable VALUES (2,1,2)
INSERT INTO @YourTable VALUES (2,1,3)
INSERT INTO @YourTable VALUES (2,2,1)
INSERT INTO @YourTable VALUES (2,2,2)
INSERT INTO @YourTable VALUES (2,2,3)
INSERT INTO @YourTable VALUES (2,3,1)
INSERT INTO @YourTable VALUES (2,3,2)
INSERT INTO @YourTable VALUES (2,3,3)
INSERT INTO @YourTable VALUES (3,1,1)
INSERT INTO @YourTable VALUES (3,1,2)
INSERT INTO @YourTable VALUES (3,1,3)
INSERT INTO @YourTable VALUES (3,2,1)
INSERT INTO @YourTable VALUES (3,2,2)
INSERT INTO @YourTable VALUES (3,2,3)
INSERT INTO @YourTable VALUES (3,3,1)
INSERT INTO @YourTable VALUES (3,3,2)
INSERT INTO @YourTable VALUES (3,3,3)
SET NOCOUNT OFF
DECLARE @PageNumber int
DECLARE @PageSize int
DECLARE @SortBy int
SET @PageNumber=3
SET @PageSize=5
SET @SortBy=1
--SELECT * FROM @YourTable
--Method 1
;WITH PaginatedYourTable AS (
SELECT
RowID,Value1,Value2,Value3
,CASE @SortBy
WHEN 1 THEN ROW_NUMBER() OVER (ORDER BY Value1 ASC)
WHEN 2 THEN ROW_NUMBER() OVER (ORDER BY Value2 ASC)
WHEN 3 THEN ROW_NUMBER() OVER (ORDER BY Value3 ASC)
WHEN -1 THEN ROW_NUMBER() OVER (ORDER BY Value1 DESC)
WHEN -2 THEN ROW_NUMBER() OVER (ORDER BY Value2 DESC)
WHEN -3 THEN ROW_NUMBER() OVER (ORDER BY Value3 DESC)
END AS RowNumber
FROM @YourTable
--WHERE
)
SELECT
RowID,Value1,Value2,Value3,RowNumber
,@PageNumber AS PageNumber, @PageSize AS PageSize, @SortBy AS SortBy
FROM PaginatedYourTable
WHERE RowNumber>=(@PageNumber-1)*@PageSize AND RowNumber<=(@PageNumber*@PageSize)-1
ORDER BY RowNumber
--------------------------------------------
--Method 2
;WITH PaginatedYourTable AS (
SELECT
RowID,Value1,Value2,Value3
,ROW_NUMBER() OVER
(
ORDER BY
CASE @SortBy
WHEN 1 THEN Value1
WHEN 2 THEN Value2
WHEN 3 THEN Value3
END ASC
,CASE @SortBy
WHEN -1 THEN Value1
WHEN -2 THEN Value2
WHEN -3 THEN Value3
END DESC
) RowNumber
FROM @YourTable
--WHERE more conditions here
)
SELECT
RowID,Value1,Value2,Value3,RowNumber
,@PageNumber AS PageNumber, @PageSize AS PageSize, @SortBy AS SortBy
FROM PaginatedYourTable
WHERE
RowNumber>=(@PageNumber-1)*@PageSize AND RowNumber<=(@PageNumber*@PageSize)-1
--AND more conditions here
ORDER BY
CASE @SortBy
WHEN 1 THEN Value1
WHEN 2 THEN Value2
WHEN 3 THEN Value3
END ASC
,CASE @SortBy
WHEN -1 THEN Value1
WHEN -2 THEN Value2
WHEN -3 THEN Value3
END DESC
OUTPUT:
RowID Value1 Value2 Value3 RowNumber PageNumber PageSize SortBy
------ ------ ------ ------ ---------- ----------- ----------- -----------
10 2 1 1 10 3 5 1
11 2 1 2 11 3 5 1
12 2 1 3 12 3 5 1
13 2 2 1 13 3 5 1
14 2 2 2 14 3 5 1
(5 row(s) affected
RowID Value1 Value2 Value3 RowNumber PageNumber PageSize SortBy
------ ------ ------ ------ ---------- ----------- ----------- -----------
10 2 1 1 10 3 5 1
11 2 1 2 11 3 5 1
12 2 1 3 12 3 5 1
13 2 2 1 13 3 5 1
14 2 2 2 14 3 5 1
(5 row(s) affected)
I am just wondering why to use some libraries for JWT token decoding and verification at all.
Encoded JWT token can be created using following pseudocode
var headers = base64URLencode(myHeaders);
var claims = base64URLencode(myClaims);
var payload = header + "." + claims;
var signature = base64URLencode(HMACSHA256(payload, secret));
var encodedJWT = payload + "." + signature;
It is very easy to do without any specific library. Using following code:
using System;
using System.Text;
using System.Security.Cryptography;
public class Program
{
// More info: https://stormpath.com/blog/jwt-the-right-way/
public static void Main()
{
var header = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}";
var claims = "{\"sub\":\"1047986\",\"email\":\"[email protected]\",\"given_name\":\"John\",\"family_name\":\"Doe\",\"primarysid\":\"b521a2af99bfdc65e04010ac1d046ff5\",\"iss\":\"http://example.com\",\"aud\":\"myapp\",\"exp\":1460555281,\"nbf\":1457963281}";
var b64header = Convert.ToBase64String(Encoding.UTF8.GetBytes(header))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
var b64claims = Convert.ToBase64String(Encoding.UTF8.GetBytes(claims))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
var payload = b64header + "." + b64claims;
Console.WriteLine("JWT without sig: " + payload);
byte[] key = Convert.FromBase64String("mPorwQB8kMDNQeeYO35KOrMMFn6rFVmbIohBphJPnp4=");
byte[] message = Encoding.UTF8.GetBytes(payload);
string sig = Convert.ToBase64String(HashHMAC(key, message))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
Console.WriteLine("JWT with signature: " + payload + "." + sig);
}
private static byte[] HashHMAC(byte[] key, byte[] message)
{
var hash = new HMACSHA256(key);
return hash.ComputeHash(message);
}
}
The token decoding is reversed version of the code above.To verify the signature you will need to the same and compare signature part with calculated signature.
UPDATE: For those how are struggling how to do base64 urlsafe encoding/decoding please see another SO question, and also wiki and RFCs
If you don't have password you can use the command without
-u
Like this
C:\wamp>bin\mysql\mysql5.7.11\bin\mysql.exe -u {User Name} {Database Name} < C:\File.sql
Or on the SQL console
mysql -u {User Name} -p {Database Name} < C:/File.sql
You could use a dict
object's get()
method, as others have already suggested. Alternatively, depending on exactly what you're doing, you might be able use a try/except
suite like this:
try:
<to do something with d[key]>
except KeyError:
<deal with it not being there>
Which is considered to be a very "Pythonic" approach to handling the case.
To add to the (really good) existing answer
open_basedir
is one that can stump you because it can be specified in a web server configuration. While this is easily remedied if you run your own dedicated server, there are some shared hosting software packages out there (like Plesk, cPanel, etc) that will configure a configuration directive on a per-domain basis. Because the software builds the configuration file (i.e. httpd.conf
) you cannot change that file directly because the hosting software will just overwrite it when it restarts.
With Plesk, they provide a place to override the provided httpd.conf
called vhost.conf
. Only the server admin can write this file. The configuration for Apache looks something like this
<Directory /var/www/vhosts/domain.com>
<IfModule mod_php5.c>
php_admin_flag engine on
php_admin_flag safe_mode off
php_admin_value open_basedir "/var/www/vhosts/domain.com:/tmp:/usr/share/pear:/local/PEAR"
</IfModule>
</Directory>
Have your server admin consult the manual for the hosting and web server software they use.
It's important to note that executing a file through your web server is very different from a command line or cron job execution. The big difference is that your web server has its own user and permissions. For security reasons that user is pretty restricted. Apache, for instance, is often apache
, www-data
or httpd
(depending on your server). A cron job or CLI execution has whatever permissions that the user running it has (i.e. running a PHP script as root will execute with permissions of root).
A lot of times people will solve a permissions problem by doing the following (Linux example)
chmod 777 /path/to/file
This is not a smart idea, because the file or directory is now world writable. If you own the server and are the only user then this isn't such a big deal, but if you're on a shared hosting environment you've just given everyone on your server access.
What you need to do is determine the user(s) that need access and give only those them access. Once you know which users need access you'll want to make sure that
That user owns the file and possibly the parent directory (especially the parent directory if you want to write files). In most shared hosting environments this won't be an issue, because your user should own all the files underneath your root. A Linux example is shown below
chown apache:apache /path/to/file
The user, and only that user, has access. In Linux, a good practice would be chmod 600
(only owner can read and write) or chmod 644
(owner can write but everyone can read)
You can read a more extended discussion of Linux/Unix permissions and users here
Go to Settings -> Compiler... And add flag to "Have g++ follow the coming C++0x ISO C++ language standard [std=c++0x]
You can simply do :-
{{"<li>Something</li>".repeat(5)}}
If you are like me - you did this by inadvertently hitting F11 - toggling fullscreen mode. https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf
Branch with short hash and last comment:
git branch -v
develop 717c2f9 [ahead 42] blabla
* master 2722bbe [ahead 1] bla
As of API 21, you should use the getDrawable(int, Theme)
method instead of getDrawable(int)
, as it allows you to fetch a drawable
object associated with a particular resource ID
for the given screen density/theme
. Calling the deprecated
getDrawable(int)
method is equivalent to calling getDrawable(int, null)
.
You should use the following code from the support library instead:
ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
Using this method is equivalent to calling:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return resources.getDrawable(id, context.getTheme());
} else {
return resources.getDrawable(id);
}
layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/layoutTest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
</LinearLayout>
</RelativeLayout>
class file:
setContentView(R.layout.layout_dynamic);
layoutTest=(LinearLayout)findViewById(R.id.layoutTest);
TextView textView = new TextView(getApplicationContext());
textView.setText("testDynamic textView");
layoutTest.addView(textView);
System.Environment has WorkingSet- a 64-bit signed integer containing the number of bytes of physical memory mapped to the process context.
If you want a lot of details there is System.Diagnostics.PerformanceCounter, but it will be a bit more effort to setup.
Try to convert one of the rows into timestamp using the pd.to_datetime function and then use .map to map the formular to the entire column
I use a way that may look stupid but it works for me. I simply concat the columns I want to compare and use NOT IN:
SELECT *
FROM table1 t1
WHERE CONCAT(t1.first_name,t1.last_name) NOT IN (SELECT CONCAT(t2.first_name,t2.last_name) FROM table2 t2)
.NET Standard: Think of it as a big standard library. When using this as a dependency you can only make libraries (.DLLs), not executables. A library made with .NET standard as a dependency can be added to a Xamarin.Android, a Xamarin.iOS, a .NET Core Windows/OS X/Linux project.
.NET Core: Think of it as the continuation of the old .NET framework, just it's opensource and some stuff is not yet implemented and others got deprecated. It extends the .NET standard with extra functions, but it only runs on desktops. When adding this as a dependency you can make runnable applications on Windows, Linux and OS X. (Although console only for now, no GUIs). So .NET Core = .NET Standard + desktop specific stuff.
Also UWP uses it and the new ASP.NET Core uses it as a dependency too.
This happened if you change something in data set using native sql query but persisted object for same data set is present in session cache. Use session.evict(yourObject);
You can use .is(':visible')
Selects all elements that are visible.
For example:
if($('#selectDiv').is(':visible')){
Also, you can get the div which is visible by:
$('div:visible').callYourFunction();
Live example:
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
display: none; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
There is also who is active?:
Who is Active? is a comprehensive server activity stored procedure based on the SQL Server 2005 and 2008 dynamic management views (DMVs). Think of it as sp_who2 on a hefty dose of anabolic steroids
Don't forget that unlike Windows, all Unix based system need to have the source before destination unlike Windows
On Windows its:
mov $source , %destination
but on the Mac its the other way around.
TLDR; (just read the bold text)
Most answers here will tell you how to create an empty DataFrame and fill it out, but no one will tell you that it is a bad thing to do.
Here is my advice: Accumulate data in a list, not a DataFrame.
Use a list to collect your data, then initialise a DataFrame when you are ready. Either a list-of-lists or list-of-dicts format will work, pd.DataFrame
accepts both.
data = []
for a, b, c in some_function_that_yields_data():
data.append([a, b, c])
df = pd.DataFrame(data, columns=['A', 'B', 'C'])
Pros of this approach:
It is always cheaper to append to a list and create a DataFrame in one go than it is to create an empty DataFrame (or one of NaNs) and append to it over and over again.
Lists also take up less memory and are a much lighter data structure to work with, append, and remove (if needed).
dtypes
are automatically inferred (rather than assigning object
to all of them).
A RangeIndex
is automatically created for your data, instead of you having to take care to assign the correct index to the row you are appending at each iteration.
If you aren't convinced yet, this is also mentioned in the documentation:
Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once.
That's fine, you can still do this in linear time by growing or creating a python list of smaller DataFrames, then calling pd.concat
.
small_dfs = []
for small_df in some_function_that_yields_dataframes():
small_dfs.append(small_df)
large_df = pd.concat(small_dfs, ignore_index=True)
or, more concisely:
large_df = pd.concat(
list(some_function_that_yields_dataframes()), ignore_index=True)
append
or concat
inside a loopHere is the biggest mistake I've seen from beginners:
df = pd.DataFrame(columns=['A', 'B', 'C'])
for a, b, c in some_function_that_yields_data():
df = df.append({'A': i, 'B': b, 'C': c}, ignore_index=True) # yuck
# or similarly,
# df = pd.concat([df, pd.Series({'A': i, 'B': b, 'C': c})], ignore_index=True)
Memory is re-allocated for every append
or concat
operation you have. Couple this with a loop and you have a quadratic complexity operation.
The other mistake associated with df.append
is that users tend to forget append is not an in-place function, so the result must be assigned back. You also have to worry about the dtypes:
df = pd.DataFrame(columns=['A', 'B', 'C'])
df = df.append({'A': 1, 'B': 12.3, 'C': 'xyz'}, ignore_index=True)
df.dtypes
A object # yuck!
B float64
C object
dtype: object
Dealing with object columns is never a good thing, because pandas cannot vectorize operations on those columns. You will need to do this to fix it:
df.infer_objects().dtypes
A int64
B float64
C object
dtype: object
loc
inside a loopI have also seen loc
used to append to a DataFrame that was created empty:
df = pd.DataFrame(columns=['A', 'B', 'C'])
for a, b, c in some_function_that_yields_data():
df.loc[len(df)] = [a, b, c]
As before, you have not pre-allocated the amount of memory you need each time, so the memory is re-grown each time you create a new row. It's just as bad as append
, and even more ugly.
And then, there's creating a DataFrame of NaNs, and all the caveats associated therewith.
df = pd.DataFrame(columns=['A', 'B', 'C'], index=range(5))
df
A B C
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 NaN NaN NaN
4 NaN NaN NaN
It creates a DataFrame of object columns, like the others.
df.dtypes
A object # you DON'T want this
B object
C object
dtype: object
Appending still has all the issues as the methods above.
for i, (a, b, c) in enumerate(some_function_that_yields_data()):
df.iloc[i] = [a, b, c]
Timing these methods is the fastest way to see just how much they differ in terms of their memory and utility.
You can use the Bean Comparator to sort on any property in your custom class.
Here is the documentation of <select>
. You are using 2 attributes:
multiple
This Boolean attribute indicates that multiple options can be selected in the list. If it is not specified, then only one option can be selected at a time. When multiple is specified, most browsers will show a scrolling list box instead of a single line dropdown.
size
If the control is presented as a scrolling list box (e.g. when multiple is specified), this attribute represents the number of rows in the list that should be visible at one time. Browsers are not required to present a select element as a scrolled list box. The default value is 0.
As described in the docs. <select size="1" multiple>
will render a List box only 1 line visible and a scrollbar. So you are loosing the dropdown/arrow with the multiple
attribute.
I have found a way if you know startIndex and endIndex of the elements one need to remove from ArrayList
Let al
be the original ArrayList and startIndex
,endIndex
be start and end index to be removed from the array respectively:
al.subList(startIndex, endIndex + 1).clear();
as answered above: Object.keys(obj).length
But: as we have now a real Map class in ES6, I would suggest to use it instead of using the properties of an object.
const map = new Map();
map.set("key", "value");
map.size; // THE fastest way
I know this has been answered already and it's an old question, but here's an extension method to do the same:
public static class DataExtensions
{
public static bool AreAllCellsEmpty(this DataRow row)
{
var itemArray = row.ItemArray;
if(itemArray==null)
return true;
return itemArray.All(x => string.IsNullOrWhiteSpace(x.ToString()));
}
}
And you use it like so:
if (dr.AreAllCellsEmpty())
// etc
test.matches() method checks all text.use test.find()
I solved the problem by enabling the mod_autoindex
from Apache. It was disabled by default.
sudo a2enmod autoindex
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.
A "REST service" and a "RESTful service" are one and the same.
A RESTful system is any system that follows the REST conventions as defined in the original document that created the idea of RESTful networked applications.
It's worth noting there are varying levels of RESTfulness. Overall, REST is a style, not a standard, so there is room for interpretation based on needs. one example is hierarchical resource URLs (e.g. /things/ID/relatedthings
) vs flat URLs (e.g. /things/ID
and /relatedthings?thing=ID
)
// inVisible
TabPage page2 = tabControl1.TabPages[0];
page2.Visible= false;
//Visible
page2.Visible= true;
// disable
TabPage page2 = tabControl1.TabPages[0];
page2.Enabled = false;
// enable
page2.Enabled = true;
//Hide
tabCtrlTagInfo.TabPages(0).Hide()
tabCtrlTagInfo.TabPages(0).Show()
Just copy paste and try it,the above code has been tested in vs2010, it works.
In my case, the issue was with a new class
not being recognized. I solved the issue by deleting the class and re-adding it but this time checking the Watch App Extension
option when creating the new class.
Please note that I do have a Watch App Extension in my Application.
import java.io.*;
import java.util.*;
import java.util.HashMap;
public class Solution
{
public static void main(String[] args)
{
HashMap<Integer,String> hm = new HashMap<Integer,String>();
hm.put(1,"SUNDAY");
hm.put(2,"MONDAY");
hm.put(3,"TUESDAY");
hm.put(4,"WEDNESDAY");
hm.put(5,"THURSDAY");
hm.put(6,"FRIDAY");
hm.put(7,"SATURDAY");
Scanner in = new Scanner(System.in);
String month = in.next();
String day = in.next();
String year = in.next();
String format = year + "/" + month + "/" + day;
Date date = null;
try
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
date = formatter.parse(format);
}
catch(Exception e){
}
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println(hm.get(dayOfWeek));
}
}
I would rather use the Date valueOf method instead of === or !==
Seems like === is comparing internal Object's references and nothing concerning date.
Assuming that your branch is called master
both here and remotely, and that your remote is called origin
you could do:
git reset --hard <commit-hash>
git push -f origin master
However, you should avoid doing this if anyone else is working with your remote repository and has pulled your changes. In that case, it would be better to revert the commits that you don't want, then push as normal.
The generic view of a loop is
for (initialization; condition; increment-decrement){}
The first part initializes the code. The second part is the condition that will continue to run the loop as long as it is true. The last part is what will be run after each iteration of the loop. The last part is typically used to increment or decrement a counter, but it doesn't have to.
This method might not be the most efficient but is simple and does the job.
It performs two operations: firstly it calls .ToString() which is basiclly a serialization, and then the deserialization using Newtonsoft nuget (which you must install).
public T Format<T>(Object obj) =>
JsonConvert.DeserializeObject<T>(obj.ToString());
If you just want to change alignment of text just make a classes
.left {
text-align: left;
}
and span that class through the text
<span class='left'>aligned left</span>
Do not use communicate(input=""). It writes input to the process, closes its stdin and then reads all output.
Do it like this:
p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)
# get output from process "Something to print"
one_line_output = p.stdout.readline()
# write 'a line\n' to the process
p.stdin.write('a line\n')
# get output from process "not time to break"
one_line_output = p.stdout.readline()
# write "n\n" to that process for if r=='n':
p.stdin.write('n\n')
# read the last output from the process "Exiting"
one_line_output = p.stdout.readline()
What you would do to remove the error:
all_the_process_will_tell_you = p.communicate('all you will ever say to this process\nn\n')[0]
But since communicate closes the stdout
and stdin
and stderr
, you can not read or write after you called communicate.
Rule of three in C++ is a fundamental principle of the design and the development of three requirements that if there is clear definition in one of the following member function, then the programmer should define the other two members functions together. Namely the following three member functions are indispensable: destructor, copy constructor, copy assignment operator.
Copy constructor in C++ is a special constructor. It is used to build a new object, which is the new object equivalent to a copy of an existing object.
Copy assignment operator is a special assignment operator that is usually used to specify an existing object to others of the same type of object.
There are quick examples:
// default constructor
My_Class a;
// copy constructor
My_Class b(a);
// copy constructor
My_Class c = a;
// copy assignment operator
b = a;
I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:
var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";
console.log( JSON.stringify(display) );
This will print:
["none","block","none"]
This is how JSON actually serializes array. However what you want to see is something like:
{"0":"none","1":"block","2":"none"}
To get this format you want to serialize object, not array. So let's rewrite above code like this:
var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";
console.log( JSON.stringify(display2) );
This will print in the format you want.
You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console
Default: 5672, the manual has the answer. It's defined in the RABBITMQ_NODE_PORT
variable.
https://www.rabbitmq.com/configure.html#define-environment-variables
The number might be differently if changed by someone in the rabbitmq configuration file:
vi /etc/rabbitmq/rabbitmq-env.conf
Ask the computer to tell you:
sudo nmap -p 1-65535 localhost
Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:50 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00041s latency).
PORT STATE SERVICE
443/tcp open https
5672/tcp open amqp
15672/tcp open unknown
35102/tcp open unknown
59440/tcp open unknown
Oh look, 5672, and 15672
Use netstat:
netstat -lntu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:15672 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:55672 0.0.0.0:* LISTEN
tcp 0 0 :::5672 :::* LISTEN
Oh look 5672.
use lsof:
eric@dev ~$ sudo lsof -i | grep beam
beam.smp 21216 rabbitmq 17u IPv4 33148214 0t0 TCP *:55672 (LISTEN)
beam.smp 21216 rabbitmq 18u IPv4 33148219 0t0 TCP *:15672 (LISTEN)
use nmap from a different machine, find out if 5672 is open:
sudo nmap -p 5672 10.0.1.71
Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:19 EDT
Nmap scan report for 10.0.1.71
Host is up (0.00011s latency).
PORT STATE SERVICE
5672/tcp open amqp
MAC Address: 0A:40:0E:8C:75:6C (Unknown)
Nmap done: 1 IP address (1 host up) scanned in 0.13 seconds
Try to connect to a port manually with telnet, 5671 is CLOSED:
telnet localhost 5671
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
Try to connect to a port manually with telnet, 5672 is OPEN:
telnet localhost 5672
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Check your firewall:
sudo cat /etc/sysconfig/iptables
It should tell you what ports are made open:
-A INPUT -p tcp -m tcp --dport 5672 -j ACCEPT
Reapply your firewall:
sudo service iptables restart
iptables: Setting chains to policy ACCEPT: filter [ OK ]
iptables: Flushing firewall rules: [ OK ]
iptables: Unloading modules: [ OK ]
iptables: Applying firewall rules: [ OK ]
Numpy's r_
convenience function can also create evenly spaced lists with syntax np.r_[start:stop:steps]
. If steps
is a real number (ending on j
), then the end point is included, equivalent to np.linspace(start, stop, step, endpoint=1)
, otherwise not.
>>> np.r_[-1:1:6j, [0]*3, 5, 6]
array([-1. , -0.6, -0.2, 0.2, 0.6, 1.])
You can also directly concatente other arrays and also scalars:
>>> np.r_[-1:1:6j, [0]*3, 5, 6]
array([-1. , -0.6, -0.2, 0.2, 0.6, 1. , 0. , 0. , 0. , 5. , 6. ])
This is cleaner way I am doing and it just works great
if (floor(NSFoundationVersionNumber) < NSFoundationVersionNumber_iOS_8_0)
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|
UIRemoteNotificationTypeAlert| UIRemoteNotificationTypeSound];
else {
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[application registerForRemoteNotifications];
}
In addition to the previous replies, I would like to introduce another function.
numpy.random.shuffle
as well as random.shuffle
perform in-place shuffling. However, if you want to return a shuffled array numpy.random.permutation
is the function to use.
I think it may be helpful to point out that if you want to select tables that contain specific words you can easily do it using the SELECT
(instead of SHOW
). Below query easily narrows down the search to tables that contain "keyword"
SELECT *
FROM information_schema.tables
WHERE table_name like "%keyword%"
I propose a simple convention:
If conversion to ASCII is > 0 or it starts with 0 then it is a number. It is not perfect but fast.
Something like this:
string token0;
if (atoi(token0.c_str())>0 || isdigit(token0.c_str()[0]) ) { //this is a value
// do what you need to do...
}
I know that I am late to party but performed test before actually implement the solution.
I did perform test against inbuilt MD5 class and also md5sum.exe. In my case inbuilt class took 13 second where md5sum.exe too around 16-18 seconds in every run.
DateTime current = DateTime.Now;
string file = @"C:\text.iso";//It's 2.5 Gb file
string output;
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(file))
{
byte[] checksum = md5.ComputeHash(stream);
output = BitConverter.ToString(checksum).Replace("-", String.Empty).ToLower();
Console.WriteLine("Total seconds : " + (DateTime.Now - current).TotalSeconds.ToString() + " " + output);
}
}
Use let...of instead of let...in !!
If you're new to Angular (>2.x) and possibly migrating from Angular1.x, most likely you're confusing in
with of
. As andreas has mentioned in the comments below for ... of
iterates over values
of an object while for ... in
iterates over properties
in an object. This is a new feature introduced in ES2015.
Simply replace:
<!-- Iterate over properties (incorrect in our case here) -->
<div *ngFor="let talk in talks">
with
<!-- Iterate over values (correct way to use here) -->
<div *ngFor="let talk of talks">
So, you must replace in
with of
inside ngFor
directive to get the values.
This is probably the easiest way, not the prettiest though:
SELECT *,
(SELECT Count(*) FROM eventsTable WHERE columnName = 'Business') as RowCount
FROM eventsTable
WHERE columnName = 'Business'
This will also work without having to use a group by
SELECT *, COUNT(*) OVER () as RowCount
FROM eventsTables
WHERE columnName = 'Business'
You need to get the content of the p tag and replace all the dolors in it with the highlighted version.
You don't even need to have jQuery for this. :-)
For compare hashed password with the plain text password string you can use the PHP password_verify
if(password_verify('1234567', $crypt_password_string)) {
// in case if "$crypt_password_string" actually hides "1234567"
}
Regarding Wolfwyrd's anwer: "On Error Resume Next" in fact turns error handling off! Not on. On Error Goto 0 turns error-handling back ON because at the least, we want the machine to catch it if we didn't write it in ourselves. Off = leaving it to you to handle it.
If you use On Error Resume Next, you need to be careful about how much code you include after it: remember, the phrase "If Err.Number <> 0 Then" only refers to the most previous error triggered.
If your block of code after "On Error Resume Next" has several places where you might reasonably expect it to fail, then you must place "If Err.number <> 0" after each and every one of those possible failure lines, to check execution.
Otherwise, after "on error resume next" means just what it says - your code can fail on as many lines as it likes and execution will continue merrily along. That's why it's a pain in the ass.
According to Reserved IP addresses there are 588,514,304 reserved addresses and since there are 4,294,967,296 (2^32) IPv4 addressess in total, there are 3,706,452,992 public addresses.
And too many addresses in this post.
If you are using Matplotlib and are trying to get good figures in a LaTeX document, save as an EPS. Specifically, try something like this after running the commands to plot the image:
plt.savefig('destination_path.eps', format='eps')
I have found that EPS files work best and the dpi
parameter is what really makes them look good in a document.
To specify the orientation of the figure before saving, simply call the following before the plt.savefig
call, but after creating the plot (assuming you have plotted using an axes with the name ax
):
ax.view_init(elev=elevation_angle, azim=azimuthal_angle)
Where elevation_angle
is a number (in degrees) specifying the polar angle (down from vertical z axis) and the azimuthal_angle
specifies the azimuthal angle (around the z axis).
I find that it is easiest to determine these values by first plotting the image and then rotating it and watching the current values of the angles appear towards the bottom of the window just below the actual plot. Keep in mind that the x, y, z, positions appear by default, but they are replaced with the two angles when you start to click+drag+rotate the image.
The answer by @hybrid is quite informative, except it doesn't explain the purpose as mentioned by @ashitaka "What if you use the Mobile First approach? So, we have the mobile CSS first and then use min-width to target larger sites. We shouldn't use the only keyword in that context, right? "
Want to add in here that the purpose is simply to prevent non supporting browsers to use that Other device style as if it starts from "screen" without it will take it for a screen whereas if it starts from "only" style will be ignored.
Answering to ashitaka consider this example
<link rel="stylesheet" type="text/css"
href="android.css" media="only screen and (max-width: 480px)" />
<link rel="stylesheet" type="text/css"
href="desktop.css" media="screen and (min-width: 481px)" />
If we don't use "only" it will still work as desktop-style will also be used striking android styles but with unnecessary overhead. In this case, IF a browser is non-supporting it will fallback to the second Style-sheet ignoring the first.
In psql alter column query syntax like this
Alter table users add column priv_user boolean default false ;
boolean value (true-false) save in DB like (t-f) value .
Technically possible. You would probably reference employees_ce in deductions and employees_sn. But why don't you merge employees_sn and employees_ce? I see no reason why you have two table. No one to many relationship. And (not in this example) many columns.
If you do two references for one column, an employee must have an entry in both tables.
your string is NOT a valid json to start with.
a valid json will be,
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
if you do a json_decode
, it will yield,
stdClass Object
(
[area] => Array
(
[0] => stdClass Object
(
[area] => kothrud
)
[1] => stdClass Object
(
[area] => katraj
)
)
)
Update: to use
$string = '
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
';
$area = json_decode($string, true);
foreach($area['area'] as $i => $v)
{
echo $v['area'].'<br/>';
}
Output:
kothrud
katraj
Update #2:
for that true
:
When TRUE, returned objects will be converted into associative arrays. for more information, click here
Another method is:
function isFloat(float) {
return /\./.test(float.toString());
}
Might not be as efficient as the others but another method all the same.
As hippietrail suggests, meder's answer can break surrogate pairs and misinterpret “characters.” For example:
// DO NOT USE THIS!
const a = ''.split('');
console.log(a);
_x000D_
I suggest using one of the following ES2015 features to correctly handle these character sequences.
const a = [...''];
console.log(a);
_x000D_
const a = Array.from('');
console.log(a);
_x000D_
u
flagconst a = ''.split(/(?=[\s\S])/u);
console.log(a);
_x000D_
Use /(?=[\s\S])/u
instead of /(?=.)/u
because .
does not match
newlines. If you are still in ES5.1 era (or if your browser doesn't
handle this regex correctly - like Edge), you can use the following alternative
(transpiled by Babel). Note, that Babel tries to also handle unmatched
surrogates correctly. However, this doesn't seem to work for unmatched low
surrogates.
const a = ''.split(/(?=(?:[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/);
console.log(a);
_x000D_
const s = '';
const a = [];
for (const s2 of s) {
a.push(s2);
}
console.log(a);
_x000D_
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {_x000D_
totalCost.value = checkbox.checked ? 10 : calculate();_x000D_
}_x000D_
_x000D_
function calculate() {_x000D_
return other.value*2;_x000D_
}
_x000D_
input { display: block}
_x000D_
Checkbox: <input type="checkbox" onclick="change(this)"/>_x000D_
Total cost: <input id="totalCost" type="number" value=5 />_x000D_
Other: <input id="other" type="number" value=7 />
_x000D_
To get the form that the submit is inside why not just
this.form
Easiest & quickest path to the result.
I had to cross compile C code in Ubuntu for ARM. This worked for me:
$ sudo apt install gcc-arm-none-eabi
Later, tested it on the qemu emulator
#Install qemu
sudo apt-get install qemu qemu-user-static qemu-system-arm
#Cross compile "helloworld.c"
$ arm-none-eabi-gcc --specs=rdimon.specs -Wl,--start-group -lgcc -lc -lm -lrdimon -Wl,--end-group helloworld.c -o helloworld
#Run
qemu-arm-static helloworld
Doing type('')
is effectively equivalent to str
and types.StringType
so type('') == str == types.StringType
will evaluate to "True
"
Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode)
or assert isinstance(obj, basestring)
, the latter of which was suggested in the comments by 007Brendan and is probably preferred.
isinstance()
is useful if you want to ask whether an object is an instance of a class, e.g:
class MyClass: pass
print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception
But for basic types, e.g. str
, unicode
, int
, float
, long
etc asking type(var) == TYPE
will work OK.
Every method (other than a constructor) must have a return type.
public double diameter(){...
It is better to add the condition in the Join. Performance is more important than readability. For large datasets, it matters.
Use below command
sudo a2enmod rewrite
And the restart apache through below command
sudo service apache2 restart
I have created on time task in which the task which user wants to repeat, add in the Custom TimeTask run() method. it is successfully reoccurring.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
CheckBox optSingleShot;
Button btnStart, btnCancel;
TextView textCounter;
Timer timer;
MyTimerTask myTimerTask;
int tobeShown = 0 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
optSingleShot = (CheckBox)findViewById(R.id.singleshot);
btnStart = (Button)findViewById(R.id.start);
btnCancel = (Button)findViewById(R.id.cancel);
textCounter = (TextView)findViewById(R.id.counter);
tobeShown = 1;
if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 1000);
}
btnStart.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this, ActivityB.class);
startActivity(i);
/*if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 1000);
}*/
}});
btnCancel.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if (timer!=null){
timer.cancel();
timer = null;
}
}
});
}
@Override
protected void onResume() {
super.onResume();
if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 1000);
}
}
@Override
protected void onPause() {
super.onPause();
if (timer!=null){
timer.cancel();
timer = null;
}
}
@Override
protected void onStop() {
super.onStop();
if (timer!=null){
timer.cancel();
timer = null;
}
}
class MyTimerTask extends TimerTask {
@Override
public void run() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
runOnUiThread(new Runnable(){
@Override
public void run() {
textCounter.setText(strDate);
}});
}
}
}
Store all the to be deleted ID's into a table. Then there are 3 ways. 1) loop through all the ID's in the table, then delete one row at a time for X commit interval. X can be a 100 or 1000. It works on OLTP environment and you can control the locks.
2) Use Oracle Bulk Delete
3) Use correlated delete query.
Single query is usually faster than multiple queries because of less context switching, and possibly less parsing.
date_part(text, timestamp)
e.g.
date_part('month', timestamp '2001-02-16 20:38:40'),
date_part('year', timestamp '2001-02-16 20:38:40')
http://www.postgresql.org/docs/8.0/interactive/functions-datetime.html
There is lecture on this by Sebastien Thurn in the free Udacity course AI for Robotics. Basically he makes a circular array of the indexed weights using the mod operator %
, sets a variable beta to 0, randomly chooses an index,
for loops through N where N is the number of indices and in the for loop firstly increments beta by the formula:
beta = beta + uniform sample from {0...2* Weight_max}
and then nested in the for loop, a while loop per below:
while w[index] < beta:
beta = beta - w[index]
index = index + 1
select p[index]
Then on to the next index to resample based on the probabilities (or normalized probability in the case presented in the course).
The lecture link: https://classroom.udacity.com/courses/cs373/lessons/48704330/concepts/487480820923
I am logged into Udacity with my school account so if the link does not work, it is Lesson 8, video number 21 of Artificial Intelligence for Robotics where he is lecturing on particle filters.
I recently came across this post and found some useful hints. However, I ended up using an entirely different approach which suited my needs. I am sharing the approach and my reasoning of why I chose this approach. The post is longer than I would have liked, but I believe screenshots are always helpful. Hopefully, the answer would be useful to someone.
My requirements were the following:
My Approach is as listed below:
To achieve requirements 2, 3 and 4 above, use table in Microsoft word, to insert the code snippet. Steps are listed below:
To achieve requirement 5, follow the steps below:
Please provide if you have any feedback or improvements or run into any issues with the approach.
Please look into Von Pookie's answer, all credits to him/her.
Sub asdf()
Dim ws As Worksheet, newWb As Workbook
Application.ScreenUpdating = False
For Each ws In Sheets(Array("EID Upload", "Wages with Locals Upload", "Wages without Local Upload"))
ws.Copy
Set newWb = ActiveWorkbook
With newWb
.SaveAs ws.Name, xlCSV
.Close (False)
End With
Next ws
Application.ScreenUpdating = True
End Sub
You need to set your window to be topmost.
a {
display: block;
position: relative;
}
I think that is all you need.
try yo write document.getElementById('id').style.visibility="hidden";
The "up" affordance indicator is provided by a drawable specified in the homeAsUpIndicator
attribute of the theme. To override it with your own custom version it would be something like this:
<style name="Theme.MyFancyTheme" parent="android:Theme.Holo">
<item name="android:homeAsUpIndicator">@drawable/my_fancy_up_indicator</item>
</style>
If you are supporting pre-3.0 with your application be sure you put this version of the custom theme in values-v11
or similar.
You have to use ==
to compare (or even ===
, if you want to compare types). A single =
is for assignment.
if (one == 'rock' && two == 'rock') {
console.log('Tie! Try again!');
}
Just had to deal with this scenario myself - found a really easy way to do this, simply annotate your property in the model like this:
[DataType(DataType.Date)]
public DateTime? SomeDateProperty { get; set; }
It will hide the time button from the date picker too.
Sorry if this answer is a little late ;)
I found this expression simplest
String[] extractednums = msg.split("\\\\D++");
call generateNumbers(numbers);
, your generateNumbers();
expects int[]
as an argument
ans you were passing none, thus the error
Add scrolling="no"
attribute to the iframe.
I got this when I forgot to unprotect workbook or sheet.
Here's a link to Sun's recommendations for Java. Not that you have to use these or even that their library code follows all of them, but it's a good start if you're going from scratch. Tool like Eclipse have built in formatters and cleanup tools that can help you conform to these conventions (or others that you define).
For me, '_' are too hard to type :)
Generally, make an "inverse" commit, using:
git revert 364705c
then send it to the remote as usual:
git push
This won't delete the commit: it makes an additional commit that undoes whatever the first commit did. Anything else, not really safe, especially when the changes have already been propagated.
Red Hat, Fedora:
yum -y install gcc mysql-devel ruby-devel rubygems
gem install -y mysql -- --with-mysql-config=/usr/bin/mysql_config
Debian, Ubuntu:
apt-get install libmysqlclient-dev ruby-dev
gem install mysql
Arch Linux:
pacman -S libmariadbclient
gem install mysql
Following are few options available to change Heap Size.
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
java -Xmx256m TestData.java
As mysql official documentation:
Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).
Online Documentation:
Since there's no way to just pass this "comma-separated list of varchars", I assume some other system is generating them. If you can modify your generator slightly, it should be workable. Rather than separating by commas, you separate by union all select
, and need to prepend a select
also to the list. Finally, you need to provide aliases for the table and column in you subselect:
Create Table #IMEIS(
imei varchar(15)
)
INSERT INTO #IMEIS(imei)
SELECT * FROM (select '012251000362843' union all select '012251001084784' union all select '012251001168744' union all
select '012273007269862' union all select '012291000080227' union all select '012291000383084' union all
select '012291000448515') t(Col)
SELECT * from #IMEIS
DROP TABLE #IMEIS;
But noting your comment to another answer, about having 5000 entries to add. I believe the 256 tables per select limitation may kick in with the above "union all" pattern, so you'll still need to do some splitting of these values into separate statements.
Just to modify scott's answer to make it a function:
Function FindFirstInRange(FindString As String, RngIn As Range, Optional UseCase As Boolean = True, Optional UseWhole As Boolean = True) As Variant
Dim LookAtWhat As Integer
If UseWhole Then LookAtWhat = xlWhole Else LookAtWhat = xlPart
With RngIn
Set FindFirstInRange = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=LookAtWhat, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=UseCase)
If FindFirstInRange Is Nothing Then FindFirstInRange = False
End With
End Function
This returns FALSE if the value isn't found, and if it's found, it returns the range.
You can optionally tell it to be case-sensitive, and/or to allow partial-word matches.
I took out the TRIM because you can add that beforehand if you want to.
An example:
MsgBox FindFirstInRange(StringToFind, Range("2:2"), TRUE, FALSE).Address
That does a case-sensitive, partial-word search on the 2nd row and displays a box with the address. The following is the same search, but a whole-word search that is not case-sensitive:
MsgBox FindFirstInRange(StringToFind, Range("2:2")).Address
You can easily tweak this function to your liking or change it from a Variant to to a boolean, or whatever, to speed it up a little.
Do note that VBA's Find is sometimes slower than other methods like brute-force looping or Match, so don't assume that it's the fastest just because it's native to VBA. It's more complicated and flexible, which also can make it not always as efficient. And it has some funny quirks to look out for, like the "Object variable or with block variable not set" error.
Don't write a toString()
method. This is not Java. Implement the stream operator for your class.
Prefer using the standard algorithms over writing your own loop. In this situation, std::for_each()
provides a nice interface to what you want to do.
If you must use a loop, but don't intend to change the data, prefer const_iterator
over iterator
. That way, if you accidently try and change the values, the compiler will warn you.
Then:
std::ostream& operator<<(std::ostream& str,something const& data)
{
data.print(str)
return str;
}
void something::print(std::ostream& str) const
{
std::for_each(table.begin(),table.end(),PrintData(str));
}
Then when you want to print it, just stream the object:
int main()
{
something bob;
std::cout << bob;
}
If you actually need a string representation of the object, you can then use lexical_cast
.
int main()
{
something bob;
std::string rope = boost::lexical_cast<std::string>(bob);
}
The details that need to be filled in.
class somthing
{
typedef std::map<std::string,std::string> DataMap;
struct PrintData
{
PrintData(std::ostream& str): m_str(str) {}
void operator()(DataMap::value_type const& data) const
{
m_str << data.first << "=" << data.second << "\n";
}
private: std::ostream& m_str;
};
DataMap table;
public:
void something::print(std::ostream& str);
};
One possible naming convention is to use something similar to the naming scheme jQuery uses. It's not universally adopted but it is pretty common.
product-name.plugin-ver.sion.filetype.js
where the product-name
+ plugin
pair can also represent a namespace and a module. The version
and filetype
are usually optional.
filetype
can be something relative to how the content of the file is. Often seen are:
min
for minified filescustom
for custom built or modified filesExamples:
jquery-1.4.2.min.js
jquery.plugin-0.1.js
myapp.invoice.js
Well there's a problem with the creation of the ContactServiceImpl
bean. First, make sure that the class is actually instantiated by debugging the no-args constructor when the Spring context is initiated and when an instance of ContactController
is created.
If the ContactServiceImpl
is actually instantiated by the Spring context, but it's simply not matched against your @Autowire
annotation, try being more explicit in your annotation injection. Here's a guy dealing with a similar problem as yours and giving some possible solutions:
http://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/
If you ask me, I think you'll be ok if you replace
@Autowired
private ContactService contactService;
with:
@Resource
@Qualifier("contactService")
private ContactService contactService;
Jquery has two properties called naturalWidth and naturalHeight, you can use in this way.
$('.my-img')[0].naturalWidth
$('.my-img')[0].naturalHeight
Where my-img is a class name used to select my image.
You could try this:
SELECT * INTO foo FROM foo_bk
For rails6, I was facing the same problem, as I was missing following files, once I added them, the issue resolved:
1. config/master.key
2. config/credentials.yml.enc
Make sure you have this files.!!!
Using [Authorize]
attributes can help prevent security holes in your application. The way that MVC handles URL's (i.e. routing them to a controller rather than to an actual file) makes it difficult to actually secure everything via the web.config file.
Read more here: http://blogs.msdn.com/b/rickandy/archive/2012/03/23/securing-your-asp-net-mvc-4-app-and-the-new-allowanonymous-attribute.aspx (via archive.org)
You need to use debug(@var)
. It's exactly like "print_r".
Simple method to sending data using java script and ajex call.
First right your form like this
<form id="frm_details" method="post" name="frm_details">
<input id="email" name="email" placeholder="Your Email id" type="text" />
<button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form>
javascript logic target on form id #frm_details after sumbit
$(function(){
$("#frm_details").on("submit", function(event) {
event.preventDefault();
var formData = {
'email': $('input[name=email]').val() //for get email
};
console.log(formData);
$.ajax({
url: "/tsmisc/api/subscribe-newsletter",
type: "post",
data: formData,
success: function(d) {
alert(d);
}
});
});
})
General
Request URL:https://test.abc
Request Method:POST
Status Code:200
Remote Address:13.76.33.57:443
From Data
email:[email protected]
What is the right approach for doing this?
There are a lot of "right" approaches, you just have decide which one best suites your needs. It appears as though you're misunderstanding how to use node_modules
...
If you're familiar with NuGet you should think of npm as its client-side counterpart. Where the node_modules
directory is like the bin
directory for NuGet. The idea is that this directory is just a common location for storing packages, in my opinion it is better to take a dependency
on the packages you need as you have done in the package.json
. Then use a task runner like Gulp
for example to copy the files you need into your desired wwwroot
location.
I wrote a blog post about this back in January that details npm, Gulp and a whole bunch of other details that are still relevant today. Additionally, someone called attention to my SO question I asked and ultimately answered myself here, which is probably helpful.
I created a Gist
that shows the gulpfile.js
as an example.
In your Startup.cs
it is still important to use static files:
app.UseStaticFiles();
This will ensure that your application can access what it needs.
I know this answer is so late, I have wrote this solution, Hacking Go run-time, It's not safety, It may crashes:
import (
"unsafe"
"reflect"
)
func isChanClosed(ch interface{}) bool {
if reflect.TypeOf(ch).Kind() != reflect.Chan {
panic("only channels!")
}
// get interface value pointer, from cgo_export
// typedef struct { void *t; void *v; } GoInterface;
// then get channel real pointer
cptr := *(*uintptr)(unsafe.Pointer(
unsafe.Pointer(uintptr(unsafe.Pointer(&ch)) + unsafe.Sizeof(uint(0))),
))
// this function will return true if chan.closed > 0
// see hchan on https://github.com/golang/go/blob/master/src/runtime/chan.go
// type hchan struct {
// qcount uint // total data in the queue
// dataqsiz uint // size of the circular queue
// buf unsafe.Pointer // points to an array of dataqsiz elements
// elemsize uint16
// closed uint32
// **
cptr += unsafe.Sizeof(uint(0))*2
cptr += unsafe.Sizeof(unsafe.Pointer(uintptr(0)))
cptr += unsafe.Sizeof(uint16(0))
return *(*uint32)(unsafe.Pointer(cptr)) > 0
}
I know this is an old post, but check out the Extended WPF Toolkit. It has a RichTextBox that supports what you are tryign to do.
Your problem is that you load an external image, meaning from another domain. This causes a security error when you try to access any data of your canvas context.
You can override any built-in function by just re-declaring it.
parseFloat = function(a){
alert(a)
};
Now parseFloat(3)
will alert 3.
Using furl and regex (python 3)
>>> import re
>>> import furl
>>> p = re.compile(r'(\/)+')
>>> url = furl.furl('/media/path').add(path='/js/foo.js').url
>>> url
'/media/path/js/foo.js'
>>> p.sub(r"\1", url)
'/media/path/js/foo.js'
>>> url = furl.furl('/media/path').add(path='js/foo.js').url
>>> url
'/media/path/js/foo.js'
>>> p.sub(r"\1", url)
'/media/path/js/foo.js'
>>> url = furl.furl('/media/path/').add(path='js/foo.js').url
>>> url
'/media/path/js/foo.js'
>>> p.sub(r"\1", url)
'/media/path/js/foo.js'
>>> url = furl.furl('/media///path///').add(path='//js///foo.js').url
>>> url
'/media///path/////js///foo.js'
>>> p.sub(r"\1", url)
'/media/path/js/foo.js'
I had the same problem, when I was trying to switch "C:\superfolder"
Error messages:
Directory 'C:\superfolder\subfolder\.svn' containing working copy admin area is missing Please execute the 'Cleanup' command.
After trying to do a "cleanup", I got the following error:
Cleanup failed to process the following paths: C:\superfolder\ 'C:\superfolder\subfolder\' is not a working copy directory
Solution:
this worked for me. Please let me know if it also works for you.
I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.
Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.
This doesn't work because NaN
isn't equal to anything, including NaN
. Use pd.isnull(df.var2)
instead.
xml:space="preserve"
has to work for all compliant XML parsers.
However, note that in HTML the line break is just whitespace and NOT a line break (this is represented with the <br />
(X)HTML tag, maybe this is the problem which you are facing.
You can also add
and/or
to insert CR/LF characters.
I had similar issue where local build was working fine however when I push my branch onto heroku it would fail to build. Issue was that I had some devDependencies in my package.json which were not installed during npm install which was causing my build to fail.
If you need access to packages declared under devDependencies in a different buildpack or at runtime, then you can set NPM_CONFIG_PRODUCTION=false or YARN_PRODUCTION=false
to skip the pruning step.
Also you can move you devDependencies into dependencies...
Even i was facing the issue @Roland , I had included one more attribute called
android:layout_alignParentRight="true"
in my RatingBar
declaration in XML. This attribute prevented from setting of the stars required and setting up the NumStars
Keep posted on the issues you come across !
I think df['word'].value_counts()
should serve. By skipping the groupby machinery, you'll save some time. I'm not sure why count
should be much slower than max
. Both take some time to avoid missing values. (Compare with size
.)
In any case, value_counts has been specifically optimized to handle object type, like your words, so I doubt you'll do much better than that.
First check if you are in the right database USE yourDB
and try Select * from contenttype
just to see what is it and if it exists really...
conn.exec = <<eos
select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc,
where etc etc etc etc etc etc etc etc etc etc etc etc etc
eos
You can use pandas library and reference the rows and columns like this:
import pandas as pd
input = pd.read_csv("path_to_file");
#for accessing ith row:
input.iloc[i]
#for accessing column named X
input.X
#for accessing ith row and column named X
input.iloc[i].X
Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:
SELECT employee_number,
MAX(MAX(course_completion_date))
OVER (PARTITION BY course_code) AS max_course_date,
MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code
And as Teradata allows re-using an alias this also works:
SELECT employee_number,
MAX(max_date)
OVER (PARTITION BY course_code) AS max_course_date,
MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code
Solution:
Step1: Uncomment the php_curl.dll from php.ini
Step2: Copy the following three files from php installed directory.i.e "C:\\php7".
libeay32.dll,
libssh2.dll,
ssleay32.dll
Step3: Paste the files under two place
httpd.conf's ServerRoot directive. i.e "C\Apache24"
apache bin directory. i.e "C\Apache24\bin"
Step4: Restart apache.
That's all. I solve the problem by this way.Hope it might work for you.
The solution is given here. https://abcofcomputing.blogspot.com/2017/06/php7-unable-to-load-phpcurldll.html
For me save_queries
option was turned off so,
$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;
Ref: Can't get result from $this->db->last_query(); codeigniter
Use df.assign
to create a new df. See http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
split = df_selected['name'].str.split(',', 1, expand=True)
df_split = df_selected.assign(first_name=split[0], last_name=split[1])
df_split.drop('name', 1, inplace=True)
I prefer an id descendant selector of your #form2, like this:
$("#form2 #name").val("Hello World!");
Along with forEach
method that accepts a lambda expression we have also got stream APIs, in Java 8.
Iterate over entries (Using forEach and Streams):
sample.forEach((k,v) -> System.out.println(k + "=" + v));
sample.entrySet().stream().forEachOrdered((entry) -> {
Object currentKey = entry.getKey();
Object currentValue = entry.getValue();
System.out.println(currentKey + "=" + currentValue);
});
sample.entrySet().parallelStream().forEach((entry) -> {
Object currentKey = entry.getKey();
Object currentValue = entry.getValue();
System.out.println(currentKey + "=" + currentValue);
});
The advantage with streams is they can be parallelized easily and can be useful when we have multiple CPUs at disposal. We simply need to use parallelStream()
in place of stream()
above. With parallel streams it makes more sense to use forEach
as forEachOrdered
would make no difference in performance. If we want to iterate over keys we can use sample.keySet()
and for values sample.values()
.
Why forEachOrdered
and not forEach
with streams ?
Streams also provide forEach
method but the behaviour of forEach
is explicitly nondeterministic where as the forEachOrdered
performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach
does not guarantee that the order would be kept. Also check this for more.
Adding origin=${window.location.host} or "*"
is not enough.
Add https://
before it and it will work.
Also, make sure that you are using an URL that can be embedded: take the video ID out and concatenate a string that has the YouTube video prefix and the video ID + embed definition.
Can you try to change your json without data
key like below?
[{"target_id":9503123,"target_type":"user"}]
You need to install the es2015
preset:
npm install babel-preset-es2015
and then configure babel-loader
:
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015']
}
}
You can find last character using php many ways like substr() and mb_substr().
If you’re using multibyte character encodings like UTF-8, use mb_substr instead of substr
Here i can show you both example:
<?php
echo substr("testers", -1);
echo mb_substr("testers", -1);
?>
You need to add your source files with git add
or the GUI equivalent so that Git will begin tracking them.
Use git status
to see what Git thinks about the files in any given directory.
You can do in this in Angular with ECMAScript6 by using the spread operator:
let copy = {...myObject};
Use Object.entries()
function.
Object.entries(object)
return:
[
[key, value],
[key, value],
...
]
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
{Object.entries(subjects).map(([key, subject], i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">key: {i} Name: {subject.name}</span>
</li>
))}
You could use Narrative JavaScript, a compiler that will transforms your code into a state machine, effectively allowing you to emulate threading. It does so by adding a "yielding" operator (notated as '->') to the language that allows you to write asynchronous code in a single, linear code block.
For me, this error message originated from a banner from Admob SDK.
I was able to track the origin to "WebThread" by setting a conditional breakpoint.
Then I was able to get rid of the issue by encapsulating the Banner creation with:
dispatch_async(dispatch_get_main_queue(), ^{
_bannerForTableFooter = [[GADBannerView alloc] initWithAdSize:kGADAdSizeSmartBannerPortrait];
...
}
I don't know why this helped as I cannot see how this code was called from a non-main-thread.
Hope it can help anyone.
You can create a usercontrol with the grid definition and define 'child' controls with varied column definitions in xaml. The parent needs a dependency property for columns and a method for loading the columns:
Parent:
public ObservableCollection<DataGridColumn> gridColumns
{
get
{
return (ObservableCollection<DataGridColumn>)GetValue(ColumnsProperty);
}
set
{
SetValue(ColumnsProperty, value);
}
}
public static readonly DependencyProperty ColumnsProperty =
DependencyProperty.Register("gridColumns",
typeof(ObservableCollection<DataGridColumn>),
typeof(parentControl),
new PropertyMetadata(new ObservableCollection<DataGridColumn>()));
public void LoadGrid()
{
if (gridColumns.Count > 0)
myGrid.Columns.Clear();
foreach (DataGridColumn c in gridColumns)
{
myGrid.Columns.Add(c);
}
}
Child Xaml:
<local:parentControl x:Name="deGrid">
<local:parentControl.gridColumns>
<toolkit:DataGridTextColumn Width="Auto" Header="1" Binding="{Binding Path=.}" />
<toolkit:DataGridTextColumn Width="Auto" Header="2" Binding="{Binding Path=.}" />
</local:parentControl.gridColumns>
</local:parentControl>
And finally, the tricky part is finding where to call 'LoadGrid'.
I am struggling with this but got things to work by calling after InitalizeComponent
in my window constructor (childGrid is x:name in window.xaml):
childGrid.deGrid.LoadGrid();
Try using rowMeans
:
z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)
w x y mean
1 5 1 1 1
2 6 2 2 2
3 7 3 3 3
4 8 4 NA 4
That is because IIS is automatically running on your machine. IIS occupied both port 80 and 443.
I uninstalled IIS for using Apache httpd.