-(void)showAlert{
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Title"
message:"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
[self showAlert];
// calling Method
SIGABRT means in general that there is an uncaught exception. There should be more information on the console.
The way using a Swift Extension to UIImageView
(source code here):
UIActivityIndicatorView
import Foundation
import UIKit
import ObjectiveC
private var activityIndicatorAssociationKey: UInt8 = 0
extension UIImageView {
//Associated Object as Computed Property
var activityIndicator: UIActivityIndicatorView! {
get {
return objc_getAssociatedObject(self, &activityIndicatorAssociationKey) as? UIActivityIndicatorView
}
set(newValue) {
objc_setAssociatedObject(self, &activityIndicatorAssociationKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
}
}
private func ensureActivityIndicatorIsAnimating() {
if (self.activityIndicator == nil) {
self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
self.activityIndicator.hidesWhenStopped = true
let size = self.frame.size;
self.activityIndicator.center = CGPoint(x: size.width/2, y: size.height/2);
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.addSubview(self.activityIndicator)
self.activityIndicator.startAnimating()
})
}
}
convenience init(URL: NSURL, errorImage: UIImage? = nil) {
self.init()
self.setImageFromURL(URL)
}
func setImageFromURL(URL: NSURL, errorImage: UIImage? = nil) {
self.ensureActivityIndicatorIsAnimating()
let downloadTask = NSURLSession.sharedSession().dataTaskWithURL(URL) {(data, response, error) in
if (error == nil) {
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.activityIndicator.stopAnimating()
self.image = UIImage(data: data)
})
}
else {
self.image = errorImage
}
}
downloadTask.resume()
}
}
Since this is a very popular topic and the good answers are spread all over and dealt with in great depth, I felt it is justifiable to compile the good answers from the others into a more concise form, so newcomers have an easy overview upfront:
You usually extend a class to add or modify functionality. So, if you don't want to overwrite any Thread behavior, then use Runnable.
In the same light, if you don't need to inherit thread methods, you can do without that overhead by using Runnable.
Single inheritance: If you extend Thread you cannot extend from any other class, so if that is what you need to do, you have to use Runnable.
It is good design to separate domain logic from technical means, in that sense it is better to have a Runnable task isolating your task from your runner.
You can execute the same Runnable object multiple times, a Thread object, however, can only be started once. (Maybe the reason, why Executors do accept Runnables, but not Threads.)
If you develop your task as Runnable, you have all flexibility how to use it now and in the future. You can have it run concurrently via Executors but also via Thread. And you still could also use/call it non-concurrently within the same thread just as any other ordinary type/object.
This makes it also easier to separate task-logic and concurrency aspects in your unit tests.
If you are interested in this question, you might be also interested in the difference between Callable and Runnable.
Having tried the solution suggested by Zelazny on a relatively large DataFrame (~400k rows) I found it to be very slow. Here is an alternative that I found to run orders of magnitude faster on my data set.
df = pd.DataFrame({
'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4', 'MM4'],
'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'count' : [3,2,5,8,10,1,2,2,7]
})
df_grouped = df.groupby(['sp', 'mt']).agg({'count':'max'})
df_grouped = df_grouped.reset_index()
df_grouped = df_grouped.rename(columns={'count':'count_max'})
df = pd.merge(df, df_grouped, how='left', on=['sp', 'mt'])
df = df[df['count'] == df['count_max']]
From what I understand and how I approach,
Interface is like a specification/contract, any class that implements an interface class have to implement all the methods defined in the abstract class (except default methods (introduced in Java 8))
Whereas I define a class abstract when I know the implementation required for some methods of the class and some methods I still do not know what will be the implementation (we might know the function signature but not the implementation). I do this so that later in the part of development when I know how these methods are to be implemented, I can just extend this abstract class and implement these methods.
Note: You cannot have function body in interface methods unless the method is static or default.
Just found another solutions worked for me. You can use '\' sign before your one special.
passwd=\@31\&3*J
This is working for me, Writing(creating as well) and/or appending content in the same mode.
$fp = fopen("MyFile.txt", "a+")
To dismiss or cancel AlertDialog.Builder
dialog.setNegativeButton("?????", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
you call dismiss() on the dialog interface
Already answered but I'd like to add a bit more on the topic and different ways to do it depending on your use case.
You can add adjustsFontSizeToFit={true}
(currently undocumented) to Text
Component to auto adjust the size inside a parent node.
<Text adjustsFontSizeToFit={true} numberOfLines={1}>Hiiiz</Text>
You can also add the following in your Text Component:
<Text style={{textAlignVertical: "center",textAlign: "center",}}>Hiiiz</Text>
Or you can add the following into the parent of the Text component:
<View style={{flex:1,justifyContent: "center",alignItems: "center"}}>
<Text>Hiiiz</Text>
</View>
or both
<View style={{flex:1,justifyContent: "center",alignItems: "center"}}>
<Text style={{textAlignVertical: "center",textAlign: "center",}}>Hiiiz</Text>
</View>
or all three
<View style={{flex:1,justifyContent: "center",alignItems: "center"}}>
<Text adjustsFontSizeToFit={true}
numberOfLines={1}
style={{textAlignVertical: "center",textAlign: "center",}}>Hiiiz</Text>
</View>
It all depends on what you're doing. You can also checkout my full blog post on the topic
Basically you can create a regex to fulfil your needs and then assign that pattern to your input field.
Or for a more direct approach:
<input type="number" require ng-pattern="<your regex here>">
More info @ angular docs here and here (built-in validators)
In my case I was missing new
inside the type definition.
some-js-component.d.ts
file:
import * as React from "react";
export default class SomeJSXComponent extends React.Component<any, any> {
new (props: any, context?: any)
}
and inside the tsx
file where I was trying to import the untyped component:
import SomeJSXComponent from 'some-js-component'
const NewComp = ({ asdf }: NewProps) => <SomeJSXComponent withProps={asdf} />
Thanks everyone who helped. After doing some research myself (I'm the guy who asked the question), here is what I found to make sense most:
Database column type: the timezone-agnostic number of milliseconds since 1970 represented as decimal(20)
because 2^64 has 20 digits and disk space is cheap; let's be straightforward. Also, I will use neither DEFAULT CURRENT_TIMESTAMP
, nor triggers. I want no magic in the DB.
Java field type: long
. The Unix timestamp is well supported across various libs, long
has no Y2038 problems, timestamp arithmetic is fast and easy (mainly operator <
and operator +
, assuming no days/months/years are involved in the calculations). And, most importantly, both primitive long
s and java.lang.Long
s are immutable—effectively passed by value—unlike java.util.Date
s; I'd be really pissed off to find something like foo.getLastUpdate().setTime(System.currentTimeMillis())
when debugging somebody else's code.
The ORM framework should be responsible for filling in the data automatically.
I haven't tested this yet, but only looking at the docs I assume that @Temporal
will do the job; not sure about whether I might use @Version
for this purpose. @PrePersist
and @PreUpdate
are good alternatives to control that manually. Adding that to the layer supertype (common base class) for all entities, is a cute idea provided that you really want timestamping for all of your entities.
The easiest way to tweak this in my opinion (imho) is to edit the .git/config file in your repository. Look for the entry you messed up and just tweak the URL.
On my machine in a repo I regularly use it looks like this:
KidA% cat .git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
autocflg = true
[remote "origin"]
url = ssh://localhost:8888/opt/local/var/git/project.git
#url = ssh://xxx.xxx.xxx.xxx:80/opt/local/var/git/project.git
fetch = +refs/heads/*:refs/remotes/origin/*
The line you see commented out is an alternative address for the repository that I sometimes switch to simply by changing which line is commented out.
This is the file that is getting manipulated under-the-hood when you run something like git remote rm
or git remote add
but in this case since its only a typo you made it might make sense to correct it this way.
Here are two quickie approaches I know of:
In base
AQ1 <- airquality
AQ1[is.na(AQ1 <- airquality)] <- 0
AQ1
Not in base
library(qdap)
NAer(airquality)
PS P.S. Does my command above create a new dataframe called AQ1?
Look at AQ1 and see
I have a very quick and simple workaround here, it does work for me, and no matter the event would be triggered once or twice or more times occasionally, check it out:
private int fireCount = 0;
private void inputFileWatcher_Changed(object sender, FileSystemEventArgs e)
{
fireCount++;
if (fireCount == 1)
{
MessageBox.Show("Fired only once!!");
dowork();
}
else
{
fireCount = 0;
}
}
}
This method work when you are using a class: In this example you will receive a array, so the only method that worked for me was these one:
template <typename T, size_t n, size_t m>
Matrix& operator= (T (&a)[n][m])
{
int arows = n;
int acols = m;
p = new double*[arows];
for (register int r = 0; r < arows; r++)
{
p[r] = new double[acols];
for (register int c = 0; c < acols; c++)
{
p[r][c] = a[r][c]; //A[rows][columns]
}
}
https://www.geeksforgeeks.org/how-to-print-size-of-an-array-in-a-function-in-c/
You can also lock your subscribers dictionary to prevent it from being modified whenever its being looped:
lock (subscribers)
{
foreach (var subscriber in subscribers)
{
//do something
}
}
You can just call the Execute command.
EXEC spDoSomthing @myDate
Edit:
Since you want to return data..that's a little harder. You can use user defined functions instead that return data.
This is not stated in the documentation, but to clear the opcode cache you must do:
apc_clear_cache('opcode');
EDIT: This seems to only apply to some older versions of APC..
No matter what version you are using you can't clear mod_php or fastcgi APC cache from a php cli script since the cli script will run from a different process as mod_php or fastcgi. You must call apc_clear_cache() from within the process (or child process) which you want to clear the cache for. Using curl to run a simple php script is one such approach.
You need to access the dataset
property:
document.getElementById("the-span").addEventListener("click", function() {
var json = JSON.stringify({
id: parseInt(this.dataset.typeid),
subject: this.dataset.type,
points: parseInt(this.dataset.points),
user: "Luïs"
});
});
Result:
// json would equal:
{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }
<asp:GridView ID="GridView1" runat="server" PageSize="2" AutoGenerateColumns="false"
AllowPaging="true" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
BorderWidth="1px" CellPadding="4" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowDeleting="GridView1_RowDeleting">
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<RowStyle BackColor="White" ForeColor="#330099" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
<Columns>
<asp:TemplateField HeaderText="SerialNo">
<ItemTemplate>
<%# Container .DataItemIndex+1 %>. 
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RollNo">
<ItemTemplate>
<%--<asp:Label ID="lblrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:Label>--%>
<asp:TextBox ID="txtrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SName">
<ItemTemplate>
<%--<asp:Label ID="lblsname" runat="server" Text='<%#Eval("SName")%>'></asp:Label>--%>
<asp:TextBox ID="txtsname" runat="server" Text='<%#Eval("SName")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="C">
<ItemTemplate>
<%-- <asp:Label ID="lblc" runat="server" Text='<%#Eval ("C") %>'></asp:Label>--%>
<asp:TextBox ID="txtc" runat="server" Text='<%#Eval ("C") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cpp">
<ItemTemplate>
<%-- <asp:Label ID="lblcpp" runat="server" Text='<%#Eval ("Cpp")%>'></asp:Label>--%>
<asp:TextBox ID="txtcpp" runat="server" Text='<%#Eval ("Cpp")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Java">
<ItemTemplate>
<%-- <asp:Label ID="lbljava" runat="server" Text='<%#Eval ("Java")%>'> </asp:Label>--%>
<asp:TextBox ID="txtjava" runat="server" Text='<%#Eval ("Java")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lnkbtnUpdate" runat="server" CausesValidation="true" Text="Update"
CommandName="Update"></asp:LinkButton>
<asp:LinkButton ID="lnkbtnCancel" runat="server" CausesValidation="false" Text="Cancel"
CommandName="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" CausesValidation="false" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
<asp:CommandField HeaderText="Select" ShowSelectButton="True" ShowHeader="True" />
</Columns>
</asp:GridView>
<table>
<tr>
<td>
<asp:Label ID="lblrollno" runat="server" Text="RollNo"></asp:Label>
<asp:TextBox ID="txtrollno" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblsname" runat="server" Text="SName"></asp:Label>
<asp:TextBox ID="txtsname" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblc" runat="server" Text="C"></asp:Label>
<asp:TextBox ID="txtc" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblcpp" runat="server" Text="Cpp"></asp:Label>
<asp:TextBox ID="txtcpp" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lbljava" runat="server" Text="Java"></asp:Label>
<asp:TextBox ID="txtjava" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click" />
<asp:Button ID="Reset" runat="server" Text="Reset" OnClick="Reset_Click" />
</td>
</tr>
</table>
If you open the DMP file with an editor that can handle big files, you might be able to locate the areas where the schema names are mentioned. Just be sure not to change anything. It would be better if you opened a copy of the original dump.
I was facing the same issue on WAMP. Locate the connectors available with pip command. You can run this from any prompt if Python ENV variables are properly set.
pip search mysql-connector
mysql-connector (2.2.9) - MySQL driver written in Python
bottle-mysql-connector (0.0.4) - MySQL integration for Bottle.
mysql-connector-python (8.0.15) - MySQL driver written in Python
mysql-connector-repackaged (0.3.1) - MySQL driver written in Python
mysql-connector-async-dd (2.0.2) - mysql async connection
Run the following command to install mysql-connector
C:\Users\Admin>pip install mysql-connector
verify the installation
C:\Users\Admin>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
>>>
This solution worked for me.
There are two ways you could simplify your work. 1. import Gson library. 2. use Lombok.
Both of them help you create String from object instance. Gson will parse your object, lombok will override your class object toString method.
I put an example about Gson prettyPrint, I create helper class to print object and collection of objects. If you are using lombok, you could mark your class as @ToString and print your object directly.
@Scope(value = "prototype")
@Component
public class DebugPrint<T> {
public String PrettyPrint(T obj){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(obj);
}
public String PrettyPrint(Collection<T> list){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return list.stream().map(gson::toJson).collect(Collectors.joining(","));
}
}
Take the following folder structure
notice:
Now in the index.html.en
file you'll want to put the following markup
<p>
<span>src="check_mark.png"</span>
<img src="check_mark.png" />
<span>I'm purple because I'm referenced from this current directory</span>
</p>
<p>
<span>src="/check_mark.png"</span>
<img src="/check_mark.png" />
<span>I'm green because I'm referenced from the ROOT directory</span>
</p>
<p>
<span>src="subfolder/check_mark.png"</span>
<img src="subfolder/check_mark.png" />
<span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>
<p>
<span>src="/subfolder/check_mark.png"</span>
<img src="/subfolder/check_mark.png" />
<span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>
<p>
<span>src="../subfolder/check_mark.png"</span>
<img src="../subfolder/check_mark.png" />
<span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>
<p>
<span>src="subfolder/subfolder/check_mark.png"</span>
<img src="subfolder/subfolder/check_mark.png" />
<span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>
<p>
<span>src="/subfolder/subfolder/check_mark.png"</span>
<img src="/subfolder/subfolder/check_mark.png" />
<span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>
Now if you load up the index.html.en
file located in the second subfolder
http://example.com/subfolder/subfolder/
This will be your output
You need to use Integer.parseInt(String)
private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getSource()==jTextField2){
int jml = Integer.parseInt(jTextField3.getText());
jTextField1.setText(numberToWord(jml));
}
}
Here is a working code snippet that will print out the full version of currently running Eclipse (or any RCP-based application).
String product = System.getProperty("eclipse.product");
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint point = registry.getExtensionPoint("org.eclipse.core.runtime.products");
Logger log = LoggerFactory.getLogger(getClass());
if (point != null) {
IExtension[] extensions = point.getExtensions();
for (IExtension ext : extensions) {
if (product.equals(ext.getUniqueIdentifier())) {
IContributor contributor = ext.getContributor();
if (contributor != null) {
Bundle bundle = Platform.getBundle(contributor.getName());
if (bundle != null) {
System.out.println("bundle version: " + bundle.getVersion());
}
}
}
}
}
It looks up the currently running "product" extension and takes the version of contributing plugin.
On Eclipse Luna 4.4.0, it gives the result of 4.4.0.20140612-0500
which is correct.
Add produces = "application/json"
in @RequestMapping
To select the 2nd option
$('#your-select-box-id :nth-child(2)').prop('selected', true);
Here we add the `trigger('change') to make the event fire.
$('#your-select-box-id :nth-child(2)').prop('selected', true).trigger('change');
You shouldn't have to care that much. RFC 3339, according to itself, is a set of standards derived from ISO 8601. There's quite a few minute differences though, and they're all outlined in RFC 3339. I could go through them all here, but you'd probably do better just reading the document for yourself in the event you're worried:
The Provider piece must be Provider=Microsoft.ACE.OLEDB.12.0
if your target database is ACCDB format. Provider=Microsoft.Jet.OLEDB.4.0
only works for the older MDB format.
You shouldn't even need Access installed if you're running 32 bit Windows. Jet 4 is included as part of the operating system. If you're using 64 bit Windows, Jet 4 is not included, but you still wouldn't need Access itself installed. You can install the Microsoft Access Database Engine 2010 Redistributable. Make sure to download the matching version (AccessDatabaseEngine.exe for 32 bit Windows, or AccessDatabaseEngine_x64.exe for 64 bit).
You can avoid the issue about which ADO version reference by using late binding, which doesn't require any reference.
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Then assign your ConnectionString property to the conn object. Here is a quick example which runs from a code module in Excel 2003 and displays a message box with the row count for MyTable. It uses late binding for the ADO connection and recordset objects, so doesn't require setting a reference.
Public Sub foo()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Access\webforums\whiteboard2003.mdb"
strSql = "SELECT Count(*) FROM MyTable;"
cn.Open strConnection
Set rs = cn.Execute(strSql)
MsgBox rs.fields(0) & " rows in MyTable"
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
If this answer doesn't resolve the problem, edit your question to show us the full connection string you're trying to use and the exact error message you get in response for that connection string.
Well, it's not a single statement, but it's about as close as you can get with oracle:
BEGIN
FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
END LOOP;
END;
You can specify the interpretation order of the axes using the order
parameter:
np.reshape(arr, (2, -1), order='F')
if myfile.closed == False:
print("File is still open ################")
I usually use float: left;
and add overflow: auto;
to solve the collapsing parent problem (as to why this works, overflow: auto
will expand the parent instead of adding scrollbars if you do not give it explicit height, overflow: hidden
works as well). Most of the vertical alignment needs I had are for one-line of text in menu bars, which can be solved using line-height
property. If I really need to vertical align a block element, I'd set an explicit height on the parent and the vertically aligned item, position absolute, top 50%, and negative margin.
The reason I don't use display: table-cell
is the way it overflows when you have more items than the site's width can handle. table-cell will force the user to scroll horizontally, while floats will wrap the overflow menu, making it still usable without the need for horizontal scrolling.
The best thing about float: left and overflow: auto is that it works all the way back to IE6 without hacks, probably even further.
Other solution is:
public static T Deserialize<T>(string rawXml)
{
using (XmlReader reader = XmlReader.Create(new StringReader(rawXml)))
{
DataContractSerializer formatter0 =
new DataContractSerializer(typeof(T));
return (T)formatter0.ReadObject(reader);
}
}
One remark: sometimes it happens that raw xml contains e.g.:
<?xml version="1.0" encoding="utf-16"?>
then of course you can't use UTF8 encoding used in other examples..
This should be a comment, but comments don't allow multi-line code.
Here's what's happening:
in Event.cpp
#include "Event.h"
preprocessor starts processing Event.h
#ifndef EVENT_H_
it isn't defined yet, so keep going
#define EVENT_H_
#include "common.h"
common.h
gets processed ok
#include "Item.h"
Item.h
gets processed ok
#include "Flight.h"
Flight.h
gets processed ok
#include "Landing.h"
preprocessor starts processing Landing.h
#ifndef LANDING_H_
not defined yet, keep going
#define LANDING_H_
#include "Event.h"
preprocessor starts processing Event.h
#ifndef EVENT_H_
This IS defined already, the whole rest of the file gets skipped. Continuing with Landing.h
class Landing: public Event {
The preprocessor doesn't care about this, but the compiler goes "WTH is Event
? I haven't heard about Event
yet."
Assuming these were datetime columns (if they're not apply to_datetime
) you can just subtract them:
df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])
In [11]: df.dtypes # if already datetime64 you don't need to use to_datetime
Out[11]:
A datetime64[ns]
B datetime64[ns]
dtype: object
In [12]: df['A'] - df['B']
Out[12]:
one -58 days
two -26 days
dtype: timedelta64[ns]
In [13]: df['C'] = df['A'] - df['B']
In [14]: df
Out[14]:
A B C
one 2014-01-01 2014-02-28 -58 days
two 2014-02-03 2014-03-01 -26 days
Note: ensure you're using a new of pandas (e.g. 0.13.1), this may not work in older versions.
If some of you, like me, encounter orientation problems I have combined the solutions here with a exif orientation fix
https://gist.github.com/SagiMedina/f00a57de4e211456225d3114fd10b0d0
I solved it simply by removing the domain from the request url.
Before: https://some.domain.com/_vti_bin/service.svc
After: /_vti_bin/service.svc
You can use CSS hover in combination with an image background.
CSS
.image
{
background:url(images/back.png);
height:100px;
width:100px;
display: block;
float:left;
}
.image a {
display: none;
}
.image a:hover {
display: block;
}
HTML
<div class="image"><a href="#">Text you want on mouseover</a></div>
Other methods were mentioned so let us please acknowledge that, at the time of writing, we are in the 21st century. Let's park the local bus browser opening, and fly with an XMLHTTP GET request (XHR GET for short).
XHR is an API in the form of an object whose methods transfer data between a web browser and a web server. The object is provided by the browser's JavaScript environment
It's a fast method for retrieving data that doesn't require opening a browser. The server response can be read into an HTMLDocument and the process of grabbing the table continued from there.
Note that javascript rendered/dynamically added content will not be retrieved as there is no javascript engine running (which there is in a browser).
In the below code, the table is grabbed by its id cr1
.
In the helper sub, WriteTable
, we loop the columns (td
tags) and then the table rows (tr
tags), and finally traverse the length of each table row, table cell by table cell. As we only want data from columns 1 and 8, a Select Case
statement is used specify what is written out to the sheet.
Sample webpage view:
Sample code output:
VBA:
Option Explicit
Public Sub GetRates()
Dim html As HTMLDocument, hTable As HTMLTable '<== Tools > References > Microsoft HTML Object Library
Set html = New HTMLDocument
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://uk.investing.com/rates-bonds/financial-futures", False
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" 'to deal with potential caching
.send
html.body.innerHTML = .responseText
End With
Application.ScreenUpdating = False
Set hTable = html.getElementById("cr1")
WriteTable hTable, 1, ThisWorkbook.Worksheets("Sheet1")
Application.ScreenUpdating = True
End Sub
Public Sub WriteTable(ByVal hTable As HTMLTable, Optional ByVal startRow As Long = 1, Optional ByVal ws As Worksheet)
Dim tSection As Object, tRow As Object, tCell As Object, tr As Object, td As Object, r As Long, C As Long, tBody As Object
r = startRow: If ws Is Nothing Then Set ws = ActiveSheet
With ws
Dim headers As Object, header As Object, columnCounter As Long
Set headers = hTable.getElementsByTagName("th")
For Each header In headers
columnCounter = columnCounter + 1
Select Case columnCounter
Case 2
.Cells(startRow, 1) = header.innerText
Case 8
.Cells(startRow, 2) = header.innerText
End Select
Next header
startRow = startRow + 1
Set tBody = hTable.getElementsByTagName("tbody")
For Each tSection In tBody
Set tRow = tSection.getElementsByTagName("tr")
For Each tr In tRow
r = r + 1
Set tCell = tr.getElementsByTagName("td")
C = 1
For Each td In tCell
Select Case C
Case 2
.Cells(r, 1).Value = td.innerText
Case 8
.Cells(r, 2).Value = td.innerText
End Select
C = C + 1
Next td
Next tr
Next tSection
End With
End Sub
Write it as below
<script language="javascript">
var visitorName = 'Chuck';
var myOldString = 'Hello username. I hope you enjoy your stay username.';
var myNewString = myOldString.replace('username', visitorName);
document.write('Old String = ' + myOldString);
document.write('<br/>New string = ' + myNewString);
</script>
Even better approach without flash or any other requirements is clipboard.js. All you need to do is add data-clipboard-target="#toCopyElement"
on any button, initialize it new Clipboard('.btn');
and it will copy the content of DOM with id toCopyElement
to clipboard. This is a snippet that copy the text provided in your question via a link.
One limitation though is that it does not work on safari, but it works on all other browser including mobile browsers as it does not use flash
$(function(){_x000D_
new Clipboard('.copy-text');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>_x000D_
_x000D_
<p id="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>_x000D_
_x000D_
<a class="copy-text" data-clipboard-target="#content" href="#">copy Text</a>
_x000D_
Very often you have no option to setup the sending server so what I did I changed the XMLHttpRequest.open call in my javascript to a local get-file.php file where I have the following code in it:
<?php_x000D_
$file = file($_GET['url']);_x000D_
echo implode('', $file);_x000D_
?>
_x000D_
javascript is doing this:
var xhttp = new XMLHttpRequest();_x000D_
xhttp.onreadystatechange = function() {_x000D_
if (this.readyState == 4 && this.status == 200) {_x000D_
// File content is now in the this.responseText_x000D_
}_x000D_
};_x000D_
xhttp.open("GET", "get-file.php?url=http://site/file", true);_x000D_
xhttp.send();
_x000D_
In my case this solved the restriction/situation just perfectly. No need to hack Firefox or servers. Just load your javascript/html file with that small php file into the server and you're done.
There are two operators for type testing: E is T
tests for E an instance of type T while E is! T
tests for E not an instance of type T.
Note that E is Object
is always true, and null is T
is always false unless T===Object
.
There are so many answers here, but if you're trying to change the jks password on a Mac in Android Studio. Here are the easiest steps I could find
1) Open Terminal and cd to where your .jks is located
2) keytool -storepasswd -new NEWPASSWORD -keystore YOURKEYSTORE.jks
3) enter your current password
Like @Nycen I also got this error because of a link to Cloudfare. Mine was for the Select2 plugin.
to fix it I just removed
src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"
and the error went away.
The environment variables of a process exist at runtime, and are not stored in some file or so. They are stored in the process's own memory (that's where they are found to pass on to children). But there is a virtual file in
/proc/pid/environ
This file shows all the environment variables that were passed when calling the process (unless the process overwrote that part of its memory — most programs don't). The kernel makes them visible through that virtual file. One can list them. For example to view the variables of process 3940, one can do
cat /proc/3940/environ | tr '\0' '\n'
Each variable is delimited by a binary zero from the next one. tr replaces the zero into a newline.
dt.Columns[0].DataType.Name.ToString()
Alternatively you could use minio-js client library get-object.js
var Minio = require('minio')
var s3Client = new Minio({
endPoint: 's3.amazonaws.com',
accessKey: 'YOUR-ACCESSKEYID',
secretKey: 'YOUR-SECRETACCESSKEY'
})
var size = 0
// Get a full object.
s3Client.getObject('my-bucketname', 'my-objectname', function(e, dataStream) {
if (e) {
return console.log(e)
}
dataStream.on('data', function(chunk) {
size += chunk.length
})
dataStream.on('end', function() {
console.log("End. Total size = " + size)
})
dataStream.on('error', function(e) {
console.log(e)
})
})
Disclaimer: I work for Minio Its open source, S3 compatible object storage written in golang with client libraries available in Java, Python, Js, golang.
do like this:
departments: string[]=[];
if(this.departments.indexOf(this.departmentName.trim()) >-1 ){
return;
}
Calculating RecyclerView
's height manually is not good, better is to use a custom LayoutManager
.
The reason for above issue is any view which has it's scroll(ListView
, GridView
, RecyclerView
) failed to calculate it's height when add as a child in another view has scroll. So overriding its onMeasure
method will solve the issue.
Please replace the default layout manager with the below:
public class MyLinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {
private static boolean canMakeInsetsDirty = true;
private static Field insetsDirtyField = null;
private static final int CHILD_WIDTH = 0;
private static final int CHILD_HEIGHT = 1;
private static final int DEFAULT_CHILD_SIZE = 100;
private final int[] childDimensions = new int[2];
private final RecyclerView view;
private int childSize = DEFAULT_CHILD_SIZE;
private boolean hasChildSize;
private int overScrollMode = ViewCompat.OVER_SCROLL_ALWAYS;
private final Rect tmpRect = new Rect();
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(Context context) {
super(context);
this.view = null;
}
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
this.view = null;
}
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(RecyclerView view) {
super(view.getContext());
this.view = view;
this.overScrollMode = ViewCompat.getOverScrollMode(view);
}
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(RecyclerView view, int orientation, boolean reverseLayout) {
super(view.getContext(), orientation, reverseLayout);
this.view = view;
this.overScrollMode = ViewCompat.getOverScrollMode(view);
}
public void setOverScrollMode(int overScrollMode) {
if (overScrollMode < ViewCompat.OVER_SCROLL_ALWAYS || overScrollMode > ViewCompat.OVER_SCROLL_NEVER)
throw new IllegalArgumentException("Unknown overscroll mode: " + overScrollMode);
if (this.view == null) throw new IllegalStateException("view == null");
this.overScrollMode = overScrollMode;
ViewCompat.setOverScrollMode(view, overScrollMode);
}
public static int makeUnspecifiedSpec() {
return View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
}
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
final boolean hasWidthSize = widthMode != View.MeasureSpec.UNSPECIFIED;
final boolean hasHeightSize = heightMode != View.MeasureSpec.UNSPECIFIED;
final boolean exactWidth = widthMode == View.MeasureSpec.EXACTLY;
final boolean exactHeight = heightMode == View.MeasureSpec.EXACTLY;
final int unspecified = makeUnspecifiedSpec();
if (exactWidth && exactHeight) {
// in case of exact calculations for both dimensions let's use default "onMeasure" implementation
super.onMeasure(recycler, state, widthSpec, heightSpec);
return;
}
final boolean vertical = getOrientation() == VERTICAL;
initChildDimensions(widthSize, heightSize, vertical);
int width = 0;
int height = 0;
// it's possible to get scrap views in recycler which are bound to old (invalid) adapter entities. This
// happens because their invalidation happens after "onMeasure" method. As a workaround let's clear the
// recycler now (it should not cause any performance issues while scrolling as "onMeasure" is never
// called whiles scrolling)
recycler.clear();
final int stateItemCount = state.getItemCount();
final int adapterItemCount = getItemCount();
// adapter always contains actual data while state might contain old data (f.e. data before the animation is
// done). As we want to measure the view with actual data we must use data from the adapter and not from the
// state
for (int i = 0; i < adapterItemCount; i++) {
if (vertical) {
if (!hasChildSize) {
if (i < stateItemCount) {
// we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
// we will use previously calculated dimensions
measureChild(recycler, i, widthSize, unspecified, childDimensions);
} else {
logMeasureWarning(i);
}
}
height += childDimensions[CHILD_HEIGHT];
if (i == 0) {
width = childDimensions[CHILD_WIDTH];
}
if (hasHeightSize && height >= heightSize) {
break;
}
} else {
if (!hasChildSize) {
if (i < stateItemCount) {
// we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
// we will use previously calculated dimensions
measureChild(recycler, i, unspecified, heightSize, childDimensions);
} else {
logMeasureWarning(i);
}
}
width += childDimensions[CHILD_WIDTH];
if (i == 0) {
height = childDimensions[CHILD_HEIGHT];
}
if (hasWidthSize && width >= widthSize) {
break;
}
}
}
if (exactWidth) {
width = widthSize;
} else {
width += getPaddingLeft() + getPaddingRight();
if (hasWidthSize) {
width = Math.min(width, widthSize);
}
}
if (exactHeight) {
height = heightSize;
} else {
height += getPaddingTop() + getPaddingBottom();
if (hasHeightSize) {
height = Math.min(height, heightSize);
}
}
setMeasuredDimension(width, height);
if (view != null && overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS) {
final boolean fit = (vertical && (!hasHeightSize || height < heightSize))
|| (!vertical && (!hasWidthSize || width < widthSize));
ViewCompat.setOverScrollMode(view, fit ? ViewCompat.OVER_SCROLL_NEVER : ViewCompat.OVER_SCROLL_ALWAYS);
}
}
private void logMeasureWarning(int child) {
if (BuildConfig.DEBUG) {
Log.w("MyLinearLayoutManager", "Can't measure child #" + child + ", previously used dimensions will be reused." +
"To remove this message either use #setChildSize() method or don't run RecyclerView animations");
}
}
private void initChildDimensions(int width, int height, boolean vertical) {
if (childDimensions[CHILD_WIDTH] != 0 || childDimensions[CHILD_HEIGHT] != 0) {
// already initialized, skipping
return;
}
if (vertical) {
childDimensions[CHILD_WIDTH] = width;
childDimensions[CHILD_HEIGHT] = childSize;
} else {
childDimensions[CHILD_WIDTH] = childSize;
childDimensions[CHILD_HEIGHT] = height;
}
}
@Override
public void setOrientation(int orientation) {
// might be called before the constructor of this class is called
//noinspection ConstantConditions
if (childDimensions != null) {
if (getOrientation() != orientation) {
childDimensions[CHILD_WIDTH] = 0;
childDimensions[CHILD_HEIGHT] = 0;
}
}
super.setOrientation(orientation);
}
public void clearChildSize() {
hasChildSize = false;
setChildSize(DEFAULT_CHILD_SIZE);
}
public void setChildSize(int childSize) {
hasChildSize = true;
if (this.childSize != childSize) {
this.childSize = childSize;
requestLayout();
}
}
private void measureChild(RecyclerView.Recycler recycler, int position, int widthSize, int heightSize, int[] dimensions) {
final View child;
try {
child = recycler.getViewForPosition(position);
} catch (IndexOutOfBoundsException e) {
if (BuildConfig.DEBUG) {
Log.w("MyLinearLayoutManager", "MyLinearLayoutManager doesn't work well with animations. Consider switching them off", e);
}
return;
}
final RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) child.getLayoutParams();
final int hPadding = getPaddingLeft() + getPaddingRight();
final int vPadding = getPaddingTop() + getPaddingBottom();
final int hMargin = p.leftMargin + p.rightMargin;
final int vMargin = p.topMargin + p.bottomMargin;
// we must make insets dirty in order calculateItemDecorationsForChild to work
makeInsetsDirty(p);
// this method should be called before any getXxxDecorationXxx() methods
calculateItemDecorationsForChild(child, tmpRect);
final int hDecoration = getRightDecorationWidth(child) + getLeftDecorationWidth(child);
final int vDecoration = getTopDecorationHeight(child) + getBottomDecorationHeight(child);
final int childWidthSpec = getChildMeasureSpec(widthSize, hPadding + hMargin + hDecoration, p.width, canScrollHorizontally());
final int childHeightSpec = getChildMeasureSpec(heightSize, vPadding + vMargin + vDecoration, p.height, canScrollVertically());
child.measure(childWidthSpec, childHeightSpec);
dimensions[CHILD_WIDTH] = getDecoratedMeasuredWidth(child) + p.leftMargin + p.rightMargin;
dimensions[CHILD_HEIGHT] = getDecoratedMeasuredHeight(child) + p.bottomMargin + p.topMargin;
// as view is recycled let's not keep old measured values
makeInsetsDirty(p);
recycler.recycleView(child);
}
private static void makeInsetsDirty(RecyclerView.LayoutParams p) {
if (!canMakeInsetsDirty) {
return;
}
try {
if (insetsDirtyField == null) {
insetsDirtyField = RecyclerView.LayoutParams.class.getDeclaredField("mInsetsDirty");
insetsDirtyField.setAccessible(true);
}
insetsDirtyField.set(p, true);
} catch (NoSuchFieldException e) {
onMakeInsertDirtyFailed();
} catch (IllegalAccessException e) {
onMakeInsertDirtyFailed();
}
}
private static void onMakeInsertDirtyFailed() {
canMakeInsetsDirty = false;
if (BuildConfig.DEBUG) {
Log.w("MyLinearLayoutManager", "Can't make LayoutParams insets dirty, decorations measurements might be incorrect");
}
}
}
#include<stdio.h>
int main()
{
int arr[]={10,20,30,40,50,60};
int *p;
int count=0;
for(p=arr;p<&arr+1;p++)
count++;
printf("The no of elements in array=%d",count);
return 0;
}
OUTPUT=6
EXPLANATION
p
is a pointer to a 1-D array, and in the loop for(p=arr,p<&arr+1;p++)
I made p
point to the base address. Suppose its base address is 1000; if we increment p
then it points to 1002 and so on. Now coming to the concept of &arr
- It basically represents the whole array, and if we add 1 to the whole array i.e. &arr+1
, it gives the address 1012 i.e. the address of next 1-D array (in our case the size of int is 2), so the condition becomes 1000<1012.
So, basically the condition becomes
for(p=1000;p<1012;p++)
And now let's check the condition and count the value
p=1000
and p<1012
condition is true
: enter in the loop, increment the value of count
to 1.p=1002
and p<1012
condition is true
: enter in the loop, increment the value of count
to 2.p=1010
and p<1012
condition is true
: enter in the loop, increment the value of count
to 6.p=1012
and p<1012
condition is false: print the value of count=6
in printf
statement.Your Javascript:
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "Your Rest URL Here", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
}
Your Button action::
<button type="submit" onclick="UserAction()">Search</button>
For more info go through the following link (Updated 2017/01/11)
If you are not required to use Apple's look and feel, a simple fix is to put the following code in your application or applet, before you add any GUI components to your JFrame or JApplet:
try {
UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
} catch (Exception e) {
e.printStackTrace();
}
That will set the look and feel to the cross-platform look and feel, and the setBackground() method will then work to change a JButton's background color.
If your stack trace looks like following then you are sending a huge load of json objects to server
Operation is not valid due to the current state of the object.
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
at Failing.Page_Load(Object sender, EventArgs e)
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
For resolution, please update your web config with following key. If you are not able to get the stack trace then please use fiddler. If it still does not help then please try increasing the number to 10000 or something
<configuration>
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
</configuration>
For more details, please read this Microsoft kb article
Here is a simple and backward compatible way to deliver ripple effect to raised buttons with the custom background.
Your layout should look like this
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/my_custom_background"
android:foreground="?android:attr/selectableItemBackground"/>
To disable CSRF for class based views the following worked for me.
Using django 1.10 and python 3.5.2
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
@method_decorator(csrf_exempt, name='dispatch')
class TestView(View):
def post(self, request, *args, **kwargs):
return HttpResponse('Hello world')
If you have multiple files and you don't want to have to type each file, I would recommend that you follow these simple steps (I am using clang-3.8
but you can use any other version):
generate all .ll
files
clang-3.8 -S -emit-llvm *.c
link them into a single one
llvm-link-3.8 -S -v -o single.ll *.ll
(Optional) Optimise your code (maybe some alias analysis)
opt-3.8 -S -O3 -aa -basicaaa -tbaa -licm single.ll -o optimised.ll
Generate assembly (generates a optimised.s
file)
llc-3.8 optimised.ll
Create executable (named a.out
)
clang-3.8 optimised.s
Both the Vars() and dict methods will work for the example the OP posted, but they won't work for "loosely" defined objects like:
class foo:
a = 'foo'
b = 'bar'
To print all non-callable attributes, you can use the following function:
def printVars(object):
for i in [v for v in dir(object) if not callable(getattr(object,v))]:
print '\n%s:' % i
exec('print object.%s\n\n') % i
Python 3 includes an improved super() which allows use like this:
super().__init__(args)
Checks for errors:
Dim result As String = str
If str.Length > 5 Then
result = str.Substring(str.Length - 5)
End If
System.Environment.NewLine
is the constant you are looking for - http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx which will provide environment specific combination that most programs on given OS will consider "next line of text".
In practice most of the text tools treat all variations that include \n
as "new line" and you can just use it in your text "foo\nbar"
. Especially if you are trying to construct multi-line format strings like $"V1 = {value1}\nV2 = {value2}\n"
. If you are building text with string concatenation consider using NewLine
. In any case make sure tools you are using understand output the way you want and you may need for example always use \r\n
irrespective of platform if editor of your choice can't correctly open files otherwise.
Note that WriteLine
methods use NewLine
so if you plan to write text with one these methods avoid using just \n
as resulting text may contain mix of \r\n
and just \n
which may confuse some tools and definitely does not look neat.
For historical background see Difference between \n and \r?
SmtpClient MyMail = new SmtpClient();
MailMessage MyMsg = new MailMessage();
MyMail.Host = "mail.eraygan.com";
MyMsg.Priority = MailPriority.High;
MyMsg.To.Add(new MailAddress(Mail));
MyMsg.Subject = Subject;
MyMsg.SubjectEncoding = Encoding.UTF8;
MyMsg.IsBodyHtml = true;
MyMsg.From = new MailAddress("username", "displayname");
MyMsg.BodyEncoding = Encoding.UTF8;
MyMsg.Body = Body;
MyMail.UseDefaultCredentials = false;
NetworkCredential MyCredentials = new NetworkCredential("username", "password");
MyMail.Credentials = MyCredentials;
MyMail.Send(MyMsg);
Unless ADB is running as root (as it would on an emulator) you cannot generally view anything under /data unless an application which owns it has made it world readable. Further, you cannot browse the directory structure - you can only list files once you get to a directory where you have access, by explicitly entering its path.
Broadly speaking you have five options:
Do the investigation within the owning app
Mark the files in question as public, and use something (adb shell or adb pull) where you can enter a full path name, instead of trying to browse the tree
Have the owning app copy the entire directory to the SD card
Use an emulator or rooted device where adb (and thus the ddms browser's access) can run as root (or use a root file explorer or a rooted device)
use adb and the run-as tool with a debuggable apk to get a command line shell running as the app's user id. For those familiar with the unix command line, this can be the most effective (though the toolbox sh on android is limited, and uses its tiny vocabulary of error messages in misleading ways)
GPS does not need any kind of internet or wireless connection, but there are technologies like A-GPS that use the mobile network to shorten the time to first fix, or the initial positioning or increase the precision in situations when there is a low satellite visibility.
Android phones tend to use A-GPS. If there is no connectivity, they use pure GPS. They do not override the data network mode. If you deactivated it, the phone won't use any data connection (which is handy if you are abroad, and do not want to pay expensive data roaming).
This error happened to me @angular 7
You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
The error is actually self-explanatory, it says somewhere
in the observable I pass the invalid object. In my case, there was lots of API call but all the calls were failing because of wrong server configuration. I tried to use map
, switchMap
, or other rxjs operator but the operators are getting undefined objects.
So double-check your rxjs operator inputs.
If you are in a browser environment you can also use btoa.
btoa
is a function which takes a string as argument and produces a Base64 encoded ASCII string. Its supported by 97% of browsers.
Example:
> "Basic " + btoa("billy"+":"+"secretpassword")
< "Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ="
You can then add Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ=
to the authorization
header.
Note that the usual caveats about HTTP BASIC auth apply, most importantly if you do not send your traffic over https an eavesdropped can simply decode the Base64 encoded string thus obtaining your password.
This security.stackexchange.com answer gives a good overview of some of the downsides.
No jQuery Needed
if (str.match(/[a-z]/i)) {
// alphabet letters found
}
Pay attention, there is a bug with Jquery 1.8.0, $(window).height() returns the all document height !
Create a Random object with a seed and get the array random by doing:
public static final int ARRAY_LENGTH = 20;
byte[] byteArray = new byte[ARRAY_LENGTH];
new Random(System.currentTimeMillis()).nextBytes(byteArray);
// get fisrt element
System.out.println("Random byte: " + byteArray[0]);
int i = 0;
bool b = Convert.ToBoolean(i);
Move round brackets like this:
var optionList = new List<string>(){"AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"};
The Collections.sort is a good sort implementation. If you don't have The comparable implemented for Contact, you will need to pass in a Comparator implementation
Of note:
The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance. The specified list must be modifiable, but need not be resizable. This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.
The merge sort is probably better than most search algorithm you can do.
Jason Scheirer's answer is correct but could use some more exposition.
First off, to repeat a string an integer number of times, you can use overloaded multiplication:
>>> 'abc' * 7
'abcabcabcabcabcabcabc'
So, to repeat a string until it's at least as long as the length you want, you calculate the appropriate number of repeats and put it on the right-hand side of that multiplication operator:
def repeat_to_at_least_length(s, wanted):
return s * (wanted//len(s) + 1)
>>> repeat_to_at_least_length('abc', 7)
'abcabcabc'
Then, you can trim it to the exact length you want with an array slice:
def repeat_to_length(s, wanted):
return (s * (wanted//len(s) + 1))[:wanted]
>>> repeat_to_length('abc', 7)
'abcabca'
Alternatively, as suggested in pillmod's answer that probably nobody scrolls down far enough to notice anymore, you can use divmod
to compute the number of full repetitions needed, and the number of extra characters, all at once:
def pillmod_repeat_to_length(s, wanted):
a, b = divmod(wanted, len(s))
return s * a + s[:b]
Which is better? Let's benchmark it:
>>> import timeit
>>> timeit.repeat('scheirer_repeat_to_length("abcdefg", 129)', globals=globals())
[0.3964178159367293, 0.32557755894958973, 0.32851039397064596]
>>> timeit.repeat('pillmod_repeat_to_length("abcdefg", 129)', globals=globals())
[0.5276265419088304, 0.46511475392617285, 0.46291469305288047]
So, pillmod's version is something like 40% slower, which is too bad, since personally I think it's much more readable. There are several possible reasons for this, starting with its compiling to about 40% more bytecode instructions.
Note: these examples use the new-ish //
operator for truncating integer division. This is often called a Python 3 feature, but according to PEP 238, it was introduced all the way back in Python 2.2. You only have to use it in Python 3 (or in modules that have from __future__ import division
) but you can use it regardless.
Edit: Use printf("val = 0x%" PRIx64 "\n", val);
instead.
Try printf("val = 0x%llx\n", val);
. See the printf manpage:
ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.
Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t
is not always a unsigned long long
: PRIx64
see also this stackoverflow answer
Here is a working example and you have to consider that every constructor with more fields should mark the extra fields as optional
.
class LocalError {
message?: string;
status?: string;
details?: Map<string, string>;
constructor(message: string);
constructor(message?: string, status?: string);
constructor(message?: string, status?: string, details?: Map<string, string>) {
this.message = message;
this.status = status;
this.details = details;
}
}
I know that this question is about 6+ years old, but the answer by @Kyle doesn't work.
Using this
setSize(width - (getInsets().left + getInsets().right), height - (getInsets().top + getInsets().bottom));
But this always work in any size:
setSize(width + 14, height + 7);
If you don't want the border to border, and only want the white area, here:
setSize(width + 16, height + 39);
Also this only works on Windows 10, for MacOS users, use @ben's answer.
Textarea resize control is available via the CSS3 resize property:
textarea { resize: both; } /* none|horizontal|vertical|both */
textarea.resize-vertical{ resize: vertical; }
textarea.resize-none { resize: none; }
Allowable values self-explanatory: none
(disables textarea resizing), both
, vertical
and horizontal
.
Notice that in Chrome, Firefox and Safari the default is both
.
If you want to constrain the width and height of the textarea element, that's not a problem: these browsers also respect max-height
, max-width
, min-height
, and min-width
CSS properties to provide resizing within certain proportions.
Code example:
#textarea-wrapper {_x000D_
padding: 10px;_x000D_
background-color: #f4f4f4;_x000D_
width: 300px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea {_x000D_
min-height:50px;_x000D_
max-height:120px;_x000D_
width: 290px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea.vertical { _x000D_
resize: vertical;_x000D_
}
_x000D_
<div id="textarea-wrapper">_x000D_
<label for="resize-default">Textarea (default):</label>_x000D_
<textarea name="resize-default" id="resize-default"></textarea>_x000D_
_x000D_
<label for="resize-vertical">Textarea (vertical):</label>_x000D_
<textarea name="resize-vertical" id="resize-vertical" class="vertical">Notice this allows only vertical resize!</textarea>_x000D_
</div>
_x000D_
Use the following code:
public void onBackPressed() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
The difference between test, [ and [[ is explained in great details in the BashFAQ.
To cut a long story short: test implements the old, portable syntax of the command. In almost all shells (the oldest Bourne shells are the exception), [ is a synonym for test (but requires a final argument of ]). Although all modern shells have built-in implementations of [, there usually still is an external executable of that name, e.g. /bin/[.
[[ is a new improved version of it, which is a keyword, not a program. This has beneficial effects on the ease of use, as shown below. [[ is understood by KornShell and BASH (e.g. 2.03), but not by the older POSIX or BourneShell.
And the conclusion:
When should the new test command [[ be used, and when the old one [? If portability to the BourneShell is a concern, the old syntax should be used. If on the other hand the script requires BASH or KornShell, the new syntax is much more flexible.
var audio = new Audio("http://rho.nu/pub/Game%20Of%20Thrones%20-%20Main%20Theme%20-%20Soundtrack.mp3");
audio.addEventListener('canplaythrough', function() {
this.currentTime = this.duration - 10;
this.loop = true;
this.play();
});
Just set loop = true in the canplaythrough eventlistener.
The only way to prevent SQL injection is with parameterized SQL. It simply isn't possible to build a filter that's smarter than the people who hack SQL for a living.
So use parameters for all input, updates, and where clauses. Dynamic SQL is simply an open door for hackers, and that includes dynamic SQL in stored procedures. Parameterize, parameterize, parameterize.
Since I was looking for an clarifying answer to this to determine the right type for notification icons, I'd like to add this clear statement to the topic. It's from http://developer.android.com/tools/help/image-asset-studio.html#saving
Note: Launcher icon files reside in a different location from that of other icons. They are located in the mipmap/ folder. All other icon files reside in the drawable/ folder of your project.
For NighwatchJS use:
"ie" : {
"desiredCapabilities": {
"browserName": "internet explorer",
"javascriptEnabled": true,
"acceptSslCerts": true,
"allowBlockedContent": true,
"ignoreProtectedModeSettings": true
}
},
You could also use React's useState
hook to declare local state for a function component. The initial state of the variable toggled
has been passed as an argument to the method .useState
.
import { render } from 'react-dom';
import React from "react";
type Props = {
text: string,
onClick(event: React.MouseEvent<HTMLButtonElement>): void,
};
export function HelloWorldButton(props: Props) {
const [toggled, setToggled] = React.useState(false); // returns a stateful value, and a function to update it
return <button
onClick={(event) => {
setToggled(!toggled);
props.onClick(event);
}}
>{props.text} (toggled: {toggled.toString()})</button>;
}
render(<HelloWorldButton text='Hello World' onClick={() => console.log('clicked!')} />, document.getElementById('root'));
alternative would be javascript and forwarding via the onclick event
<div onclick="window.location.href='somewhere...';">...</div>
All the different answers on this topic are very confusing, so I’m hoping to give a bit more clarity with this overview of the different bindings of libmagic. Previously mammadori gave a short answer listing the available option.
magic
When determining a files mime-type, the tool of choice is simply called file
and its back-end is called libmagic
. (See the Project home page.) The project is developed in a private cvs-repository, but there is a read-only git mirror on github.
Now this tool, which you will need if you want to use any of the libmagic bindings with python, already comes with its own python bindings called file-magic
. There is not much dedicated documentation for them, but you can always have a look at the man page of the c-library: man libmagic
. The basic usage is described in the readme file:
import magic
detected = magic.detect_from_filename('magic.py')
print 'Detected MIME type: {}'.format(detected.mime_type)
print 'Detected encoding: {}'.format(detected.encoding)
print 'Detected file type name: {}'.format(detected.name)
Apart from this, you can also use the library by creating a Magic
object using magic.open(flags)
as shown in the example file.
Both toivotuo and ewr2san use these file-magic
bindings included in the file
tool. They mistakenly assume, they are using the python-magic
package. This seems to indicate, that if both file
and python-magic
are installed, the python module magic
refers to the former one.
magic
This is the library that Simon Zimmermann talks about in his answer and which is also employed by Claude COULOMBE as well as Gringo Suave.
magic
Note: This project was last updated in 2013!
Due to being based on the same c-api, this library has some similarity with file-magic
included in libmagic
. It is only mentioned by mammadori and no other answer employs it.
The following method will allow you to lighten or darken the exposure value of a Hexadecimal (Hex) color string:
private static string GetHexFromRGB(byte r, byte g, byte b, double exposure)
{
exposure = Math.Max(Math.Min(exposure, 1.0), -1.0);
if (exposure >= 0)
{
return "#"
+ ((byte)(r + ((byte.MaxValue - r) * exposure))).ToString("X2")
+ ((byte)(g + ((byte.MaxValue - g) * exposure))).ToString("X2")
+ ((byte)(b + ((byte.MaxValue - b) * exposure))).ToString("X2");
}
else
{
return "#"
+ ((byte)(r + (r * exposure))).ToString("X2")
+ ((byte)(g + (g * exposure))).ToString("X2")
+ ((byte)(b + (b * exposure))).ToString("X2");
}
}
For the last parameter value in GetHexFromRGB(), Pass in a double value somewhere between -1 and 1 (-1 is black, 0 is unchanged, 1 is white):
// split color (#e04006) into three strings
var r = Convert.ToByte("e0", 16);
var g = Convert.ToByte("40", 16);
var b = Convert.ToByte("06", 16);
GetHexFromRGB(r, g, b, 0.25); // Lighten by 25%;
From this answer:
[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
var content = request.Content;
string jsonContent = content.ReadAsStringAsync().Result;
}
Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.
{
int main(void);
should be
int main(void)
{
Then I let you fix the next compilation errors of your program...
You are dropping it, then creating it, then trying to create it again by using SELECT INTO
. Change to:
DROP TABLE #TMPGUARDIAN
CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))
INSERT INTO #TMPGUARDIAN
SELECT LAST_NAME,FRST_NAME
FROM TBL_PEOPLE
In MS SQL Server you can create a table without a CREATE TABLE
statement by using SELECT INTO
Here is my use case, which requires an exceptional amount of encoding. Maybe you think it contrived, but we run this on production. Coincidently, this covers every type of encoding, so I'm posting as a tutorial.
Somebody just bought a prepaid gift card ("token") on our website. Tokens have corresponding URLs to redeem them. This customer wants to email the URL to someone else. Our web page includes a mailto
link that lets them do that.
// The order system generates some opaque token
$token = 'w%a&!e#"^2(^@azW';
// Here is a URL to redeem that token
$redeemUrl = 'https://httpbin.org/get?token=' . urlencode($token);
// Actual contents we want for the email
$subject = 'I just bought this for you';
$body = 'Please enter your shipping details here: ' . $redeemUrl;
// A URI for the email as prescribed
$mailToUri = 'mailto:?subject=' . rawurlencode($subject) . '&body=' . rawurlencode($body);
// Print an HTML element with that mailto link
echo '<a href="' . htmlspecialchars($mailToUri) . '">Email your friend</a>';
Note: the above assumes you are outputting to a text/html
document. If your output media type is text/json
then simply use $retval['url'] = $mailToUri;
because output encoding is handled by json_encode()
.
You should see:
"args": {
"token": "w%a&!e#\"^2(^@azW"
},
And of course this is the JSON representation of $token
above.
You can also try with Object.values
const points = { Neel: 100, Veer: 89, Shubham: 78, Vikash: 67 };_x000D_
_x000D_
const vals = Object.values(points);_x000D_
const max = Math.max(...vals);_x000D_
const min = Math.min(...vals);_x000D_
console.log(max);_x000D_
console.log(min);
_x000D_
You can use a much simpler formula. I just created a new workbook to test it.
Column A = Date1 | Column B = Date2 | Column C = Date3
Highlight Column A and enter the conditional formatting formula:
=AND(A1>B1,A1<C1)
Running JMeter in command line mode:
1.Navigate to JMeter’s bin directory
Now enter following command,
jmeter -n –t test.jmx
-n: specifies JMeter is to run in non-gui mode
-t: specifies name of JMX file that contains the Test Plan
I would like to add the official npmjs documentation as well which describes all methods for version specificity including the ones referred to in the question -
https://docs.npmjs.com/files/package.json
https://docs.npmjs.com/misc/semver#x-ranges-12x-1x-12-
~version
"Approximately equivalent to version" See npm semver - Tilde Ranges & semver (7)^version
"Compatible with version" See npm semver - Caret Ranges & semver (7)version
Must match version exactly>version
Must be greater than version>=version
etc<version
<=version
1.2.x
1.2.0, 1.2.1, etc., but not 1.3.0http://sometarballurl
(this may be the URL of a tarball which will be downloaded and installed locally*
Matches any versionlatest
Obtains latest releaseThe above list is not exhaustive. Other version specifiers include GitHub urls and GitHub user repo's, local paths and packages with specific npm tags
Shared folder was earlier working for me but all f sudden it stopped working (Virualbox - host was Windows 7, Guest was OpenSuSe)
modprobe -a vboxguest vboxsf vboxvideo
then
mount -t vboxsf testsf /opt/tsf
(testsf
was the folder in Windows C drive which was added in Virtualbox shared folder --- and /opt/tsf
is the folder in OpenSuse
In order to create a File from a HTTP URL you need to download the contents from that URL:
URL url = new URL("http://www.google.ro/logos/2011/twain11-hp-bg.jpg");
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("downloaded.jpg"));
byte[] buf = new byte[512];
while (true) {
int len = in.read(buf);
if (len == -1) {
break;
}
fos.write(buf, 0, len);
}
in.close();
fos.flush();
fos.close();
The downloaded file will be found at the root of your project: {project}/downloaded.jpg
The following works for me:
form_for @user, :url => {:action => "YourActionName"}
Look at https://expressjs.com/en/resources/middleware/cors.html You have to use cors.
Install:
$ npm install cors
const cors = require('cors');
app.use(cors());
You have to put this code in your node server.
After converting your varchar2
date to a true date
datatype, then convert back to varchar2
with the desired mask:
to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW')
If you want the week number in a number
datatype, you can wrap the statement in to_number()
:
to_number(to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW'))
However, you have several week number options to consider:
WW Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year.
W Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh.
IW Week of year (1-52 or 1-53) based on the ISO standard.
There are already multiple answers and formatting types for SQL server 2008. But this method somewhat ambiguous and it would be difficult for you to remember the number with respect to Specific Date Format. That's why in next versions of SQL server there is better option.
FORMAT ( value, format [, culture ] )
With culture option, you can specify date as per your viewers.
DECLARE @d DATETIME = '10/01/2011';
SELECT FORMAT ( @d, 'd', 'en-US' ) AS 'US English Result'
,FORMAT ( @d, 'd', 'en-gb' ) AS 'Great Britain English Result'
,FORMAT ( @d, 'd', 'de-de' ) AS 'German Result'
,FORMAT ( @d, 'd', 'zh-cn' ) AS 'Simplified Chinese (PRC) Result';
SELECT FORMAT ( @d, 'D', 'en-US' ) AS 'US English Result'
,FORMAT ( @d, 'D', 'en-gb' ) AS 'Great Britain English Result'
,FORMAT ( @d, 'D', 'de-de' ) AS 'German Result'
,FORMAT ( @d, 'D', 'zh-cn' ) AS 'Chinese (Simplified PRC) Result';
US English Result Great Britain English Result German Result Simplified Chinese (PRC) Result
---------------- ----------------------------- ------------- -------------------------------------
10/1/2011 01/10/2011 01.10.2011 2011/10/1
US English Result Great Britain English Result German Result Chinese (Simplified PRC) Result
---------------------------- ----------------------------- ----------------------------- ---------------------------------------
Saturday, October 01, 2011 01 October 2011 Samstag, 1. Oktober 2011 2011?10?1?
For OP's solution, we can use following format, which is already mentioned by @Martin Smith:
FORMAT(GETDATE(), 'dd/MMM/yyyy', 'en-us')
Some sample date formats:
If you want more date formats of SQL server, you should visit:
We wrote a CLI tool for this purpose: docker-ls It allows you to browse a docker registry and supports authentication via token or basic auth.
In my case it was just because I had not Saved the source file and was trying to compile a empty file .
Try this:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
Notice that you have to work at least with 4.5 .NET framework
I am on an angular project that (unfortunately) uses source code inclusion via tsconfig.json
to connect different collections of code. I came across a similar StaticInjector
error for a service (e.g.RestService
in the top example) and I was able to fix it by listing the service dependencies in the deps
array when providing the affected service in the module, for example:
import { HttpClient } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { RestService } from 'mylib/src/rest/rest.service';
...
@NgModule({
imports: [
...
HttpModule,
...
],
providers: [
{
provide: RestService,
useClass: RestService,
deps: [HttpClient] /* the injected services in the constructor for RestService */
},
]
...
Don't know why, my Neon Eclipse still having this issue, it doesn't seem to be fixed in Mars version as many people said.
I found that using command is too troublesome, I delete the plugin away via the Eclipse Installation Manager.
Just select the plugin "Dali Java Persistence Tools -JPA Support" and click "uninstall" will do. Please take note my screen below doesn't have that because I already uninstalled.
You need to set property for the control:
listView1.View = View.Details;
If you have XDocument it is easier to use LINQ-to-XML:
var document = XDocument.Load(fileName);
var name = document.Descendants(XName.Get("Name", @"http://demo.com/2011/demo-schema")).First().Value;
If you are sure that XPath is the only solution you need:
using System.Xml.XPath;
var document = XDocument.Load(fileName);
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("empty", "http://demo.com/2011/demo-schema");
var name = document.XPathSelectElement("/empty:Report/empty:ReportInfo/empty:Name", namespaceManager).Value;
It's already 2017, and you can now use Apache Commons Collections4
The usage:
for(Object obj : CollectionUtils.emptyIfNull(list1)){
// Do your stuff
}
$(document).ready(function () {
var someObj = {};
$("#checkAll").click(function () {
$('.chk').prop('checked', this.checked);
});
$(".chk").click(function () {
$("#checkAll").prop('checked', ($('.chk:checked').length == $('.chk').length) ? true : false);
});
$("input:checkbox").change(function () {
debugger;
someObj.elementChecked = [];
$("input:checkbox").each(function () {
if ($(this).is(":checked")) {
someObj.elementChecked.push($(this).attr("id"));
}
});
});
$("#button").click(function () {
debugger;
alert(someObj.elementChecked);
});
});
</script>
</head>
<body>
<ul class="chkAry">
<li><input type="checkbox" id="checkAll" />Select All</li>
<li><input class="chk" type="checkbox" id="Delhi">Delhi</li>
<li><input class="chk" type="checkbox" id="Pune">Pune</li>
<li><input class="chk" type="checkbox" id="Goa">Goa</li>
<li><input class="chk" type="checkbox" id="Haryana">Haryana</li>
<li><input class="chk" type="checkbox" id="Mohali">Mohali</li>
</ul>
<input type="button" id="button" value="Get" />
</body>
my solution, hope help
custom ObjectMapper and config to spring xml(register message conveters)
public class PyResponseConfigObjectMapper extends ObjectMapper {
public PyResponseConfigObjectMapper() {
disable(SerializationFeature.WRITE_NULL_MAP_VALUES); //map no_null
setSerializationInclusion(JsonInclude.Include.NON_NULL); // bean no_null
}
}
Use of the argmin method for numpy arrays.
import numpy as np
np.argmin(myList)
However, it is not the fastest method: it is 3 times slower than OP's answer on my computer. It may be the most concise one though.
Just turn off notifications for the default sms app. Process your own notifications for all text messages!
iTerm handles multiple-line command perfectly, it saves multiple-lines command as one command, then we can use Cmd
+ Shift
+ ;
to navigate the history.
Check more iTerm tips at Working effectively with iTerm
…just because this method hasn't been mentioned so far - open the console and type:
$ === jQuery
As @Juhana mentioned above $().jquery
will return the version number.
It's quite possible that someone will provide a truly detailed answer here, but I've always found this post from Robert Sosinski to be a great explanation of the subtleties between blocks, procs & lambdas.
I should add that I believe the post I'm linking to is specific to ruby 1.8. Some things have changed in ruby 1.9, such as block variables being local to the block. In 1.8, you'd get something like the following:
>> a = "Hello"
=> "Hello"
>> 1.times { |a| a = "Goodbye" }
=> 1
>> a
=> "Goodbye"
Whereas 1.9 would give you:
>> a = "Hello"
=> "Hello"
>> 1.times { |a| a = "Goodbye" }
=> 1
>> a
=> "Hello"
I don't have 1.9 on this machine so the above might have an error in it.
Look for an installation subdirectory, likely named eclipse. Under that subdirectory, if you see files like eclipse.ini, icon.xpm and subdirectories like plugins and dropins, remove the subdirectory parent (the one named eclipse).
That will remove your installation except for anything you've set up yourself (like workspaces, projects, etc.).
Hope this helps.
tell you the true, I still don't get what you need, but
window.location(url);
should be
window.location = url;
a search on window.location reference will tell you that.
If you're using ASP.NET Core MVC and need to handle the square brackets (rather than use the jQuery "traditional" option), the only option I've found is to manually build the IEnumerable
in the contoller method.
string arrayKey = "p[]=";
var pArray = HttpContext.Request.QueryString.Value
.Split('&')
.Where(s => s.Contains(arrayKey))
.Select(s => s.Substring(arrayKey.Length));
In Windows, you can use /
in your path just like Linux or macOS in all places as long as you use PowerShell as your command-line interface. It comes pre-installed on Windows and it supports many Linux commands like ls
command.
If you use Windows Command Prompt (the one that appears when you type cmd
in Windows Start Menu), you need to specify paths with \
just inside it. You can use /
paths in all other places (code editor, Python interactive mode, etc.).
As you've tagged this jQuery ...
First, put IDs on your input buttons and remove the inline handlers:
<input type="number" id="input" />
<input type="button" id="stop" value="stop"/>
<input type="button" id="start" value="start"/>
Then keep all of your state and functions encapsulated in a closure:
EDIT updated for a cleaner implementation, that also addresses @Esailija's concerns about use of setInterval()
.
$(function() {
var timer = null;
var input = document.getElementById('input');
function tick() {
++input.value;
start(); // restart the timer
};
function start() { // use a one-off timer
timer = setTimeout(tick, 1000);
};
function stop() {
clearTimeout(timer);
};
$('#start').bind("click", start); // use .on in jQuery 1.7+
$('#stop').bind("click", stop);
start(); // if you want it to auto-start
});
This ensures that none of your variables leak into global scope, and can't be modified from outside.
(Updated) working demo at http://jsfiddle.net/alnitak/Q6RhG/
Say you let vmware use port 443, and use another ssl port in XAMPP Apache (httpd-ssl.conf) :
The red error will keep popping in XAMPP Control Panel. You also need to change the port in the XAMPP Control Panel configuration :
In XAMPP Control Panel, click the "Config" button (top-left). Then click "Service and Port Settings". There you can set the ports to match the ports used by Apache.
You simply can find a matrix dimension by using Numpy:
import numpy as np
x = np.arange(24).reshape((6, 4))
x.ndim
output will be:
2
It means this matrix is a 2 dimensional matrix.
x.shape
Will show you the size of each dimension. The shape for x is equal to:
(6, 4)
The CSS property font-variant-position
is under consideration and may eventually be the answer to this question. As of early 2017, only Firefox supports it, though.
.super {
font-variant-position: super;
}
See MDN.
There are hardware and software watchpoints. They are for reading and for writing a variable. You need to consult a tutorial:
http://www.unknownroad.com/rtfm/gdbtut/gdbwatch.html
To set a watchpoint, first you need to break the code into a place where the varianle i is present in the environment, and set the watchpoint.
watch
command is used to set a watchpoit for writing, while rwatch
for reading, and awatch
for reading/writing.
If the child is always going to be a specific tag then you could do it like this
function test(el)
{
var children = el.getElementsByTagName('div');// any tag could be used here..
for(var i = 0; i< children.length;i++)
{
if (children[i].getAttribute('id') == 'child') // any attribute could be used here
{
// do what ever you want with the element..
// children[i] holds the element at the moment..
}
}
}
Code worked very well! You can overload onSizeChanged method, if not only Text has to be Changed.
@Override
protected void onSizeChanged (int w, int h, int oldw, int oldh) {
isStale = true;
super.onSizeChanged(w, h, oldw, oldh);
}
Try this On window load submit your form.
window.onload = function(){
document.forms['member_signup'].submit();
}
I did what @gbero said, and I changed the Android version number that Studio uses from 22 to 17 and it works.
I am using the backwards compatibility to build for Android ver 22 but to target 17 (idk if that's correctly said, I am still trying to figure this app stuff out) so that triggered the backwards compatibility, which afaik is what the android.support.v7.*
is. This is probably a bug with their rendering code. Not sure if clearing the cache as suggested above was needed as rendering didn't work just after invalidating the cache, it started working after I changed the version to render. If I change back to version 22, the rendering breaks, if I switch back to 17, it works again.
Microsoft SQL Server for instance, Schemas refer to a single user and is another level of a container in the order of indicating the server, database, schema, tables, and objects.
For example, when you are intending to update dbo.table_a and the syntax isn't full qualified such as UPDATE table.a the DBMS can't decide to use the intended table. Essentially by default the DBMS will utilize myuser.table_a
if needle in haystack:
is the normal use, as @Michael says -- it relies on the in
operator, more readable and faster than a method call.
If you truly need a method instead of an operator (e.g. to do some weird key=
for a very peculiar sort...?), that would be 'haystack'.__contains__
. But since your example is for use in an if
, I guess you don't really mean what you say;-). It's not good form (nor readable, nor efficient) to use special methods directly -- they're meant to be used, instead, through the operators and builtins that delegate to them.
Easiest method is to type:
sudo /bin/sh example.sh
If you want to dump the entire db as csv
#!/bin/bash
host=hostname
uname=username
pass=password
port=portnr
db=db_name
s3_url=s3://bxb2-anl-analyzed-pue2/bxb_ump/db_dump/
DATE=`date +%Y%m%d`
rm -rf $DATE
echo 'show tables' | mysql -B -h${host} -u${uname} -p${pass} -P${port} ${db} > tables.txt
awk 'NR>1' tables.txt > tables_new.txt
while IFS= read -r line
do
mkdir -p $DATE/$line
echo "select * from $line" | mysql -B -h"${host}" -u"${uname}" -p"${pass}" -P"${port}" "${db}" > $DATE/$line/dump.tsv
done < tables_new.txt
touch $DATE/$DATE.fin
rm -rf tables_new.txt tables.txt
Here a simple one liners to check if only one parameter is given otherwise exit the script:
[ "$#" -ne 1 ] && echo "USAGE $0 <PARAMETER>" && exit
You could also do:
for option in options:
if option == options[selected_index]:
#print
else:
#print
Although you'd run into issues if there are duplicate options.
You want
typedef char type24[3];
C type declarations are strange that way. You put the type exactly where the variable name would go if you were declaring a variable of that type.
I have faced the similar issue on my website hosted on IIS. This issue generally because of IIS Application pool settings. As application pool recycle after some time that caused the issue for me.
Following steps help me to fix the issue:
Then try again . It will solve your issue.
What no one here is saying is that with Build Tools 24.0.0, Java 8 is required and most people have either 1.6 or 1.7.
So yeah, setting the build tool to 23.x.x would 'solve' the problem but the root cause is the Java version on your system.
On the long term, you might want to upgrade your dev environment to use JDK8 to make use the new language enhancements and the jack compiler.
If you have already got the cursor, then this is how you may get the last record from cursor:
cursor.moveToPosition(cursor.getCount() - 1);
//then use cursor to read values
If this need to be done in UIBarButtonItem, additional wrapping in view should be used
This will work
let view = UIView()
let button = UIButton()
button.setTitle("Skip", for: .normal)
button.setImage(#imageLiteral(resourceName:"forward_button"), for: .normal)
button.semanticContentAttribute = .forceRightToLeft
button.sizeToFit()
view.addSubview(button)
view.frame = button.bounds
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: view)
This won't work
let button = UIButton()
button.setTitle("Skip", for: .normal)
button.setImage(#imageLiteral(resourceName:"forward_button"), for: .normal)
button.semanticContentAttribute = .forceRightToLeft
button.sizeToFit()
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
For a cross-browser solution (tested in Chrome 21, IE9, FF15), consider using the following code, which is a slightly tweaked version of Slaks' code:
var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind('beforeunload', function(eventObject) {
var returnValue = undefined;
if (! inFormOrLink) {
returnValue = "Do you really want to close?";
}
eventObject.returnValue = returnValue;
return returnValue;
});
Note that since Firefox 4, the message "Do you really want to close?" is not displayed. FF just displays a generic message. See note in https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload
Using Java 8's time API (assuming you are happy to get the year in your system's default time zone), you could use the Year::now
method:
int year = Year.now().getValue();
This error can be resolved by various methods-
If you are using ES5 syntax, then as per React js Documentation you have to use bind method.
Something like this for the above example:
this.delta = this.delta.bind(this)
If you are using ES6 syntax,then you need not use bind method,you can do it with something like this:
delta=()=>{
this.setState({
count : this.state.count++
});
}
Expression you are looking for may be:
...
return any( isinstance(e, list) for e in my_list )
Testing:
>>> my_list = [1,2]
>>> any( isinstance(e, list) for e in my_list )
False
>>> my_list = [1,2, [3,4,5]]
>>> any( isinstance(e, list) for e in my_list )
True
>>>
You could also make it a post-build step. Setup a new configuration which is "Deploy" in addition to Debug and Release, and then have the post-build step copy over the correct web.config.
We use automated builds for all of our projects, and with those the build script updates the web.config file to point to the correct location. But that won't help you if you are doing everything from VS.
To send an email from iPhone application you need to do below list of task.
Step 1: Import #import <MessageUI/MessageUI.h>
In your controller class where you want to send an email.
Step 2: Add the delegate to your controller like shown below
@interface <yourControllerName> : UIViewController <MFMessageComposeViewControllerDelegate, MFMailComposeViewControllerDelegate>
Step 3: Add below method for send email.
- (void) sendEmail {
// Check if your app support the email.
if ([MFMailComposeViewController canSendMail]) {
// Create an object of mail composer.
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
// Add delegate to your self.
mailComposer.mailComposeDelegate = self;
// Add recipients to mail if you do not want to add default recipient then remove below line.
[mailComposer setToRecipients:@[<add here your recipient objects>]];
// Write email subject.
[mailComposer setSubject:@“<Your Subject Here>”];
// Set your email body and if body contains HTML then Pass “YES” in isHTML.
[mailComposer setMessageBody:@“<Your Message Body>” isHTML:NO];
// Show your mail composer.
[self presentViewController:mailComposer animated:YES completion:NULL];
}
else {
// Here you can show toast to user about not support to sending email.
}
}
Step 4: Implement MFMailComposeViewController Delegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(nullable NSError *)error {
[controller dismissViewControllerAnimated:TRUE completion:nil];
switch (result) {
case MFMailComposeResultSaved: {
// Add code on save mail to draft.
break;
}
case MFMailComposeResultSent: {
// Add code on sent a mail.
break;
}
case MFMailComposeResultCancelled: {
// Add code on cancel a mail.
break;
}
case MFMailComposeResultFailed: {
// Add code on failed to send a mail.
break;
}
default:
break;
}
}
The primary use of AtomicInteger
is when you are in a multithreaded context and you need to perform thread safe operations on an integer without using synchronized
. The assignation and retrieval on the primitive type int
are already atomic but AtomicInteger
comes with many operations which are not atomic on int
.
The simplest are the getAndXXX
or xXXAndGet
. For instance getAndIncrement()
is an atomic equivalent to i++
which is not atomic because it is actually a short cut for three operations: retrieval, addition and assignation. compareAndSet
is very useful to implements semaphores, locks, latches, etc.
Using the AtomicInteger
is faster and more readable than performing the same using synchronization.
A simple test:
public synchronized int incrementNotAtomic() {
return notAtomic++;
}
public void performTestNotAtomic() {
final long start = System.currentTimeMillis();
for (int i = 0 ; i < NUM ; i++) {
incrementNotAtomic();
}
System.out.println("Not atomic: "+(System.currentTimeMillis() - start));
}
public void performTestAtomic() {
final long start = System.currentTimeMillis();
for (int i = 0 ; i < NUM ; i++) {
atomic.getAndIncrement();
}
System.out.println("Atomic: "+(System.currentTimeMillis() - start));
}
On my PC with Java 1.6 the atomic test runs in 3 seconds while the synchronized one runs in about 5.5 seconds. The problem here is that the operation to synchronize (notAtomic++
) is really short. So the cost of the synchronization is really important compared to the operation.
Beside atomicity AtomicInteger can be use as a mutable version of Integer
for instance in Map
s as values.
Another python3 implementation that involves the use of Abstract classes with super(). You should remember that
super().__init__(name, 10)
has the same effect as
Person.__init__(self, name, 10)
Remember there's a hidden 'self' in super(), So the same object passes on to the superclass init method and the attributes are added to the object that called it.
Hence super()
gets translated to Person
and then if you include the hidden self, you get the above code frag.
from abc import ABCMeta, abstractmethod
class Person(metaclass=ABCMeta):
name = ""
age = 0
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
@abstractmethod
def showName(self):
pass
@abstractmethod
def showAge(self):
pass
class Man(Person):
def __init__(self, name, height):
self.height = height
# Person.__init__(self, name, 10)
super().__init__(name, 10) # same as Person.__init__(self, name, 10)
# basically used to call the superclass init . This is used incase you want to call subclass init
# and then also call superclass's init.
# Since there's a hidden self in the super's parameters, when it's is called,
# the superclasses attributes are a part of the same object that was sent out in the super() method
def showIdentity(self):
return self.name, self.age, self.height
def showName(self):
pass
def showAge(self):
pass
a = Man("piyush", "179")
print(a.showIdentity())
You can use java.util.Objects
as following.
public static boolean compare(String str1, String str2) {
return Objects.equals(str1, str2);
}
I agree with @arcy, the problem is on client side, on my case it was because of nginx, let me elaborate
I am using nginx as the frontend (so I can distribute load, ssl, etc ...) and using proxy_pass http://127.0.0.1:8080
to forward the appropiate requests to tomcat.
There is a default value for the nginx variable proxy_read_timeout
of 60s that should be enough, but on some peak moments my setup would error with the java.io.IOException: Broken pipe changing the value will help until the root cause (60s should be enough) can be fixed.
NOTE: I made a new answer so I could expand a bit more with my case (it was the only mention I found about this error on internet after looking quite a lot)
$('.line').click(function() {_x000D_
$(this).toggleClass('red');_x000D_
});
_x000D_
.line {_x000D_
border: 0;_x000D_
background-color: #000;_x000D_
height: 3px;_x000D_
cursor: pointer;_x000D_
}_x000D_
.red {_x000D_
background-color: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<hr class="line"></hr>_x000D_
<p>click the line</p>
_x000D_
I used this way, and kind liked it , it validates the form before submit also is compatible with safari/google. no jquery n.n.
<module-body>
<form id="testform" method="post">
<label>Input Title</label>
<input name="named1" placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
<alert>No Alerts!</alert>
<label>Input Title</label>
<input placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
<alert>No Alerts!</alert>
<label>Input Title</label>
<input placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
<alert>No Alerts!</alert>
</form>
</module-body>
<module-footer>
<input type="button" onclick='if (document.querySelector("#testform").reportValidity()) { document.querySelector("#testform").submit(); }' value="Submit">
<input type="button" value="Reset">
</module-footer>
Per the specification, the JSON grammar's char production can take the following values:
"
-or-\
-or-control-character\"
\\
\/
\b
\f
\n
\r
\t
\u
four-hex-digitsNewlines are "control characters", so no, you may not have a literal newline within your string. However, you may encode it using whatever combination of \n
and \r
you require.
The JSONLint tool confirms that your JSON is invalid.
And, if you want to write newlines inside your JSON syntax without actually including newlines in the data, then you're doubly out of luck. While JSON is intended to be human-friendly to a degree, it is still data and you're trying to apply arbitrary formatting to that data. That is absolutely not what JSON is about.
A useful trick to avoid creating temporary patch files:
git diff | patch -p1 -d [dst-dir]
It was moved to functools
.
If you'd like the cross to be partially transparent, the naive approach would be to make linear-gradient
colors semi-transparent. But that doesn't work out good due to the alpha blending at the intersection, producing a differently colored diamond. The solution to this is to leave the colors solid but add transparency to the gradient container instead:
.cross {_x000D_
position: relative;_x000D_
}_x000D_
.cross::after {_x000D_
pointer-events: none;_x000D_
content: "";_x000D_
position: absolute;_x000D_
top: 0; bottom: 0; left: 0; right: 0;_x000D_
}_x000D_
_x000D_
.cross1::after {_x000D_
background:_x000D_
linear-gradient(to top left, transparent 45%, rgba(255,0,0,0.35) 46%, rgba(255,0,0,0.35) 54%, transparent 55%),_x000D_
linear-gradient(to top right, transparent 45%, rgba(255,0,0,0.35) 46%, rgba(255,0,0,0.35) 54%, transparent 55%);_x000D_
}_x000D_
_x000D_
.cross2::after {_x000D_
background:_x000D_
linear-gradient(to top left, transparent 45%, rgb(255,0,0) 46%, rgb(255,0,0) 54%, transparent 55%),_x000D_
linear-gradient(to top right, transparent 45%, rgb(255,0,0) 46%, rgb(255,0,0) 54%, transparent 55%);_x000D_
opacity: 0.35;_x000D_
}_x000D_
_x000D_
div { width: 180px; text-align: justify; display: inline-block; margin: 20px; }
_x000D_
<div class="cross cross1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et dui imperdiet, dapibus augue quis, molestie libero. Cras nisi leo, sollicitudin nec eros vel, finibus laoreet nulla. Ut sit amet leo dui. Praesent rutrum rhoncus mauris ac ornare. Donec in accumsan turpis, pharetra eleifend lorem. Ut vitae aliquet mi, id cursus purus.</div>_x000D_
_x000D_
<div class="cross cross2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et dui imperdiet, dapibus augue quis, molestie libero. Cras nisi leo, sollicitudin nec eros vel, finibus laoreet nulla. Ut sit amet leo dui. Praesent rutrum rhoncus mauris ac ornare. Donec in accumsan turpis, pharetra eleifend lorem. Ut vitae aliquet mi, id cursus purus.</div>
_x000D_
<input type='submit' value='Submit' onclick='this.form.action="somethingelse";' />
Or you can modify it from outside the form, with javascript the normal way:
document.getElementById('form_id').action = 'somethingelse';
I would just use
string data= "/temp string";
data = data.substring(1)
Output:
temp string
That always works for me.
Even though this can technically be solved as pgb recommends, IMHO, this is a design flaw. The view should not need to be aware of the controller.
Xavi's code was allmost fully working. But when navigating to another page, submitting a form, then being redirected to the page with my tabs was not loading the saved tab at all.
localStorage to the rescue (slightly changed Nguyen's code):
$('a[data-toggle="tab"]').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
$('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
var id = $(e.target).attr("href");
localStorage.setItem('selectedTab', id)
});
var selectedTab = localStorage.getItem('selectedTab');
if (selectedTab != null) {
$('a[data-toggle="tab"][href="' + selectedTab + '"]').tab('show');
}
The problem with all of the answers given so far is that on the something borrowed site, the Mac bar remains totally hidden when scrolling up, and the provided answers don't accomplish that.
If you just use scrollTo
and then the user later scrolls up, the nav bar is revealed again, so it seems you have to put the whole site inside of a div and force scrolling to happen inside of that div rather than on the body which keeps the nav bar hidden during scrolling in any direction.
You can, however, still reveal the nav bar by touching near the top of the screen on apple devices.
For future Googlers i've a different approach to check if it's last element. It's similar to last lines in OP question.
This directly compares elements rather than just checking index numbers.
$yourset.each(function() {
var $this = $(this);
if($this[0] === $yourset.last()[0]) {
//$this is the last one
}
});
You can use Calendar's method
func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = default) -> Date?
to add any Calendar.Component
to any Date
. You can create a Date extension to add x minutes to your UIDatePicker
's date:
Xcode 8 and Xcode 9 • Swift 3.0 and Swift 4.0
extension Date {
func adding(minutes: Int) -> Date {
return Calendar.current.date(byAdding: .minute, value: minutes, to: self)!
}
}
Then you can just use the extension method to add minutes to the sender (UIDatePicker):
let section1 = sender.date.adding(minutes: 5)
let section2 = sender.date.adding(minutes: 10)
Playground testing:
Date().adding(minutes: 10) // "Jun 14, 2016, 5:31 PM"
If you are using maven, define your profiles as shown below within your pom.xml
<profiles>
<profile>
<id>local</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<jdbc.url>dbUrl</jdbc.url>
<jdbc.username>dbuser</jdbc.username>
<jdbc.password>dbPassword</jdbc.password>
<jdbc.driver>dbDriver</jdbc.driver>
</properties>
</profile>
<profile>
<id>dev</id>
<properties>
<jdbc.url>dbUrl</jdbc.url>
<jdbc.username>dbuser</jdbc.username>
<jdbc.password>dbPassword</jdbc.password>
<jdbc.driver>dbDriver</jdbc.driver>
</properties>
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
</dependencies>
</profile>
<profile>
<id>prod</id>
<properties>
<jdbc.url>dbUrl</jdbc.url>
<jdbc.username>dbuser</jdbc.username>
<jdbc.password>dbPassword</jdbc.password>
<jdbc.driver>dbDriver</jdbc.driver>
</properties>
</profile>
By default, i.e if No profile is selected, the local profile will always be use.
To select a specific profile in Spring Boot 2.x.x, use the below command.
mvn spring-boot:run -Dspring-boot.run.profiles=dev
If you want want to build/compile using properties of a specific profile, use the below command.
mvn clean install -Pdev -DprofileIdEnabled=true
picmate's answer is right. on windows the main DB folder location is (at least on my installation)
C:\PostgreSQL\9.2\data\base\
and not in program files.
his 2 scripts, will give you the exact directory/file(s) you need:
SELECT oid from pg_database WHERE datname = <database_name>;
SELECT relname, relfilenode FROM pg_class WHERE relname = <table_name>;
mine is in datname 16393 and relfilenode 41603
The initial problem is that the the configuration specifies a property suffix=".jsp"
so the ViewResolver implementing class will add .jsp
to the end of the view name being returned from your method.
However since you commented out the InternalResourceViewResolver
then, depending on the rest of your application configuration, there might not be any other ViewResolver registered. You might find that nothing is working now.
Since .html
files are static and do not require processing by a servlet then it is more efficient, and simpler, to use an <mvc:resources/>
mapping. This requires Spring 3.0.4+.
For example:
<mvc:resources mapping="/static/**" location="/static/" />
which would pass through all requests starting with /static/
to the webapp/static/
directory.
So by putting index.html
in webapp/static/
and using return "static/index.html";
from your method, Spring should find the view.
std::less<>
when using custom classes with operator<
If you are dealing with a set of your custom class that has operator<
defined, then you can just use std::less<>
.
As mentioned at http://en.cppreference.com/w/cpp/container/set/find C++14 has added two new find
APIs:
template< class K > iterator find( const K& x );
template< class K > const_iterator find( const K& x ) const;
which allow you to do:
main.cpp
#include <cassert>
#include <set>
class Point {
public:
// Note that there is _no_ conversion constructor,
// everything is done at the template level without
// intermediate object creation.
//Point(int x) : x(x) {}
Point(int x, int y) : x(x), y(y) {}
int x;
int y;
};
bool operator<(const Point& c, int x) { return c.x < x; }
bool operator<(int x, const Point& c) { return x < c.x; }
bool operator<(const Point& c, const Point& d) {
return c.x < d;
}
int main() {
std::set<Point, std::less<>> s;
s.insert(Point(1, -1));
s.insert(Point(2, -2));
s.insert(Point(0, 0));
s.insert(Point(3, -3));
assert(s.find(0)->y == 0);
assert(s.find(1)->y == -1);
assert(s.find(2)->y == -2);
assert(s.find(3)->y == -3);
// Ignore 1234, find 1.
assert(s.find(Point(1, 1234))->y == -1);
}
Compile and run:
g++ -std=c++14 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
More info about std::less<>
can be found at: What are transparent comparators?
Tested on Ubuntu 16.10, g++
6.2.0.
Things are much easier nowadays: the builtin Snippet Generator supports the 'build' step (I don't know since when though).
the above solutions wont work on ipad-2
recently I had an safari browser crash issue while plotting the markers even if there are less number of markers. Initially I was using marker with label (markerwithlabel.js) library for plotting the marker , when i use google native marker it was working fine even with large number of markers but i want customized markers , so i refer the above solution given by jonathan but still the crashing issue is not resolved after doing lot of research i came to know about http://nickjohnson.com/b/google-maps-v3-how-to-quickly-add-many-markers this blog and now my map search is working smoothly on ipad-2 :)
IsEmpty()
would be the quickest way to check for that.
IsNull()
would seem like a similar solution, but keep in mind Null has to be assigned to the cell; it's not inherently created in the cell.
Also, you can check the cell by:
count()
counta()
Len(range("BCell").Value) = 0
Some great solutions have already been posted. When I encountered this problem, I wanted to go both ways: convert an enum into a description, and convert a string matching a description into an enum.
I have two variants, slow and fast. Both convert from enum to string and string to enum. My problem is that I have enums like this, where some elements need attributes and some don't. I don't want to put attributes on elements that don't need them. I have about a hundred of these total currently:
public enum POS
{
CC, // Coordinating conjunction
CD, // Cardinal Number
DT, // Determiner
EX, // Existential there
FW, // Foreign Word
IN, // Preposision or subordinating conjunction
JJ, // Adjective
[System.ComponentModel.Description("WP$")]
WPDollar, //$ Possessive wh-pronoun
WRB, // Wh-adverb
[System.ComponentModel.Description("#")]
Hash,
[System.ComponentModel.Description("$")]
Dollar,
[System.ComponentModel.Description("''")]
DoubleTick,
[System.ComponentModel.Description("(")]
LeftParenth,
[System.ComponentModel.Description(")")]
RightParenth,
[System.ComponentModel.Description(",")]
Comma,
[System.ComponentModel.Description(".")]
Period,
[System.ComponentModel.Description(":")]
Colon,
[System.ComponentModel.Description("``")]
DoubleBackTick,
};
The first method for dealing with this is slow, and is based on suggestions I saw here and around the net. It's slow because we are reflecting for every conversion:
using System;
using System.Collections.Generic;
namespace CustomExtensions
{
/// <summary>
/// uses extension methods to convert enums with hypens in their names to underscore and other variants
public static class EnumExtensions
{
/// <summary>
/// Gets the description string, if available. Otherwise returns the name of the enum field
/// LthWrapper.POS.Dollar.GetString() yields "$", an impossible control character for enums
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string GetStringSlow(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
System.Reflection.FieldInfo field = type.GetField(name);
if (field != null)
{
System.ComponentModel.DescriptionAttribute attr =
Attribute.GetCustomAttribute(field,
typeof(System.ComponentModel.DescriptionAttribute)) as System.ComponentModel.DescriptionAttribute;
if (attr != null)
{
//return the description if we have it
name = attr.Description;
}
}
}
return name;
}
/// <summary>
/// Converts a string to an enum field using the string first; if that fails, tries to find a description
/// attribute that matches.
/// "$".ToEnum<LthWrapper.POS>() yields POS.Dollar
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static T ToEnumSlow<T>(this string value) //, T defaultValue)
{
T theEnum = default(T);
Type enumType = typeof(T);
//check and see if the value is a non attribute value
try
{
theEnum = (T)Enum.Parse(enumType, value);
}
catch (System.ArgumentException e)
{
bool found = false;
foreach (T enumValue in Enum.GetValues(enumType))
{
System.Reflection.FieldInfo field = enumType.GetField(enumValue.ToString());
System.ComponentModel.DescriptionAttribute attr =
Attribute.GetCustomAttribute(field,
typeof(System.ComponentModel.DescriptionAttribute)) as System.ComponentModel.DescriptionAttribute;
if (attr != null && attr.Description.Equals(value))
{
theEnum = enumValue;
found = true;
break;
}
}
if( !found )
throw new ArgumentException("Cannot convert " + value + " to " + enumType.ToString());
}
return theEnum;
}
}
}
The problem with this is that you're doing reflection every time. I haven't measured the performance hit from doing so, but it seems alarming. Worse we are computing these expensive conversions repeatedly, without caching them.
Instead we can use a static constructor to populate some dictionaries with this conversion information, then just look up this information when needed. Apparently static classes (required for extension methods) can have constructors and fields :)
using System;
using System.Collections.Generic;
namespace CustomExtensions
{
/// <summary>
/// uses extension methods to convert enums with hypens in their names to underscore and other variants
/// I'm not sure this is a good idea. While it makes that section of the code much much nicer to maintain, it
/// also incurs a performance hit via reflection. To circumvent this, I've added a dictionary so all the lookup can be done once at
/// load time. It requires that all enums involved in this extension are in this assembly.
/// </summary>
public static class EnumExtensions
{
//To avoid collisions, every Enum type has its own hash table
private static readonly Dictionary<Type, Dictionary<object,string>> enumToStringDictionary = new Dictionary<Type,Dictionary<object,string>>();
private static readonly Dictionary<Type, Dictionary<string, object>> stringToEnumDictionary = new Dictionary<Type, Dictionary<string, object>>();
static EnumExtensions()
{
//let's collect the enums we care about
List<Type> enumTypeList = new List<Type>();
//probe this assembly for all enums
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
Type[] exportedTypes = assembly.GetExportedTypes();
foreach (Type type in exportedTypes)
{
if (type.IsEnum)
enumTypeList.Add(type);
}
//for each enum in our list, populate the appropriate dictionaries
foreach (Type type in enumTypeList)
{
//add dictionaries for this type
EnumExtensions.enumToStringDictionary.Add(type, new Dictionary<object,string>() );
EnumExtensions.stringToEnumDictionary.Add(type, new Dictionary<string,object>() );
Array values = Enum.GetValues(type);
//its ok to manipulate 'value' as object, since when we convert we're given the type to cast to
foreach (object value in values)
{
System.Reflection.FieldInfo fieldInfo = type.GetField(value.ToString());
//check for an attribute
System.ComponentModel.DescriptionAttribute attribute =
Attribute.GetCustomAttribute(fieldInfo,
typeof(System.ComponentModel.DescriptionAttribute)) as System.ComponentModel.DescriptionAttribute;
//populate our dictionaries
if (attribute != null)
{
EnumExtensions.enumToStringDictionary[type].Add(value, attribute.Description);
EnumExtensions.stringToEnumDictionary[type].Add(attribute.Description, value);
}
else
{
EnumExtensions.enumToStringDictionary[type].Add(value, value.ToString());
EnumExtensions.stringToEnumDictionary[type].Add(value.ToString(), value);
}
}
}
}
public static string GetString(this Enum value)
{
Type type = value.GetType();
string aString = EnumExtensions.enumToStringDictionary[type][value];
return aString;
}
public static T ToEnum<T>(this string value)
{
Type type = typeof(T);
T theEnum = (T)EnumExtensions.stringToEnumDictionary[type][value];
return theEnum;
}
}
}
Look how tight the conversion methods are now. The only flaw I can think of is that this requires all the converted enums to be in the current assembly. Also, I only bother with exported enums, but you could change that if you wish.
This is how to call the methods
string x = LthWrapper.POS.Dollar.GetString();
LthWrapper.POS y = "PRP$".ToEnum<LthWrapper.POS>();
@Shane Arney
performSelector:withObject:withObject:
You might also want to mention that this method is only for passing maximum 2 arguments, and it cannot be delayed. (such as performSelector:withObject:afterDelay:)
.
kinda weird that apple only supports 2 objects to be send and didnt make it more generic.
I found this nugget at the link following. It worked perfect for me and only took 5 seconds.
As of VirtualBox 4 they added support for expansion.
VBoxManage modifyhd filename.vdi --resize 46080
That will resize a virtual disk image to 45GB.
https://superuser.com/questions/172651/increasing-disk-space-on-virtualbox
if you are using 3.6 try this
k = 250
print(f"User pressed the: {k}")
Output: User pressed the: 250
If your url in PHP like http://yourdomain.com/demo.php than comes like http://yourdomain.com/demo
This is all you need:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteRule ^([^\.]+)$ $1.html [NC,L]
RewriteRule ^([^\.]+)$ $1.php [NC,L]
Try
var marker = new google.maps.Marker({
position: map.getCenter(),
icon: 'http://imageshack.us/a/img826/9489/x1my.png',
map: map
});
from here
https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom
In C++20 we'll finally get std::set::contains
method.
#include <iostream>
#include <string>
#include <set>
int main()
{
std::set<std::string> example = {"Do", "not", "panic", "!!!"};
if(example.contains("panic")) {
std::cout << "Found\n";
} else {
std::cout << "Not found\n";
}
}
There are MANY reasons to use brace initialization, but you should be aware that the initializer_list<>
constructor is preferred to the other constructors, the exception being the default-constructor. This leads to problems with constructors and templates where the type T
constructor can be either an initializer list or a plain old ctor.
struct Foo {
Foo() {}
Foo(std::initializer_list<Foo>) {
std::cout << "initializer list" << std::endl;
}
Foo(const Foo&) {
std::cout << "copy ctor" << std::endl;
}
};
int main() {
Foo a;
Foo b(a); // copy ctor
Foo c{a}; // copy ctor (init. list element) + initializer list!!!
}
Assuming you don't encounter such classes there is little reason not to use the intializer list.
pt is a derivation (abbreviation) of "point" which historically was used in print type faces where the size was commonly "measured" in "points" where 1 point has an approximate measurement of 1/72 of an inch, and thus a 72 point font would be 1 inch in size.
px is an abbreviation for "pixel" which is a simple "dot" on either a screen or a dot matrix printer or other printer or device which renders in a dot fashion - as opposed to old typewriters which had a fixed size, solid striker which left an imprint of the character by pressing on a ribbon, thus leaving an image of a fixed size.
Closely related to point are the terms "uppercase" and "lowercase" which historically had to do with the selection of the fixed typographical characters where the "captital" characters where placed in a box (case) above the non-captitalized characters which were place in a box below, and thus the "lower" case.
There were different boxes (cases) for different typographical fonts and sizes, but still and "upper" and "lower" case for each of those.
Another term is the "pica" which is a measure of one character in the font, thus a pica is 1/6 of an inch or 12 point units of measure (12/72) of measure.
Strickly speaking the measurement is on computers 4.233mm or 0.166in whereas the old point (American) is 1/72.27 of an inch and French is 4.512mm (0.177in.). Thus my statement of "approximate" regarding the measurements.
Further, typewriters as used in offices, had either and "Elite" or a "Pica" size where the size was 10 and 12 characters per inch repectivly.
Additionally, the "point", prior to standardization was based on the metal typographers "foot" size, the size of the basic footprint of one character, and varied somewhat in size.
Note that a typographical "foot" was originally from a deceased printers actual foot. A typographic foot contains 72 picas or 864 points.
As to CSS use, I prefer to use EM rather than px or pt, thus gaining the advantage of scaling without loss of relative location and size.
EDIT: Just for completeness you can think of EM (em) as an element of measure of one font height, thus 1em for a 12pt font would be the height of that font and 2em would be twice that height. Note that for a 12px font, 2em is 24 pixels. SO 10px is typically 0.63em of a standard font as "most" browsers base on 16px = 1em as a standard font size.
Here is how I do it in 2018. Who knows, maybe an R newbie will see it one day and fall in love with ggplot2
.
library(ggplot2)
ggplot(data = iris, aes(Petal.Length, Petal.Width, color = Species)) +
geom_point() +
scale_color_manual(values = c("setosa" = "red", "versicolor" = "blue", "virginica" = "yellow"))
Yes, that is fine. $_POST
is just another variable, except it has (super)global scope.
$_POST = array();
...will be quite enough. The loop is useless. It's probably best to keep it as an array rather than unset it, in case other files are attempting to read it and assuming it is an array.
You don't have to always use ul
elements to achieve that, you can use other elements too as seen below. Here there are 2 examples, one using div
and one using select
.
This examples demonstrates the basic functionality, but can be extended/enriched more. It is tested in linux only (iceweasel and chrome).
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<style>
.drop_container
{
position:relative;
float:left;
}
.always_visible
{
background-color:#FAFAFA;
color:#333333;
font-weight:bold;
cursor:pointer;
border:2px silver solid;
margin:0px;
margin-right:5px;
font-size:14px;
font-family:"Times New Roman", Times, serif;
}
.always_visible:hover + .hidden_container
{
display:block;
position:absolute;
color:green;
}
.hidden_container
{
display:none;
border:1px gray solid;
left:0px;
background-color:#FAFAFA;
padding:5px;
z-index:1;
}
.hidden_container:hover
{
display:block;
position:absolute;
}
.link
{
color:blue;
white-space:nowrap;
margin:3px;
display:block;
}
.link:hover
{
color:white;
background-color:blue;
}
.line_1
{
width:800px;
border:1px tomato solid;
padding:5px;
}
</style>
</head>
<body>
<div class="line_1">
<div class="drop_container">
<select class="always_visible" disabled><option>Select</option></select>
<div class="hidden_container">
<a href="http://www.google.gr" class="link">Option_ 1</a>
<a href="http://www.google.gr" class="link">Option__ 2</a>
<a href="http://www.google.gr" class="link">Option___ 3</a>
<a href="http://www.google.gr" class="link">Option____ 4</a>
</div>
</div>
<div class="drop_container">
<select class="always_visible" disabled><option>Select</option></select>
<div class="hidden_container">
<a href="http://www.google.gr" class="link">____1</a>
<a href="http://www.google.gr" class="link">___2</a>
<a href="http://www.google.gr" class="link">__3</a>
<a href="http://www.google.gr" class="link">_4</a>
</div>
</div>
<div style="clear:both;"></div>
</div>
<br>
<div class="line_1">
<div class="drop_container">
<div class="always_visible">Select___</div>
<div class="hidden_container">
<a href="http://www.google.gr" class="link">Option_ 1</a>
<a href="http://www.google.gr" class="link">Option__ 2</a>
<a href="http://www.google.gr" class="link">Option___ 3</a>
<a href="http://www.google.gr" class="link">Option____ 4</a>
</div>
</div>
<div class="drop_container">
<div class="always_visible">Select___</div>
<div class="hidden_container">
<a href="http://www.google.gr" class="link">Option_ 1</a>
<a href="http://www.google.gr" class="link">Option__ 2</a>
<a href="http://www.google.gr" class="link">Option___ 3</a>
<a href="http://www.google.gr" class="link">Option____ 4</a>
</div>
</div>
<div style="clear:both;"></div>
</div>
</body>
</html>
I don't understand how other answers don't answer the original question about how to use PHP (not very consistent with the title).
PHP files or PHP code embedded in HTML code start always with the tag <?php
and ends with ?>
.
You can embed PHP code inside HTML like this (you have to save the file using .php
extension to let PHP server recognize and process it, ie: index.php):
<body>
<?php echo "<div>Hello World!</div>" ?>
</body>
or you can use a whole php file, ie: test.php:
<?php
$mycontent = "Hello World!";
echo "<div>$mycontent</div>";
?> // is not mandatory to put this at the end of the file
there's no document.ready
in PHP, the scripts are processed when they are invoked from the browser or from another PHP file.
if you can, use flexbox:
<ul>
<li>HOME</li>
<li>ABOUT US</li>
<li>SERVICES</li>
<li>PREVIOUS PROJECTS</li>
<li>TESTIMONIALS</li>
<li>NEWS</li>
<li>RESEARCH & DEV</li>
<li>CONTACT</li>
</ul>
ul {
display: flex;
justify-content:space-between;
list-style-type: none;
}
jsfiddle: http://jsfiddle.net/RAaJ8/
Browser support is actually quite good (with prefixes an other nasty stuff): http://caniuse.com/flexbox
Modify your log4j.properties
file accordingly:
log4j.rootLogger=TRACE,stdout
...
log4j.logger.debugLog=TRACE,debugLog
log4j.logger.reportsLog=DEBUG,reportsLog
Change the log levels for each logger depending to your needs.
One very simple way to make a method asynchronous is to use Task.Yield() method. As MSDN states:
You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.
Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.
private async Task<DateTime> CountToAsync(int num = 1000)
{
await Task.Yield();
for (int i = 0; i < num; i++)
{
Console.WriteLine("#{0}", i);
}
return DateTime.Now;
}
((EditText) findViewById(R.id.User)).setText("");
((EditText) findViewById(R.id.Password)).setText("");
set print elements 0
set print elements
number-of-elements
Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the set print elements
command. This limit also applies to the display of strings. When GDB starts, this limit is set to 200. Setting number-of-elements to zero means that the printing is unlimited.
If you doing from windows folder, I mean if you are using the kafka from windows machine
kafka-console-consumer.bat --bootstrap-server localhost:9092 --<topic-name> test --from-beginning
Change the axis_colour to match the background and if you are modifying the background dynamically you will need to update the axis_colour simultaneously. * The shared picture shows the graph/plot example using mock data ()
### Main Plotting Function ###
plotXY <- function(time, value){
### Plot Style Settings ###
### default bg is white, set it the same as the axis-colour
background <- "white"
### default col.axis is black, set it the same as the background to match
axis_colour <- "white"
plot_title <- "Graph it!"
xlabel <- "Time"
ylabel <- "Value"
label_colour <- "black"
label_scale <- 2
axis_scale <- 2
symbol_scale <- 2
title_scale <- 2
subtitle_scale <- 2
# point style 16 is a black dot
point <- 16
# p - points, l - line, b - both
plot_type <- "b"
plot(time, value, main=plot_title, cex=symbol_scale, cex.lab=label_scale, cex.axis=axis_scale, cex.main=title_scale, cex.sub=subtitle_scale, xlab=xlabel, ylab=ylabel, col.lab=label_colour, col.axis=axis_colour, bg=background, pch=point, type=plot_type)
}
plotXY(time, value)
There is no magic method that will do what you want. The answer is simply name it appropriately. asdict
is a reasonable choice for a plain conversion to dict
, inspired primarily by namedtuple
. However, your method will obviously contain special logic that might not be immediately obvious from that name; you are returning only a subset of the class' state. If you can come up with with a slightly more verbose name that communicates the concepts clearly, all the better.
Other answers suggest using __iter__
, but unless your object is truly iterable (represents a series of elements), this really makes little sense and constitutes an awkward abuse of the method. The fact that you want to filter out some of the class' state makes this approach even more dubious.
Is $target.remove();
what you're looking for?
Personally, I prefer the simple modulo operation solution in the accepted answer. Unfortunately, SonarQube doesn't like equality tests with floating points without setting a round precision. So we have tried to find a more compliant solution. Here it is:
if (new BigDecimal(decimalValue).remainder(new BigDecimal(1)).equals(BigDecimal.ZERO)) {
// no decimal places
} else {
// decimal places
}
Remainder(BigDecimal)
returns a BigDecimal
whose value is (this % divisor)
. If this one's equal to zero, we know there is no floating point.
Python 3.x:
small greek letters are coded from 945 to 969
so,alpha is chr(945)
, omega is chr(969)
so just type
print(chr(945))
the list of small greek letters in a list:
greek_letterz=[chr(code) for code in range(945,970)]
print(greek_letterz)
And now, alpha is greek_letterz[0]
, beta is greek_letterz[1]
, a.s.o
$routeProvider
.when('/main' , {templateUrl: 'partials/main.html', controller: MainController})
.when('/login', {templateUrl: 'partials/login.html', controller: LoginController}).
.when('/login', {templateUrl: 'partials/index.html', controller: IndexController})
.otherwise({redirectTo: '/index'});
List All:
SHOW FULL PROCESSLIST
if you want to kill a hang transaction copy transaction id and kill transaction by using this command:
KILL <id> // e.g KILL 16543
just use onkeydown="return false" to the control tag like shown below, it will not accept values from user.
<asp:TextBox ID="txtDate" runat="server" AutoPostBack="True"
ontextchanged="txtDate_TextChanged" onkeydown="return false" >
</asp:TextBox>
It's not a matter of deep copy or shallow copy, none of what you're doing is deep copy.
Here:
>>> new = original
you're creating a new reference to the the list/dict referenced by original.
while here:
>>> new = original.copy()
>>> # or
>>> new = list(original) # dict(original)
you're creating a new list/dict which is filled with a copy of the references of objects contained in the original container.