This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT
time! if it does not get any signal it throw exception! It means that time expired!
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class SocketTest extends Thread {
private ServerSocket serverSocket;
public SocketTest() throws IOException {
serverSocket = new ServerSocket(8008);
serverSocket.setSoTimeout(10000);
}
public void run() {
while (true) {
try {
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket client = serverSocket.accept();
System.out.println("Just connected to " + client.getRemoteSocketAddress());
client.close();
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) {
try {
Thread t = new SocketTest();
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I ran into this problem with a particular webpage I was maintaining. No matter what settings I changed, it kept going back to IE8 compatibility mode.
It turned out X-UA-Compatible
was set in the metadata in the head:
<meta http-equiv="X-UA-Compatible" content="IE=8" >
As I later discovered, and at least in Internet Explorer 11, you can see where it gets its "document mode" from, by going into developer tools (F12), then selecting the tab "Emulation", and checking the text below the drop down "Document mode".
Since we only support IE11 and higher, and Microsoft says document modes are deprecated, I just threw the whole thing out. That solved it.
In case anyone still looking for a solution. This worked for me.
Python adds the folder containing the script you launch to the PYTHONPATH, so if you run
python application/app2/some_folder/some_file.py
Only the folder application/app2/some_folder is added to the path (not the base dir that you're executing the command in). Instead, run your file as a module and add a __init__.py in your some_folder directory.
python -m application.app2.some_folder.some_file
This will add the base dir to the python path, and then classes will be accessible via a non-relative import.
Many ways to do this. ismember is the first that comes to mind, since it is a set membership action you wish to take. Thus
X = primes(20);
ismember([15 17],X)
ans =
0 1
Since 15 is not prime, but 17 is, ismember has done its job well here.
Of course, find (or any) will also work. But these are not vectorized in the sense that ismember was. We can test to see if 15 is in the set represented by X, but to test both of those numbers will take a loop, or successive tests.
~isempty(find(X == 15))
~isempty(find(X == 17))
or,
any(X == 15)
any(X == 17)
Finally, I would point out that tests for exact values are dangerous if the numbers may be true floats. Tests against integer values as I have shown are easy. But tests against floating point numbers should usually employ a tolerance.
tol = 10*eps;
any(abs(X - 3.1415926535897932384) <= tol)
There is an elegant way to do this. If you are using Resource Controllers, your link to edit your record will look like this:
/users/{user}/edit OR /users/1/edit
And in your UserRequest, the rule should be like this :
public function rules()
{
return [
'name' => [
'required',
'unique:users,name,' . $this->user
],
];
}
Or if your link to edit your record look like this:
/users/edit/1
You can try this also:
public function rules()
{
return [
'name' => [
'required',
'unique:users,name,' . $this->id
],
];
}
If you have data already present in both the tables and you want to update a table column values based on some condition then use this
UPDATE Table1 set Name=(select t2.Name from Table2 t2 where t2.id=Table1.id)
KeyboardInterrupt and signals are only seen by the process (ie the main thread)... Have a look at Ctrl-c i.e. KeyboardInterrupt to kill threads in python
This could be because your CSV file has embedded single or double quotes. If your CSV file is tab-delimited try opening it as:
c = csv.reader(f, delimiter='\t', quoting=csv.QUOTE_NONE)
If ctrl+c doesn't respond right away because your script is too long/complex, hold it.
The break command doesn't run when matlab is executing some of its deeper scripts, and either it won't log a ctrl sequence in the buffer, or it clears the buffer just before or just after it completes those pieces of code. In either case, when matlab returns to execute more of your script, it will recognize that you are holding ctrl+c and terminate.
For longer running programs, I usually try to find a good place to provide a status update and I always accompany that with some measure of time using tic and toc. Depending on what I am doing, I might use run time, segment time, some kind of average, etc...
For really long running programs, I found this to be exceptionally useful http://www.mathworks.com/matlabcentral/fileexchange/16649-send-text-message-to-cell-phone/content/send_text_message.m
but it looks like they have some newer functions for this too.
you can simply use react-native-rename npm package.
Install using
npm install react-native-rename -g
Then from the root of your React Native project execute the following
react-native-rename "MyApp" -b com.mycompany.myapp
react-native-rename on npm
but notice that, this lib remove your MainActivity.java
and MainApplication.java
.
before changing your package name, give a backup from this two file and, after changing package name just put it back to their place. this solution work for me
more info: react-native-rename
I think I found the proper way to do it...
// Create a DOM Text node:
var text_node = document.createTextNode(unescaped_text);
// Get the HTML element where you want to insert the text into:
var elem = document.getElementById('msg_span');
// Optional: clear its old contents
//elem.innerHTML = '';
// Append the text node into it:
elem.appendChild(text_node);
If the class implements the method directly, it will not use the traits version. Perhaps what you are thinking of is:
trait A {
function calc($v) {
return $v+1;
}
}
class MyClass {
function calc($v) {
return $v+2;
}
}
class MyChildClass extends MyClass{
}
class MyTraitChildClass extends MyClass{
use A;
}
print (new MyChildClass())->calc(2); // will print 4
print (new MyTraitChildClass())->calc(2); // will print 3
Because the child classes do not implement the method directly, they will first use that of the trait if there otherwise use that of the parent class.
If you want, the trait can use method in the parent class (assuming you know the method would be there) e.g.
trait A {
function calc($v) {
return parent::calc($v*3);
}
}
// .... other code from above
print (new MyTraitChildClass())->calc(2); // will print 8 (2*3 + 2)
You can also provide for ways to override, but still access the trait method as follows:
trait A {
function trait_calc($v) {
return $v*3;
}
}
class MyClass {
function calc($v) {
return $v+2;
}
}
class MyTraitChildClass extends MyClass{
use A {
A::trait_calc as calc;
}
}
class MySecondTraitChildClass extends MyClass{
use A {
A::trait_calc as calc;
}
public function calc($v) {
return $this->trait_calc($v)+.5;
}
}
print (new MyTraitChildClass())->calc(2); // will print 6
echo "\n";
print (new MySecondTraitChildClass())->calc(2); // will print 6.5
You can see it work at http://sandbox.onlinephpfunctions.com/code/e53f6e8f9834aea5e038aec4766ac7e1c19cc2b5
if is there only one Top-Level Container then last lines in GUI constructor would be for example
.
.
.
myFrame.setVisible(true);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
myComponent.grabFocus();
myComponent.requestFocus();//or inWindow
}
});
private AdapterView.OnItemClickListener onItemClickListener;
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
.......
final View view = convertView;
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(null, view, position, -1);
}
}
});
return convertView;
}
public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
Then in your activity, use adapter.setOnItemClickListener() before attaching it to the listview.
Worked for me after replacing
SparkConf sparkConf = new SparkConf().setAppName("SOME APP NAME");
with
SparkConf sparkConf = new SparkConf().setAppName("SOME APP NAME").setMaster("local[2]").set("spark.executor.memory","1g");
Found this solution on some other thread on stackoverflow.
Because autocomplete="off" does not work for password fields, one must rely on javascript. Here's a simple solution based on answers found here.
Add the attribute data-password-autocomplete="off" to your password field:
<input type="password" data-password-autocomplete="off">
Include the following JS:
$(function(){
$('[data-password-autocomplete="off"]').each(function() {
$(this).prop('type', 'text');
$('<input type="password"/>').hide().insertBefore(this);
$(this).focus(function() {
$(this).prop('type', 'password');
});
});
});
This solution works for both Chrome and FF.
Try to use datepicker/ timepicker instead of datetimepicker like:
replace:
$('#datetimepicker1').datetimepicker();
with:
$('#datetimepicker1').datepicker(); // or timepicker for time picker
IMO, it's better to use the install
command in such situations. I was trying to make systemd-journald
persistent across reboots.
install -d -g systemd-journal -m 2755 -v /var/log/journal
As addition to the other answers, in a cpanel installation, the mysql root password is stored in a file named /root/.my.cnf
. (and the cpanel service resets it back on change, so the other answers here won't help)
<Resource>
tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
global="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"
username="root"
password=""
maxActive="10"
maxIdle="10"
minIdle="5"
maxWait="10000"/>
<ResourceLink>
inside the <Context>
tag.<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource" />
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>
Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->
There are libraries that do charset conversion in Javascript. But if you want something simple, this function does approximately what you want:
function stringToBytes(text) {
const length = text.length;
const result = new Uint8Array(length);
for (let i = 0; i < length; i++) {
const code = text.charCodeAt(i);
const byte = code > 255 ? 32 : code;
result[i] = byte;
}
return result;
}
If you want to convert the resulting byte array into a Blob, you would do something like this:
const originalString = 'ååå';
const bytes = stringToBytes(originalString);
const blob = new Blob([bytes.buffer], { type: 'text/plain; charset=ISO-8859-1' });
Now, keep in mind that some apps do accept UTF-8 encoding, but they can't guess the encoding unless you prepend a BOM character, as explained here.
If you are using jQuery you can easily check the type of any element.
function(elementID){
var type = $(elementId).attr('type');
if(type == "text") //inputBox
console.log("input text" + $(elementId).val().size());
}
similarly you can check the other types and take appropriate action.
In response to your first question: Yes, you have to run a server app to send the messages, as well as a client app to receive them.
In response to your second question: Yes, every application needs its own API key. This key is for your server app, not the client.
Use percent encoding. Modern browsers will take care of display & paste issues and make it human-readable. E. g. http://ko.wikipedia.org/wiki/????:??
Edit: when you copy such an url in Firefox, the clipboard will hold the percent-encoded form (which is usually a good thing), but if you copy only a part of it, it will remain unencoded.
go to your project directory in CMD, and run the following commands. You can use the visual studio code terminal also.
ng generate component "component_name"
OR
ng g c "component_name"
a new folder with "component_name"
will be created
component_name/component_name.component.html component_name/component_name.component.spec.ts component_name/component_name.component.ts component_name/component_name.component.css
new component will be Automatically added module.
you can avoid creating spec file by following command
ng g c "component_name" --nospec
Your server configuration settings allows users to upload files upto 16MB (because you have set upload_max_filesize = 16Mb) but the post_max_size accepts post data upto 8MB only. This is why it throws an error.
Quoted from the official PHP site:
To upload large files, post_max_size value must be larger than upload_max_filesize.
memory_limit should be larger than post_max_size
You should always set your post_max_size value greater than the upload_max_filesize value.
ping (ICMP protocol) and ssh are two different protocols.
It could be that ssh service is not running or not installed
firewall restriction (local to server like iptables or even sshd config lock down ) or (external firewall that protects incomming traffic to network hosting 111.111.111.111)
First check is to see if ssh port is up
nc -v -w 1 111.111.111.111 -z 22
if it succeeds then ssh should communicate if not then it will never work until restriction is lifted or ssh is started
The MySQL function describe table should get you where you want to go (put your table name in for "table"). You'll have to parse the output some, but it's pretty easy. As I recall, if you execute that query, the PHP query result accessing functions that would normally give you a key-value pair will have the column names as the keys. But it's been a while since I used PHP so don't hold me to that. :)
This worked for me on win replace REL_PATH_TO_FILE with the relative path to the file to remove Removing sensitive data from a repository The docs say full path - but that errored for me -so I tried rel path and it worked.
<from the repo dir>git filter-branch --force --index-filter "git rm --cached --ignore-unmatch REL_PATH_TO_FILE" --prune-empty --tag-name-filter cat -- --all
This may have changed since the question was asked, but there is a difference between stopping an instance and terminating an instance.
If your instance is EBS-based, it can be stopped. It will remain in your account, but you will not be charged for it (you will continue to be charged for EBS storage associated with the instance and unused Elastic IP addresses). You can re-start the instance at any time.
If the instance is terminated, it will be deleted from your account. You’ll be charged for any remaining EBS volumes, but by default the associated EBS volume will be deleted. This can be configured when you create the instance using the command-line EC2 API Tools.
I had the same problem now with testing code. That was caused in spring boot because of the @RunWith
annotation. I have used:
@RunWith(SpringRunner.class)
With that annotation there is JUnit Vintage running which can't find any tests and gives you the error. I have removed that and only JUnit Jupiter is running and everything is fine.
You can also use String.format("%3.3s", "abcdefgh")
. The first digit is the minimum length (the string will be left padded if it's shorter), the second digit is the maxiumum length and the string will be truncated if it's longer. So
System.out.printf("'%3.3s' '%3.3s'", "abcdefgh", "a");
will produce
'abc' ' a'
(you can remove quotes, obviously).
Found this good site https://stefancosma.xyz/2018/10/01/how-to-use-tomcat-intellij-idea-community/ All credits to the author
You can use getContent() method on Request object.
$request->getContent() //json as a string.
Basically my code sends data to the next page like so:
**Referring Page**
$this = $_SERVER['PHP_SELF'];
echo "<a href='next_page.php?prev=$this'>Next Page</a>";
**Page with button**
$prev = $_GET['prev'];
echo "<a href='$prev'><button id='back'>Back</button></a>";
According to the ant manual, setting JAVA_HOME should work - are you sure the changed setting is visible to ant?
Alternatively, you could use the JAVACMD variable.
To reduce the risk you can also associate the originating IP with the session. That way an attacker has to be within the same private network to be able to use the session.
Checking referer headers can also be an option but those are more easily spoofed.
I had the same problem. I used a trigger and in that trigger I called a procedure which computed some values into 2 OUT variables. When I tried to print the result in the trigger body, nothing showed on screen. But then I solved this problem by making 2 local variables in a function, computed what I need with them and finally, copied those variables in your OUT procedure variables. I hope it'll be useful and successful!
you could use replaceAll instead of remove and append replaceAll
This should work:
// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
/* utf.js - UTF-8 <=> UTF-16 convertion
*
* Copyright (C) 1999 Masanao Izumo <[email protected]>
* Version: 1.0
* LastModified: Dec 25 1999
* This library is free. You can redistribute it and/or modify it.
*/
function Utf8ArrayToStr(array) {
var out, i, len, c;
var char2, char3;
out = "";
len = array.length;
i = 0;
while(i < len) {
c = array[i++];
switch(c >> 4)
{
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
// 0xxxxxxx
out += String.fromCharCode(c);
break;
case 12: case 13:
// 110x xxxx 10xx xxxx
char2 = array[i++];
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = array[i++];
char3 = array[i++];
out += String.fromCharCode(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
break;
}
}
return out;
}
It's somewhat cleaner as the other solutions because it doesn't use any hacks nor depends on Browser JS functions, e.g. works also in other JS environments.
Check out the JSFiddle demo.
when a developer use an initializer block, the Java Compiler copies the initializer into each constructor of the current class.
Example:
the following code:
class MyClass {
private int myField = 3;
{
myField = myField + 2;
//myField is worth 5 for all instance
}
public MyClass() {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
}
public MyClass(int _myParam) {
if (_myParam > 0) {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
//if _myParam is greater than 0
} else {
myField = myField + 5;
//myField is worth 10 for all instance initialized with this construtor
//if _myParam is lower than 0 or if _myParam is worth 0
}
}
public void setMyField(int _myField) {
myField = _myField;
}
public int getMyField() {
return myField;
}
}
public class MainClass{
public static void main(String[] args) {
MyClass myFirstInstance_ = new MyClass();
System.out.println(myFirstInstance_.getMyField());//20
MyClass mySecondInstance_ = new MyClass(1);
System.out.println(mySecondInstance_.getMyField());//20
MyClass myThirdInstance_ = new MyClass(-1);
System.out.println(myThirdInstance_.getMyField());//10
}
}
is equivalent to:
class MyClass {
private int myField = 3;
public MyClass() {
myField = myField + 2;
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
}
public MyClass(int _myParam) {
myField = myField + 2;
if (_myParam > 0) {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
//if _myParam is greater than 0
} else {
myField = myField + 5;
//myField is worth 10 for all instance initialized with this construtor
//if _myParam is lower than 0 or if _myParam is worth 0
}
}
public void setMyField(int _myField) {
myField = _myField;
}
public int getMyField() {
return myField;
}
}
public class MainClass{
public static void main(String[] args) {
MyClass myFirstInstance_ = new MyClass();
System.out.println(myFirstInstance_.getMyField());//20
MyClass mySecondInstance_ = new MyClass(1);
System.out.println(mySecondInstance_.getMyField());//20
MyClass myThirdInstance_ = new MyClass(-1);
System.out.println(myThirdInstance_.getMyField());//10
}
}
I hope my example is understood by developers.
This works well for coping entire records.
UPDATE your_table
SET new_field = sourse_field
Guava also provides such function which will return an Optional
if an enum cannot be found.
Enums.getIfPresent(MyEnum.class, id).toJavaUtil()
.orElseThrow(()-> new RuntimeException("Invalid enum blah blah blah.....")))
When you aren't sure which syntax to choose, especially when there doesn't seem to be much to separate the choices, consult a book on heuristics. As far as I know, the only heuristics book for SQL is 'Joe Celko's SQL Programming Style':
A correlation name is more often called an alias, but I will be formal. In SQL-92, they can have an optional
AS
operator, and it should be used to make it clear that something is being given a new name. [p16]
This way, if your team doesn't like the convention, you can blame Celko -- I know I do ;)
UPDATE 1: IIRC for a long time, Oracle did not support the AS
(preceding correlation name) keyword, which may explain why some old timers don't use it habitually.
UPDATE 2: the term 'correlation name', although used by the SQL Standard, is inappropriate. The underlying concept is that of a ‘range variable’.
UPDATE 3: I just re-read what Celko wrote and he is wrong: the table is not being renamed! I now think:
A correlation name is more often called an alias, but I will be formal. In Standard SQL they can have an optional
AS
keyword but it should not be used because it may give the impression that something is being renamed when it is not. In fact, it should be omitted to enforce the point that it is a range variable.
Answer: 165
Method: brute-force! Here is a tiny bit of Python (version 2.7) code to count'em all.
from math import sqrt, floor
is_ps = lambda x: floor(sqrt(x)) ** 2 == x
count = 0
for n in range(1002, 10000, 3):
if n % 11 and is_ps(sum(map(int, str(n)))):
count += 1
print "#%i: %s" % (count, n)
ES6 of the day here;
const json_getAllKeys = data => (
data.reduce((keys, obj) => (
keys.concat(Object.keys(obj).filter(key => (
keys.indexOf(key) === -1))
)
), [])
)
And yes it can be written in very long one line;
const json_getAllKeys = data => data.reduce((keys, obj) => keys.concat(Object.keys(obj).filter(key => keys.indexOf(key) === -1)), [])
EDIT: Returns all first order keys if the input is of type array of objects
.click
events only work when element gets rendered and are only attached to elements loaded when the DOM is ready.
.on
events are dynamically attached to DOM elements, which is helpful when you want to attach an event to DOM elements that are rendered on ajax request or something else (after the DOM is ready).
HTML is in its basic form just XML. You could Parse your text in an XmlDocument object, and on the root element call InnerText to extract the text. This will strip all HTML tages in any form and also deal with special characters like < all in one go.
Adding answer as this was the top hit when searching for "drop multiple columns in r":
The general version of the single column removal, e.g df$column1 <- NULL
, is to use list(NULL)
:
df[ ,c('column1', 'column2')] <- list(NULL)
This also works for position index as well:
df[ ,c(1,2)] <- list(NULL)
This is a more general drop and as some comments have mentioned, removing by indices isn't recommended. Plus the familiar negative subset (used in other answers) doesn't work for columns given as strings:
> iris[ ,-c("Species")]
Error in -"Species" : invalid argument to unary operator
Well, in my case updating drivers, restarting Android Studio, restarting my phone, changing the USB mode or unplugging USB did not help.
Then I went to the dev settings in my phone, toggled the Dev. Mode off and back on, and it worked. AS was open and phone was plugged at the moment.
As of Notepad++ 6.9, the new Folder as Workspace feature can be used.
Folder as Workspace opens your folder(s) in a panel so you can browse folder(s) and open any file in Notepad++. Every changement in the folder(s) from outside will be synchronized in the panel. Usage: Simply drop 1 (or more) folder(s) in Notepad++.
This feature has the advantage of not showing your entire file system when just the working directory is needed. It also means you don't need plugins for it to work.
To inspect the error message and do something with it (with Python 3)...
try:
some_method()
except Exception as e:
if {value} in e.args:
{do something}
i tried it worked tnx @Anastasiosyal i want to share it on this thread.
I'm not positive how the input fields did not trigger when I emptied the fields. But I managed to trigger each required field individually using:
$(".setting-p input").bind("change", function () {
//Seven.NetOps.validateSettings(Seven.NetOps.saveSettings);
/*$.validator.unobtrusive.parse($('#saveForm'));*/
$('#NodeZoomLevel').valid();
$('#ZoomLevel').valid();
$('#CenterLatitude').valid();
$('#CenterLongitude').valid();
$('#NodeIconSize').valid();
$('#SaveDashboard').valid();
$('#AutoRefresh').valid();
});
here's my view
@using (Html.BeginForm("SaveSettings", "Settings", FormMethod.Post, new {id = "saveForm"}))
{
<div id="sevenRightBody">
<div id="mapMenuitemPanel" class="setingsPanelStyle" style="display: block;">
<div class="defaultpanelTitleStyle">Map Settings</div>
Customize the map view upon initial navigation to the map view page.
<p class="setting-p">@Html.LabelFor(x => x.NodeZoomLevel)</p>
<p class="setting-p">@Html.EditorFor(x => x.NodeZoomLevel) @Html.ValidationMessageFor(x => x.NodeZoomLevel)</p>
<p class="setting-p">@Html.LabelFor(x => x.ZoomLevel)</p>
<p class="setting-p">@Html.EditorFor(x => x.ZoomLevel) @Html.ValidationMessageFor(x => x.ZoomLevel)</p>
<p class="setting-p">@Html.LabelFor(x => x.CenterLatitude)</p>
<p class="setting-p">@Html.EditorFor(x => x.CenterLatitude) @Html.ValidationMessageFor(x => x.CenterLatitude)</p>
<p class="setting-p">@Html.LabelFor(x => x.CenterLongitude)</p>
<p class="setting-p">@Html.EditorFor(x => x.CenterLongitude) @Html.ValidationMessageFor(x => x.CenterLongitude)</p>
<p class="setting-p">@Html.LabelFor(x => x.NodeIconSize)</p>
<p class="setting-p">@Html.SliderSelectFor(x => x.NodeIconSize) @Html.ValidationMessageFor(x => x.NodeIconSize)</p>
</div>
and my Entity
public class UserSetting : IEquatable<UserSetting>
{
[Required(ErrorMessage = "Missing Node Zoom Level.")]
[Range(200, 10000000, ErrorMessage = "Node Zoom Level must be between {1} and {2}.")]
[DefaultValue(100000)]
[Display(Name = "Node Zoom Level")]
public double NodeZoomLevel { get; set; }
[Required(ErrorMessage = "Missing Zoom Level.")]
[Range(200, 10000000, ErrorMessage = "Zoom Level must be between {1} and {2}.")]
[DefaultValue(1000000)]
[Display(Name = "Zoom Level")]
public double ZoomLevel { get; set; }
[Range(-90, 90, ErrorMessage = "Latitude degrees must be between {1} and {2}.")]
[Required(ErrorMessage = "Missing Latitude.")]
[DefaultValue(-200)]
[Display(Name = "Latitude")]
public double CenterLatitude { get; set; }
[Range(-180, 180, ErrorMessage = "Longitude degrees must be between {1} and {2}.")]
[Required(ErrorMessage = "Missing Longitude.")]
[DefaultValue(-200)]
[Display(Name = "Longitude")]
public double CenterLongitude { get; set; }
[Display(Name = "Save Dashboard")]
public bool SaveDashboard { get; set; }
.....
}
Using the join operator you can only perform equijoins. Other types of joins can be constructed using other operators. I'm not sure whether the exact join you are trying to do would be easier using these methods or by changing the where clause. Documentation on the join clause can be found here. MSDN has an article on join operations with multiple links to examples of other joins, as well.
If you know about Environment variables
and the system variable called path
, consider that any version of any binary which comes sooner, will be used as default.
Look at the image below, I have 3 different python versions but python 3.8
will be used as default since it came sooner than the other two. (In case of mentioned image, sooner means higher!)
With jQuery its just: $(this).blur();
Try this:
@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)
in your code should be,
@Html.ActionLink("Search", "List", "Search", new{@class="btn btn-info", @id="addressSearch"})
Once you have the packages setup, you'll need to create either an app.config or web.config and add something like the following:
<configuration>
<appSettings>
<add key="key" value="value"/>
</appSettings>
</configuration>
These regexes are equivalent (for matching purposes):
/^(7|8|9)\d{9}$/
/^[789]\d{9}$/
/^[7-9]\d{9}$/
The explanation:
(a|b|c)
is a regex "OR" and means "a or b or c", although the presence of brackets, necessary for the OR, also captures the digit. To be strictly equivalent, you would code (?:7|8|9)
to make it a non capturing group.
[abc]
is a "character class" that means "any character from a,b or c" (a character class may use ranges, e.g. [a-d]
= [abcd]
)
The reason these regexes are similar is that a character class is a shorthand for an "or" (but only for single characters). In an alternation, you can also do something like (abc|def)
which does not translate to a character class.
Using KeyGenerator
would be the preferred method. As Duncan indicated, I would certainly give the key size during initialization. KeyFactory
is a method that should be used for pre-existing keys.
OK, so lets get to the nitty-gritty of this. In principle AES keys can have any value. There are no "weak keys" as in (3)DES. Nor are there any bits that have a specific meaning as in (3)DES parity bits. So generating a key can be as simple as generating a byte array with random values, and creating a SecretKeySpec
around it.
But there are still advantages to the method you are using: the KeyGenerator
is specifically created to generate keys. This means that the code may be optimized for this generation. This could have efficiency and security benefits. It might be programmed to avoid a timing side channel attacks that would expose the key, for instance. Note that it may already be a good idea to clear any byte[]
that hold key information as they may be leaked into a swap file (this may be the case anyway though).
Furthermore, as said, not all algorithms are using fully random keys. So using KeyGenerator
would make it easier to switch to other algorithms. More modern ciphers will only accept fully random keys though; this is seen as a major benefit over e.g. DES.
Finally, and in my case the most important reason, it that the KeyGenerator
method is the only valid way of handling AES keys within a secure token (smart card, TPM, USB token or HSM). If you create the byte[]
with the SecretKeySpec
then the key must come from memory. That means that the key may be put in the secure token, but that the key is exposed in memory regardless. Normally, secure tokens only work with keys that are either generated in the secure token or are injected by e.g. a smart card or a key ceremony. A KeyGenerator
can be supplied with a provider so that the key is directly generated within the secure token.
As indicated in Duncan's answer: always specify the key size (and any other parameters) explicitly. Do not rely on provider defaults as this will make it unclear what your application is doing, and each provider may have its own defaults.
You can write this query to get column name and all details without using INFORMATION_SCHEMA in MySql :
SHOW COLUMNS FROM database_Name.table_name;
you can use RabbitMQ API to get count or messages :
/api/queues/vhost/name/get
Get messages from a queue. (This is not an HTTP GET as it will alter the state of the queue.) You should post a body looking like:
{"count":5,"requeue":true,"encoding":"auto","truncate":50000}
count controls the maximum number of messages to get. You may get fewer messages than this if the queue cannot immediately provide them.
requeue determines whether the messages will be removed from the queue. If requeue is true they will be requeued - but their redelivered flag will be set. encoding must be either "auto" (in which case the payload will be returned as a string if it is valid UTF-8, and base64 encoded otherwise), or "base64" (in which case the payload will always be base64 encoded). If truncate is present it will truncate the message payload if it is larger than the size given (in bytes). truncate is optional; all other keys are mandatory.
Please note that the publish / get paths in the HTTP API are intended for injecting test messages, diagnostics etc - they do not implement reliable delivery and so should be treated as a sysadmin's tool rather than a general API for messaging.
http://hg.rabbitmq.com/rabbitmq-management/raw-file/rabbitmq_v3_1_3/priv/www/api/index.html
Let avg be the list, then:
In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')
You can use %e
or %s
depending on your requirement.
Check out strptime in the time module. It is the inverse of strftime.
$ python
>>> import time
>>> my_time = time.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
time.struct_time(tm_year=2005, tm_mon=6, tm_mday=1,
tm_hour=13, tm_min=33, tm_sec=0,
tm_wday=2, tm_yday=152, tm_isdst=-1)
timestamp = time.mktime(my_time)
# convert time object to datetime
from datetime import datetime
my_datetime = datetime.fromtimestamp(timestamp)
# convert time object to date
from datetime import date
my_date = date.fromtimestamp(timestamp)
The Password Visibility Toggle feature has been added to support library version 24.2.0 enabling you to toggle the password straight from the EditText
without the need for a CheckBox
.
You can make that work basically by first updating your support library version to 24.2.0 and then setting an inputType
of password on the TextInputEditText
. Here's how to do that:
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/password"
android:inputType="textPassword"/>
</android.support.design.widget.TextInputLayout>
You can get more information about the new feature on the developer documentation for TextInputLayout.
You can use java.util.Arrays:
String res = Arrays.toString(array);
System.out.println(res);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If you want to rotate a vector you should construct what is known as a rotation matrix.
Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are
x' = x cos ? - y sin ?
y' = x sin ? + y cos ?
To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider
Unit vector along X axis = <1, 0>
x' = 1 cos 90 - 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ? Y-axis
When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is
|cos ? -sin ?| |x| = |x cos ? - y sin ?| = |x'|
|sin ? cos ?| |y| |x sin ? + y cos ?| |y'|
That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be
|cos ? -sin ? 0| |x| |x cos ? - y sin ?| |x'|
|sin ? cos ? 0| |y| = |x sin ? + y cos ?| = |y'|
| 0 0 1| |z| | z | |z'|
around the Y-axis would be
| cos ? 0 sin ?| |x| | x cos ? + z sin ?| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin ? 0 cos ?| |z| |-x sin ? + z cos ?| |z'|
around the X-axis would be
|1 0 0| |x| | x | |x'|
|0 cos ? -sin ?| |y| = |y cos ? - z sin ?| = |y'|
|0 sin ? cos ?| |z| |y sin ? + z cos ?| |z'|
Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.
Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.
I hope this clarifies basic rotation.
The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.
I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).
A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.
I see you've already solved your problem - but for posterity:
We had a similar problem, and the SVC handler was already correctly installed. Our problem was the ExtensionlessUrl handler processing requests before they reached the SVC handler.
To check this - in Handler Mappings in IIS Manager at the web server level, view the list of handlers in order (it's an option on the right-hand side). If the various ExtensionlessUrl handlers appear above the SVC handlers, then repeatedly move them down until they're at the bottom.
My VS 2015 install hung after hours of downloading. The VS installer window said it was still proceeding, but Windows Resource Monitor indicated there had been no networ, disk, or CPU usage by the vs_community.exe process tree for dozens of minutes. Windows Process Explorer revealed wusa.exe at the bottom of this tree (wusa is Windows Update Standalone Installer). Tempted to kill wusa.exe, I instead heeded the warnings in other answers to this question.
After studying other answers here (strongly recommended), I made an educated guess and initiated a restart of my Windows 7 Pro. The restart hung because vs_community.exe would not exit. I therefore selected Cancel on Windows' restart popup.
Windows returned to my user session, and now the VS 2015 install came to life(!) Process Explorer revealed wusa.exe no longer present. I therefore suspect that was the roadblock, but my conscience is clean (I didn't kill wusa.exe, Windows did!)
After awhile the installer displayed the following:
When I clicked Restart Now, Windows restarted to a "Configuring Windows" screen, and completed my VS install.
I case you are running SpringBoot:
I just had the same problem, that I could not Autowire one of my services from the static main method.
See below an approach in case you are relying on SpringApplication.run:
@SpringBootApplication
public class PricingOnlineApplication {
@Autowired
OrchestratorService orchestratorService;
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(PricingOnlineApplication.class, args);
PricingOnlineApplication application = context.getBean(PricingOnlineApplication.class);
application.start();
}
private void start() {
orchestratorService.performPricingRequest(null);
}
}
I noticed that SpringApplication.run returns a context which can be used similar to the above described approaches. From there, it is exactly the same as above ;-)
I was working in Wildfly but I was using
org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession();
and the correct was
org.hibernate.Session session = (Session) manager.getDelegate();
Try this
<div *ngFor="let piece of allPieces; let i=index">
{{i}} // this will give index
</div>
TomA's answer is right.
Using the "querystring" method will not be cached as quoted by Steve Souders below:
...that Squid, a popular proxy, doesn’t cache resources with a querystring.
TomA's suggestion of using style.TIMESTAMP.css is good, but MD5 would be much better as only when the contents were genuinely changed, the MD5 changes as well.
You can use (mouseover)
and (mouseout)
events.
component.ts
changeText:boolean=true;
component.html
<div (mouseover)="changeText=true" (mouseout)="changeText=false">
<span [hidden]="changeText">Hide</span>
<span [hidden]="!changeText">Show</span>
</div>
I, for example, use fail()
to indicate tests that are not yet finished (it happens); otherwise, they would show as successful.
This is perhaps due to the fact that I am unaware of some sort of incomplete() functionality, which exists in NUnit.
In Python, we handle exceptions similar to other language, but the difference is some syntax difference, for example,
try:
#Your code in which exception can occur
except <here we can put in a particular exception name>:
# We can call that exception here also, like ZeroDivisionError()
# now your code
# We can put in a finally block also
finally:
# Your code...
assert_has_calls
is another approach to this problem.
From the docs:
assert_has_calls (calls, any_order=False)
assert the mock has been called with the specified calls. The mock_calls list is checked for the calls.
If any_order is False (the default) then the calls must be sequential. There can be extra calls before or after the specified calls.
If any_order is True then the calls can be in any order, but they must all appear in mock_calls.
Example:
>>> from unittest.mock import call, Mock
>>> mock = Mock(return_value=None)
>>> mock(1)
>>> mock(2)
>>> mock(3)
>>> mock(4)
>>> calls = [call(2), call(3)]
>>> mock.assert_has_calls(calls)
>>> calls = [call(4), call(2), call(3)]
>>> mock.assert_has_calls(calls, any_order=True)
Source: https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_has_calls
You need access to /private/etc/
so, no. you cant.
you can also have multiple listings in the @Profile annotation
@Profile({"dev","default"})
If you set "default" as an additional value, you don't have to specify spring.profiles.active
select *
from blah
where DatetimeField between '22/02/2009 09:00:00.000' and '23/05/2009 10:30:00.000'
Depending on the country setting for the login, the month/day may need to be swapped around.
I recently got this error because the typo, I write 'canavas' instead of 'canvas', hope this could help someone who is searching for this.
This is because width
when provided a %
doesn't account for padding
/margin
s. You will need to reduce the amount to possibly 24%
or 24.5%
. Once this is done you should be good, but you will need to provide different options based on the screen size if you want this to always work correct since you have a hardcoded margin, but a relative size.
Considering that you are using OpenCV, the best way to convert between data types is to use normalize
function.
img_n = cv2.normalize(src=img, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
However, if you don't want to use OpenCV, you can do this in numpy
def convert(img, target_type_min, target_type_max, target_type):
imin = img.min()
imax = img.max()
a = (target_type_max - target_type_min) / (imax - imin)
b = target_type_max - a * imax
new_img = (a * img + b).astype(target_type)
return new_img
And then use it like this
imgu8 = convert(img16u, 0, 255, np.uint8)
This is based on the answer that I found on crossvalidated board in comments under this solution https://stats.stackexchange.com/a/70808/277040
System.out.println("\"Hello\"");
if you want to change only a column.for example from string to int32 you can use Expression property:
DataColumn col = new DataColumn("col_int" , typeof(int));
table.Columns.Add(col);
col.Expression = "table_exist_col_string"; // digit string convert to int
I spent over 5 hours trying to get rid of this message under Windows 8.1. So I would like to share my case and save someones time. I was not behind the proxy... but setting proxy helped to resolve the problem. So I go deep and found that issue was caused by Comodo Firewall... which blocked cmd since I was installing packages too fast (turning off and even closing Firewall did not help, which caused me so long to find the issue... seems like there was some other process of Firewall running in background). You may have same issue with any other firewall/antivirus installed so make sure that cmd is not blocked by them. Good luck!
use the fully qualified name instead of importing the class.
e.g.
//import java.util.Date; //delete this
//import my.own.Date;
class Test{
public static void main(String [] args){
// I want to choose my.own.Date here. How?
my.own.Date myDate = new my.own.Date();
// I want to choose util.Date here. How ?
java.util.Date javaDate = new java.util.Date();
}
}
Warning: This will break your repo.
This will corrupt binary files, including those under
svn
,.git
! Read the comments before using!
find . -iname '*.java' -type f -exec sed -i.orig 's/\t/ /g' {} +
The original file is saved as [filename].orig
.
Replace '*.java' with the file ending of the file type you are looking for. This way you can prevent accidental corruption of binary files.
Downsides:
Following is a Java-Spark way to do it , 1) add a sequentially increment columns. 2) Select Row number using Id. 3) Drop the Column
import static org.apache.spark.sql.functions.*;
..
ds = ds.withColumn("rownum", functions.monotonically_increasing_id());
ds = ds.filter(col("rownum").equalTo(99));
ds = ds.drop("rownum");
N.B. monotonically_increasing_id starts from 0;
There is no such thing as one language being faster than another, so the proper answer is no.
What you really have to ask is "is code compiled with Fortran compiler X faster than equivalent code compiled with C compiler Y?" The answer to that question of course depends on which two compilers you pick.
Another question one could ask would be along the lines of "Given the same amount of effort put into optimizing in their compilers, which compiler would produce faster code?" The answer to this would in fact be Fortran. Fortran compilers have certian advantages:
However, there is nothing stopping someone from putting a ton of effort into their C compiler's optimization, and making it generate better code than their platform's Fortran compiler. In fact, the larger sales generated by C compilers makes this scenario quite feasible
Well, you can read the entirety of the POST body like so
echo file_get_contents( 'php://input' );
And, assuming your webserver is Apache, you can read the request headers like so
$requestHeaders = apache_request_headers();
The AWS support pointed a simpler solution. It's basically the same idea proposed by @Vivek M. Chawla, with a more simple implementation.
AWS S3:
aws.example.com
Redirect all requests to another host name
and enter your URL:
https://myaccount.signin.aws.amazon.com/console/
AWS Route53:
Yes
. Click on Alias
Target
field and select the S3 bucket you created in the previous
step.Reference: How to redirect domains using Amazon Web Services
AWS official documentation: Is there a way to redirect a domain to another domain using Amazon Route 53?
I don't actually think that DI/IoC are that uncommon in Python. What is uncommon, however, are DI/IoC frameworks/containers.
Think about it: what does a DI container do? It allows you to
We have names for "wiring together" and "at runtime":
So, a DI container is nothing but an interpreter for a dynamic scripting language. Actually, let me rephrase that: a typical Java/.NET DI container is nothing but a crappy interpreter for a really bad dynamic scripting language with butt-ugly, sometimes XML-based, syntax.
When you program in Python, why would you want to use an ugly, bad scripting language when you have a beautiful, brilliant scripting language at your disposal? Actually, that's a more general question: when you program in pretty much any language, why would you want to use an ugly, bad scripting language when you have Jython and IronPython at your disposal?
So, to recap: the practice of DI/IoC is just as important in Python as it is in Java, for exactly the same reasons. The implementation of DI/IoC however, is built into the language and often so lightweight that it completely vanishes.
(Here's a brief aside for an analogy: in assembly, a subroutine call is a pretty major deal - you have to save your local variables and registers to memory, save your return address somewhere, change the instruction pointer to the subroutine you are calling, arrange for it to somehow jump back into your subroutine when it is finished, put the arguments somewhere where the callee can find them, and so on. IOW: in assembly, "subroutine call" is a Design Pattern, and before there were languages like Fortran which had subroutine calls built in, people were building their own "subroutine frameworks". Would you say that subroutine calls are "uncommon" in Python, just because you don't use subroutine frameworks?)
BTW: for an example of what it looks like to take DI to its logical conclusion, take a look at Gilad Bracha's Newspeak Programming Language and his writings on the subject:
If you want to use the font to draw with graphics2d or similar, this works:
InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("roboto-bold.ttf")
Font font = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(48f)
As this was already answered, I just wanted to point out the differences in approaches on getting the constructor of an object in JavaScript.
There is a difference between the constructor and the actual object/class name. If the following adds to the complexity of your decision then maybe you're looking for instanceof
. Or maybe you should ask yourself "Why am I doing this? Is this really what I am trying to solve?"
Notes:
The obj.constructor.name
is not available on older browsers.
Matching (\w+)
should satisfy ES6 style classes.
Code:
var what = function(obj) {
return obj.toString().match(/ (\w+)/)[1];
};
var p;
// Normal obj with constructor.
function Entity() {}
p = new Entity();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));
// Obj with prototype overriden.
function Player() { console.warn('Player constructor called.'); }
Player.prototype = new Entity();
p = new Player();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));
// Obj with constructor property overriden.
function OtherPlayer() { console.warn('OtherPlayer constructor called.'); }
OtherPlayer.constructor = new Player();
p = new OtherPlayer();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));
// Anonymous function obj.
p = new Function("");
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));
// No constructor here.
p = {};
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));
// ES6 class.
class NPC {
constructor() {
}
}
p = new NPC();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));
// ES6 class extended
class Boss extends NPC {
constructor() {
super();
}
}
p = new Boss();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));
Result:
I did this by creating a new XML file res/values/style.xml
as follows:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="boldText">
<item name="android:textStyle">bold|italic</item>
<item name="android:textColor">#FFFFFF</item>
</style>
<style name="normalText">
<item name="android:textStyle">normal</item>
<item name="android:textColor">#C0C0C0</item>
</style>
</resources>
I also have an entries in my "strings.xml" file like this:
<color name="highlightedTextViewColor">#000088</color>
<color name="normalTextViewColor">#000044</color>
Then, in my code I created a ClickListener to trap the tap event on that TextView: EDIT: As from API 23 'setTextAppearance' is deprecated
myTextView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
//highlight the TextView
//myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
if (Build.VERSION.SDK_INT < 23) {
myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
} else {
myTextView.setTextAppearance(R.style.boldText);
}
myTextView.setBackgroundResource(R.color.highlightedTextViewColor);
}
});
To change it back, you would use this:
if (Build.VERSION.SDK_INT < 23) {
myTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
} else{
myTextView.setTextAppearance(R.style.normalText);
}
myTextView.setBackgroundResource(R.color.normalTextViewColor);
Let's fit the model:
> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)
Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)
Residuals:
Min 1Q Median 3Q Max
-245.74 -113.99 -32.05 104.96 484.81
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 811.2267 76.9755 10.539 2.29e-13 ***
body.weight 7.0595 0.9776 7.221 7.03e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433
F-statistic: 52.15 on 1 and 42 DF, p-value: 7.025e-09
The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).
This can be computed using confint
:
> confint(fit, 'body.weight', level=0.95)
2.5 % 97.5 %
body.weight 5.086656 9.0324
While using formControl
, you have to import ReactiveFormsModule
to your imports
array.
Example:
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
MaterialModule,
],
...
})
export class AppModule {}
OSX users can follow by Nicolay77 or mikkom that uses the mdbtools utility. You can install it via Homebrew. Just have your homebrew installed and then go
$ homebrew install mdbtools
Then create one of the scripts described by the guys and use it. I've used mikkom's one, converted all my mdb files into sql.
$ ./to_mysql.sh myfile.mdb > myfile.sql
(which btw contains more than 1 table)
There are two different ways to implement inserting data from one table to another table.
This method is used when the table is already created in the database earlier and the data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them. It is good practice to always list them for readability and scalability purpose.
----Create testable
CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable
This method is used when the table is not created earlier and needs to be created when data from one table is to be inserted into the newly created table from another table. The new table is created with the same data types as selected columns.
----Create a new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable
We should have the projects which include (at least) all the filtered tags, or said in a different way, exclude the ones which doesn't include all those filtered tags.
So we can use Linq Except
to get those tags which are not included. Then we can use Count() == 0
to have only those which excluded no tags:
var res = projects.Where(p => filteredTags.Except(p.Tags).Count() == 0);
Or we can make it slightly faster with by replacing Count() == 0
with !Any()
:
var res = projects.Where(p => !filteredTags.Except(p.Tags).Any());
I do recomend doing it in 2 filles (.h .cpp)
But if u lazy just add inline
before the function
So it will look something like this
inline void functionX()
{ }
more about inline functions:
The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime. NOTE- This is just a suggestion to compiler to make the function inline, if function is big (in term of executable instruction etc) then, compiler can ignore the “inline” request and treat the function as normal function.
more info here
For anyone attempting something similar using a Dockerfile...
Running in detached mode won't help. The container will always exit (stop running) if the command is non-blocking, this is the case with bash.
In this case, a workaround would be: 1. Commit the resulting image: (container_name = the name of the container you want to base the image off of, image_name = the name of the image to be created docker commit container_name image_name 2. Use docker run to create a new container using the new image, specifying the command you want to run. Here, I will run "bash": docker run -it image_name bash
This would get you the interactive login you're looking for.
You can redirect forward or mask your domain name in godaddy but I don't know about other hosting sites.Have a look on this link
Consider an IBM 1403 impact printer. CR moved the print head to the start of the line, but did NOT advance the paper. This allowed for "overprinting", placing multiple lines of output on one line. Things like underlining were achieved this way, as was BOLD print. LF advanced the paper one line. If there was no CR, the next line would print as a staggered-step because LF didn't move the print head. FF advanced the paper to the next page. It typically also moved the print head to the start of the first line on the new page, but you might need CR for that. To be sure, most programmers coded CRFF instead of CRLF at the end of the last line on a page because an extra CR created by FF wouldn't matter.
In Python you will be creating a list of lists. You do not have to declare the dimensions ahead of time, but you can. For example:
matrix = []
matrix.append([])
matrix.append([])
matrix[0].append(2)
matrix[1].append(3)
Now matrix[0][0] == 2 and matrix[1][0] == 3. You can also use the list comprehension syntax. This example uses it twice over to build a "two-dimensional list":
from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]
Funnily, closing Xcode and reopening it might also be enough.
/*
LINES I WANT COMMENTED
LINES I WANT COMMENTED
LINES I WANT COMMENTED
*/
talonmies' answer above is a fine way to abort an application in an assert
-style manner.
Occasionally we may wish to report and recover from an error condition in a C++ context as part of a larger application.
Here's a reasonably terse way to do that by throwing a C++ exception derived from std::runtime_error
using thrust::system_error
:
#include <thrust/system_error.h>
#include <thrust/system/cuda/error.h>
#include <sstream>
void throw_on_cuda_error(cudaError_t code, const char *file, int line)
{
if(code != cudaSuccess)
{
std::stringstream ss;
ss << file << "(" << line << ")";
std::string file_and_line;
ss >> file_and_line;
throw thrust::system_error(code, thrust::cuda_category(), file_and_line);
}
}
This will incorporate the filename, line number, and an English language description of the cudaError_t
into the thrown exception's .what()
member:
#include <iostream>
int main()
{
try
{
// do something crazy
throw_on_cuda_error(cudaSetDevice(-1), __FILE__, __LINE__);
}
catch(thrust::system_error &e)
{
std::cerr << "CUDA error after cudaSetDevice: " << e.what() << std::endl;
// oops, recover
cudaSetDevice(0);
}
return 0;
}
The output:
$ nvcc exception.cu -run
CUDA error after cudaSetDevice: exception.cu(23): invalid device ordinal
A client of some_function
can distinguish CUDA errors from other kinds of errors if desired:
try
{
// call some_function which may throw something
some_function();
}
catch(thrust::system_error &e)
{
std::cerr << "CUDA error during some_function: " << e.what() << std::endl;
}
catch(std::bad_alloc &e)
{
std::cerr << "Bad memory allocation during some_function: " << e.what() << std::endl;
}
catch(std::runtime_error &e)
{
std::cerr << "Runtime error during some_function: " << e.what() << std::endl;
}
catch(...)
{
std::cerr << "Some other kind of error during some_function" << std::endl;
// no idea what to do, so just rethrow the exception
throw;
}
Because thrust::system_error
is a std::runtime_error
, we can alternatively handle it in the same manner of a broad class of errors if we don't require the precision of the previous example:
try
{
// call some_function which may throw something
some_function();
}
catch(std::runtime_error &e)
{
std::cerr << "Runtime error during some_function: " << e.what() << std::endl;
}
A Re-Introduction to Javascript by the Mozilla team (they make Firefox) should explain it.
Custom format
[>=1000]#,##0,"K";0
will give you:
Note the comma between the zero and the "K". To display millions or billions, use two or three commas instead.
Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf
between host and guest (there is known performance issues if there are large numbers of files/directories).
/vagrant
in guestVagrant is mounting the current working directory (where Vagrantfile
resides) as /vagrant
in the guest, this is the default behaviour.
See docs
NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.
You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true
in your Vagrantfile
.
Based on the output /tmp
on host was NOT mounted during up time.
Use VAGRANT_INFO=debug vagrant up
or VAGRANT_INFO=debug vagrant reload
to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp
on host should be drwxrwxrwt
).
I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)
config.vm.synced_folder "/tmp", "/tmp/src"
output
$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src
Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw)
.
Applying recursion to reorder items in an arraylist
public class ArrayListUtils {
public static <T> void reArrange(List<T> list,int from, int to){
if(from != to){
if(from > to)
reArrange(list,from -1, to);
else
reArrange(list,from +1, to);
Collections.swap(list, from, to);
}
}
}
IIUC you want the number of different ID
for every domain
, then you can try this:
output = df.drop_duplicates()
output.groupby('domain').size()
output:
domain
facebook.com 1
google.com 1
twitter.com 2
vk.com 3
dtype: int64
You could also use value_counts
, which is slightly less efficient.But the best is Jezrael's answer using nunique
:
%timeit df.drop_duplicates().groupby('domain').size()
1000 loops, best of 3: 939 µs per loop
%timeit df.drop_duplicates().domain.value_counts()
1000 loops, best of 3: 1.1 ms per loop
%timeit df.groupby('domain')['ID'].nunique()
1000 loops, best of 3: 440 µs per loop
If you are inside of Spring bean (in this case @Controller
bean) you shouldn't use Spring context instance at all. Just autowire className
bean directly.
BTW, avoid using field injection as it's considered as bad practice.
Short answer: When I send files between devices with OBEX I am almost never prompted to pair, so it is certainly possible.
1) An application and the device itself can each be set to need/not-need authentication modes, so often there was no requirement for pairing. For instance most OBEX (OPP) servers don't need any authentication at all so there is not need for pairing/bonding.
Presumably "Wireless Designs"'s answer was covering that case.
2) Then if pairing was required by the device/app:
2.1) Prior to v2.1 for pairing then the two devices needed to have matching passphrase/PINs. So this either needed user involvement (to enter the PINs) or knowledge in the softwareto know the PIN: either defined in the app if pin callback send pin="1234"
, or smarts in the OS like BlueZ and Win7 (see Slide 20 at my Bluetooth in Windows 7 doc) which has logic like: if(remotedevice=headset) then expectedPin ="0000"
. Don't know what Android does
2.2) In v2.1 Secure Simple Pairing (SSP) was added. Which changes pairing to:
if (either is pre-v2.1) then Legacy else if (Out-Of-Band channel) then OutOfBand else if (neither have "Man-in-the-Middle Protection Required") then (i.e. both have "Man-in-the-Middle Protection _Not_ Required") Just-Works else Depending on the two devices' "IO Capabilities", either NumericComparison or Passkey. Passkey is used when one device has KeyboardOnly -- and the peer device _isn't_ NoInputNoOutput. endif
From 32feet.NET's BluetoothWin32Authentication user guide, see also the SSP sections in [1]
So to have pairing be unprompted needs either "JustWorks" or "Out-of-Band" eg your NFC suggestion.
Hope that helps...
Let say button 1 has an event called
Button1_Click(Sender, eventarg)
If you want to call it in Button2 then call this function directly.
Button1_Click(Nothing, Nothing)
[^\x00-\x7F]
and [^[:ascii:]]
miss some control bytes so strings can be the better option sometimes. For example cat test.torrent | perl -pe 's/[^[:ascii:]]+/\n/g'
will do odd things to your terminal, where as strings test.torrent
will behave.
You can set one of the columns as an index in case it is an "id" for example. In this case the index column will be replaced by one of the columns you have chosen.
df.set_index('id', inplace=True)
index.html (index.html should be in templates folder)
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<h2>jQuery-AJAX in FLASK. Execute function on button click</h2>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<script type=text/javascript> $(function() { $("#mybutton").click(function (event) { $.getJSON('/SomeFunction', { },
function(data) { }); return false; }); }); </script>
</head>
<body>
<input type = "button" id = "mybutton" value = "Click Here" />
</body>
</html>
test.py
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/SomeFunction')
def SomeFunction():
print('In SomeFunction')
return "Nothing"
if __name__ == '__main__':
app.run()
If you are using curl on Windows:
curl -H "Content-Type: application/xml" -d "<?xml version="""1.0""" encoding="""UTF-8""" standalone="""yes"""?><message><sender>Me</sender><content>Hello!</content></message>" http://localhost:8080/webapp/rest/hello
I was getting the below error when i was trying to launch a new conatier- listen tcp 0.0.0.0:8080: bind: address already in use.
Solution: netstat -tulnp | grep 8080
[[email protected] (aws_main) ~]# netstat -tulnp | grep 8080 tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 12749/java [[email protected] (aws_main) ~]#
kill -9 12749
Then try to relaunch the container it should work
str.toLowerCase().replace(/[\*\^\'\!]/g, '').split(' ').join('-')
If Machine A is a Windows box, you can use Plink (part of PuTTY) with the -m parameter, and it will execute the local script on the remote server.
plink root@MachineB -m local_script.sh
If Machine A is a Unix-based system, you can use:
ssh root@MachineB 'bash -s' < local_script.sh
You shouldn't have to copy the script to the remote server to run it.
What regex engine are you using? Most of them will support the following expression:
\{\d+:\d+\}
The \d
is actually shorthand for [0-9]
, but the important part is the addition of +
which means "one or more".
myDivObj = document.getElementById("myDiv");
if ( myDivObj ) {
alert ( myDivObj.innerHTML );
}else{
alert ( "Alien Found" );
}
Above code will show the innerHTML, i.e if you have used html tags inside div then it will show even those too. probably this is not what you expected. So another solution is to use: innerText / textContent property [ thanx to bobince, see his comment ]
function showDivText(){
divObj = document.getElementById("myDiv");
if ( divObj ){
if ( divObj.textContent ){ // FF
alert ( divObj.textContent );
}else{ // IE
alert ( divObj.innerText ); //alert ( divObj.innerHTML );
}
}
}
The datepicker('setDate') sets the date in the datepicket not in the input.
You should add the date and set it in the input.
var date2 = $('.pickupDate').datepicker('getDate');
var nextDayDate = new Date();
nextDayDate.setDate(date2.getDate() + 1);
$('input').val(nextDayDate);
try this:
var c=document.getElementById("alpha");
var d=c.toDataURL("image/png");
var w=window.open('about:blank','image from canvas');
w.document.write("<img src='"+d+"' alt='from canvas'/>");
This shows image from canvas on new page, but if you have open popup in new tab
setting it shows about:blank
in address bar.
EDIT:- though window.open("<img src='"+ c.toDataURL('image/png') +"'/>")
does not work in FF or Chrome, following works though rendering is somewhat different from what is shown on canvas, I think transparency is the issue:
window.open(c.toDataURL('image/png'));
In SQL Management Studio you can:
Right click on the result set grid, select 'Save Result As...' and save in.
On a tool bar toggle 'Result to Text' button. This will prompt for file name on each query run.
If you need to automate it, use bcp tool.
One of the properties of the listview is IsHitTestVisible
.
Uncheck it.
As far as I know, the most pythonic/efficient method would be:
import string
filtered_string = filter(lambda x: x in string.printable, myStr)
You can take advantage of the head()
(or first()
) functions to see if the DataFrame
has a single row. If so, it is not empty.
is just going to look for a div with class="outer inner", is that correct?
No, '.outer .inner'
will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner'
(no space) would give the results you're thinking of.
'.outer > .inner'
will look for immediate children of an element with the .outer class for elements with the .inner class.
Both '.outer .inner'
and '.outer > .inner'
should work for your example, although the selectors are fundamentally different and you should be wary of this.
I suggest using "outline" instead of "border". For example: outline: 1px solid #1e5180
.
You can find clear difference between interface and abstract class.
Interface
Abstract class
Abstract class contains abstract and non-abstract methods.
Does not force users to implement all methods when inherited the abstract class.
Contains all kinds of variables including primitive and non-primitive
Declare using abstract keyword.
Methods and members of an abstract class can be defined with any visibility.
A child class can only extend a single class (abstract or concrete).
You shouldn't be passing anything in to getCountry()
. Remove Locale.getDefault()
:
String locale = context.getResources().getConfiguration().locale.getCountry();
Use following layerlist
:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" android:padding="10dp">
<corners
android:bottomRightRadius="5dp"
android:bottomLeftRadius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
</shape>
</item>
<item android:drawable="@drawable/image_name_here" />
</layer-list>
This appears to be a bug in Bundler not recognizing the default gems installed along with ruby 2.x. I still experienced the problem even with the latest version of bundler (1.5.3).
One solution is to simply delete json-1.8.1.gemspec from the default gemspec directory.
rm ~/.rubies/ruby-2.1.0/lib/ruby/gems/2.1.0/specifications/default/json-1.8.1.gemspec
After doing this, bundler should have no problem locating the gem. Note that I am using chruby. If you're using some other ruby manager, you'll have to update your path accordingly.
I tried my best to follow the answers given above. But I have below reason for the same.
Note: This is for maven+eclipse+tomcat deployment and issue faced especially with spring mvc.
1- If you are including servlet and jsp dependency please mark them provided in scope.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
Possibly you might be including jstl as dependency. So, jsp-api.jar
and servlet-api.jar
will be included along. So, require to exclude the servlet-api and jsp-api being deployed as required lib in target or in "WEB-INF/lib" as given below.
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
<exclusions>
<exclusion>
<artifactId>servlet-api</artifactId>
<groupId>javax.servlet</groupId>
</exclusion>
<exclusion>
<artifactId>jsp-api</artifactId>
<groupId>javax.servlet.jsp</groupId>
</exclusion>
</exclusions>
</dependency>
I found that the best way to embed a pdf for my case was by using bootstrap because not only does it show the pdf but it also fill available space and you can specify the ratio as you wish. Here's an example of what i made with it:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<div class="embed-responsive embed-responsive-1by1">
<iframe class="embed-responsive-item" src="http://example.com/the.pdf" type="application/pdf" allowfullscreen></iframe>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
_x000D_
Disable true for input type :
In case of a specific input type (Ex. Text type input)
$("input[type=text]").attr('disabled', true);
For all type of input type
$("input").attr('disabled', true);
Strangely, I didn't find anything about legends and labels in the Chart.js documentation. It seems like you can't do it with chart.js alone.
I used https://github.com/bebraw/Chart.js.legend which is extremely light, to generate the legends.
In app-level gradle, you have to write these code:
android {
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
They come from JavaVersion.java in Android.
An enumeration of Java versions.
Before 9: http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html
After 9: http://openjdk.java.net/jeps/223
@canerkaseler
The problem here is windows credentials manager, Please goto control panel and search for credentials manager and delete all contents of it regarding github
For jupyter lab this should work (@Alasja)
from IPython.display import HTML
HTML('''<script>
var code_show_err = false;
var code_toggle_err = function() {
var stderrNodes = document.querySelectorAll('[data-mime-type="application/vnd.jupyter.stderr"]')
var stderr = Array.from(stderrNodes)
if (code_show_err){
stderr.forEach(ele => ele.style.display = 'block');
} else {
stderr.forEach(ele => ele.style.display = 'none');
}
code_show_err = !code_show_err
}
document.addEventListener('DOMContentLoaded', code_toggle_err);
</script>
To toggle on/off output_stderr, click <a onclick="javascript:code_toggle_err()">here</a>.''')
I have just ran into the same problem after updating. The JRE that is downloaded by OSX Lion is missing JavaRuntimeSupport.jar which will work but can wreck havoc on a lot of things. If you've updated, and you had a working JDK/JRE installed prior to that, do the following in Eclipse:
1) Project > Properties > Java Build Path > Select broken JRE/JDK > Edit
2) Select "Alternate JRE"
3) Click "Installed JREs..."
4) In the window that opens, click "Search..."
If all goes well, it will find your older JRE/JDK. Mine was in this location:
/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
You could do that:
KeyValuePair<TKey, TValue>
's in the dictionary (which will be a sizable performance hit if you have a number of entries in the dictionary) Use Method 1 if performance is not a consideration, use Method 2 if memory is not a consideration.
Also, all keys must be unique, but the values are not required to be unique. You may have more than one key with the specified value.
Is there any reason you can't reverse the key-value relationship?
SOLUTION:
Here is the solution. Executing a function after the user has stopped typing for a specified amount of time:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Usage
$('input').keyup(function() {
delay(function(){
alert('Hi, func called');
}, 1000 );
});
To disable inputting password:
sudo visudo
Then add a new line like below and save then:
# The user can run installer as root without inputting password
yourusername ALL=(root) NOPASSWD: /usr/sbin/installer
Then you run installer without password:
sudo installer -pkg ...
Building on the answer from @Brian-Fisher and answering the comments of some of the people on this post, I have a bunch of huge (and unnecessary) tables in my database so I wanted to skip their contents when copying, but keep the structure:
mysqldump -h <host> -u <username> -p <schema> --no-data > db-structure.sql
mysqldump -h <host> -u <username> -p <schema> --no-create-info --ignore-table=schema.table1 --ignore-table=schema.table2 > db-data.sql
The resulting two files are structurally sound but the dumped data is now ~500MB rather than 9GB, much better for me. I can now import these two files into another database for testing purposes without having to worry about manipulating 9GB of data or running out of disk space.
extern "C"
makes a function-name in C++ have C linkage (compiler does not mangle the name) so that client C code can link to (use) your function using a C compatible header file that contains just the declaration of your function. Your function definition is contained in a binary format (that was compiled by your C++ compiler) that the client C linker will then link to using the C name.
Since C++ has overloading of function names and C does not, the C++ compiler cannot just use the function name as a unique id to link to, so it mangles the name by adding information about the arguments. A C compiler does not need to mangle the name since you can not overload function names in C. When you state that a function has extern "C"
linkage in C++, the C++ compiler does not add argument/parameter type information to the name used for linkage.
Just so you know, you can specify extern "C"
linkage to each individual declaration/definition explicitly or use a block to group a sequence of declarations/definitions to have a certain linkage:
extern "C" void foo(int);
extern "C"
{
void g(char);
int i;
}
If you care about the technicalities, they are listed in section 7.5 of the C++03 standard, here is a brief summary (with emphasis on extern "C"
):
extern "C"
is a linkage-specificationextern "C"
is ignored for class membersextern "C"
forces a function to have external linkage (cannot make it static) static
inside extern "C"
is valid; an entity so declared has internal linkage, and so does not have a language linkageDBEngine.CompactDatabase source, dest
You can't do it using environment variables. It's done via "non standard" options. Run: java -X
for details. The options you're looking for are -Xmx
and -Xms
(this is "initial" heap size, so probably what you're looking for.)
I have created main.css file and included all css files in it.
We can include only one main.css file
@import url('style.css');
@import url('platforms.css');
To be honest, I was not really convinced with any of the answers in this thread. So, here's are my solutions:
This method is agnostic to whether the directive's $scope
is a shared one or isolated one
A factory
to register the directive instances
angular.module('myModule').factory('MyDirectiveHandler', function() {
var instance_map = {};
var service = {
registerDirective: registerDirective,
getDirective: getDirective,
deregisterDirective: deregisterDirective
};
return service;
function registerDirective(name, ctrl) {
instance_map[name] = ctrl;
}
function getDirective(name) {
return instance_map[name];
}
function deregisterDirective(name) {
instance_map[name] = null;
}
});
The directive code, I usually put all the logic that doesn't deal with DOM inside directive controller. And registering the controller instance inside our handler
angular.module('myModule').directive('myDirective', function(MyDirectiveHandler) {
var directive = {
link: link,
controller: controller
};
return directive;
function link() {
//link fn code
}
function controller($scope, $attrs) {
var name = $attrs.name;
this.updateMap = function() {
//some code
};
MyDirectiveHandler.registerDirective(name, this);
$scope.$on('destroy', function() {
MyDirectiveHandler.deregisterDirective(name);
});
}
})
template code
<div my-directive name="foo"></div>
Access the controller instance using the factory
& run the publicly exposed methods
angular.module('myModule').controller('MyController', function(MyDirectiveHandler, $scope) {
$scope.someFn = function() {
MyDirectiveHandler.get('foo').updateMap();
};
});
Taking a leaf out of angular's book on how they deal with
<form name="my_form"></form>
using $parse and registering controller on $parent
scope. This technique doesn't work on isolated $scope
directives.
angular.module('myModule').directive('myDirective', function($parse) {
var directive = {
link: link,
controller: controller,
scope: true
};
return directive;
function link() {
//link fn code
}
function controller($scope, $attrs) {
$parse($attrs.name).assign($scope.$parent, this);
this.updateMap = function() {
//some code
};
}
})
Access it inside controller using $scope.foo
angular.module('myModule').controller('MyController', function($scope) {
$scope.someFn = function() {
$scope.foo.updateMap();
};
});
In the case of your fictional getattr
function, if the requested attribute always should be available but isn't then throw an error. If the attribute is optional then return None
.
To import your module, you need to add its directory to the environment variable, either temporarily or permanently.
import sys
sys.path.append("/path/to/my/modules/")
import my_module
Adding the following line to your .bashrc
file (in linux) and excecute source ~/.bashrc
in the terminal:
export PYTHONPATH="${PYTHONPATH}:/path/to/my/modules/"
Credit/Source: saarrrr, another stackexchange question
I would strongly recommend using a library like PHPMailer to send emails.
It's easier and handles most of the issues automatically for you.
Regarding displaying embedded (inline) images, here's what's on their documentation:
Inline Attachments
There is an additional way to add an attachment. If you want to make a HTML e-mail with images incorporated into the desk, it's necessary to attach the image and then link the tag to it. For example, if you add an image as inline attachment with the CID my-photo, you would access it within the HTML e-mail with
<img src="cid:my-photo" alt="my-photo" />
.In detail, here is the function to add an inline attachment:
$mail->AddEmbeddedImage(filename, cid, name);
//By using this function with this example's value above, results in this code:
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');
To give you a more complete example of how it would work:
<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->Port = 25; // set the SMTP port
$mail->SetFrom('[email protected]', 'First Last');
$mail->AddAddress('[email protected]', 'John Doe');
$mail->Subject = 'PHPMailer Test';
$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';
$mail->AddAttachment('something.zip'); // this is a regular attachment (Not inline)
$mail->Send();
echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
Regarding your comment, you asked how to send HTML email with embedded images, so I gave you an example of how to do that.
The library I told you about can send emails using a lot of methods other than SMTP.
Take a look at the PHPMailer Example page for other examples.
One way or the other, if you don't want to send the email in the ways supported by the library, you can (should) still use the library to build the message, then you send it the way you want.
For example:
You can replace the line that send the email:
$mail->Send();
With this:
$mime_message = $mail->CreateBody(); //Retrieve the message content
echo $mime_message; // Echo it to the screen or send it using whatever method you want
Hope that helps. Let me know if you run into trouble using it.
In addition to the value you wish to print, the {0} {1}
, etc., you can specify a format. For example, {0,4}
will be a value that is padded to four spaces.
There are a number of built-in format specifiers, and in addition, you can make your own. For a decent tutorial/list see String Formatting in C#. Also, there is a FAQ here.
Found another case which results in bloody Certificate has either expired or has been revoked
error in Xcode 9
. If you're trying to sign with valid certificate but you do have another revoked certificate in the same team on your keychain, Xcode throws this error. To check if you do have revoked certificate see Xcode -> Preferences -> Accounts -> Your Apple ID -> Your Team -> Manage Certificates
. Deleting revoked certificate with Keychain Access
solves this. Looks like another code sign bug in Xcode.
I had the same problem and couldn't find the right solution so I wrote a function called GetFiles:
/// <summary>
/// Get all files with a specific extension
/// </summary>
/// <param name="extensionsToCompare">string list of all the extensions</param>
/// <param name="Location">string of the location</param>
/// <returns>array of all the files with the specific extensions</returns>
public string[] GetFiles(List<string> extensionsToCompare, string Location)
{
List<string> files = new List<string>();
foreach (string file in Directory.GetFiles(Location))
{
if (extensionsToCompare.Contains(file.Substring(file.IndexOf('.')+1).ToLower())) files.Add(file);
}
files.Sort();
return files.ToArray();
}
This function will call Directory.Getfiles()
only one time.
For example call the function like this:
string[] images = GetFiles(new List<string>{"jpg", "png", "gif"}, "imageFolder");
EDIT: To get one file with multiple extensions use this one:
/// <summary>
/// Get the file with a specific name and extension
/// </summary>
/// <param name="filename">the name of the file to find</param>
/// <param name="extensionsToCompare">string list of all the extensions</param>
/// <param name="Location">string of the location</param>
/// <returns>file with the requested filename</returns>
public string GetFile( string filename, List<string> extensionsToCompare, string Location)
{
foreach (string file in Directory.GetFiles(Location))
{
if (extensionsToCompare.Contains(file.Substring(file.IndexOf('.') + 1).ToLower()) &&& file.Substring(Location.Length + 1, (file.IndexOf('.') - (Location.Length + 1))).ToLower() == filename)
return file;
}
return "";
}
For example call the function like this:
string image = GetFile("imagename", new List<string>{"jpg", "png", "gif"}, "imageFolder");
The easiest of all:
keytool -list -printcert -jarfile file.apk
This uses the Java built-in keytool app and does not require extraction or any build-tools installation.
This property controls the magnification level for the current element. The rendering effect for the element is that of a “zoom” function on a camera. Even though this property is not inherited, it still affects the rendering of child elements.
Example
div { zoom: 200% }
<div style=”zoom: 200%”>This is x2 text </div>
You could download it from a Android 4.0 phone and then mount the system image rw
and copy it over.
Didnt tried it before but it should work.
Here is the OOP way of adding a colorbar:
fig, ax = plt.subplots()
im = ax.scatter(x, y, c=c)
fig.colorbar(im, ax=ax)
Many good answers have already been posted to this question, but I believe we really are missing an important one - namely, the illustrated answer.
What does it mean to say that the height of a complete binary tree is O(log n)?
The following drawing depicts a binary tree. Notice how each level contains double the number of nodes compared to the level above (hence binary):
Binary search is an example with complexity O(log n)
. Let's say that the nodes in the bottom level of the tree in figure 1 represents items in some sorted collection. Binary search is a divide-and-conquer algorithm, and the drawing shows how we will need (at most) 4 comparisons to find the record we are searching for in this 16 item dataset.
Assume we had instead a dataset with 32 elements. Continue the drawing above to find that we will now need 5 comparisons to find what we are searching for, as the tree has only grown one level deeper when we multiplied the amount of data. As a result, the complexity of the algorithm can be described as a logarithmic order.
Plotting log(n)
on a plain piece of paper, will result in a graph where the rise of the curve decelerates as n
increases:
The BEST way to use the AppData directory, IS to use Environment.ExpandEnvironmentVariable
method.
Reasons:
Examples:
string path;
path = @"%AppData%\stuff";
path = @"%aPpdAtA%\HelloWorld";
path = @"%progRAMfiLES%\Adobe;%appdata%\FileZilla"; // collection of paths
path = Environment.ExpandEnvironmentVariables(path);
Console.WriteLine(path);
%ALLUSERSPROFILE% C:\ProgramData
%APPDATA% C:\Users\Username\AppData\Roaming
%COMMONPROGRAMFILES% C:\Program Files\Common Files
%COMMONPROGRAMFILES(x86)% C:\Program Files (x86)\Common Files
%COMSPEC% C:\Windows\System32\cmd.exe
%HOMEDRIVE% C:
%HOMEPATH% C:\Users\Username
%LOCALAPPDATA% C:\Users\Username\AppData\Local
%PROGRAMDATA% C:\ProgramData
%PROGRAMFILES% C:\Program Files
%PROGRAMFILES(X86)% C:\Program Files (x86) (only in 64-bit version)
%PUBLIC% C:\Users\Public
%SystemDrive% C:
%SystemRoot% C:\Windows
%TEMP% and %TMP% C:\Users\Username\AppData\Local\Temp
%USERPROFILE% C:\Users\Username
%WINDIR% C:\Windows
I need to add my solution which is WAY eaiser than the one above. We don't even need to use styles.
Create a selector file in the drawable folder:
custom_ratingbar_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background"
android:drawable="@drawable/star_off" />
<item android:id="@android:id/secondaryProgress"
android:drawable="@drawable/star_off" />
<item android:id="@android:id/progress"
android:drawable="@drawable/star_on" />
</layer-list>
In the layout set the selector file as progressDrawable:
<RatingBar
android:id="@+id/ratingBar2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:progressDrawable="@drawable/custom_ratingbar_selector"
android:numStars="8"
android:stepSize="0.2"
android:rating="3.0" />
And that's all we need.
When it comes to Muhammad Mehdi's answer, it is better to do:
private void salary_texbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex ( "[^0-9]+" );
if(regex.IsMatch(e.Text))
{
MessageBox.Show("Error");
}
}
Because when comparing with the TextCompositionEventArgs it gets also the last character, while with the textbox.Text it does not. With textbox, the error will show after next inserted character.
<html>
<body>
<input id="mycheck" type="checkbox">
</body>
<script language="javascript">
var=check;
document.getElementById("mycheck");
check.checked="false";
</script>
</html>
The answer by Nick Mitchinson is for Bootstrap version 2.
If you are using Bootstrap version 3, then forms have changed a bit. For bootstrap 3, use the following instead:
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-6">
<textarea class="form-control" rows="3" placeholder="What's up?" required></textarea>
</div>
</div>
</div>
Where, col-md-6 will target medium sized devices. You can add col-xs-6 etc to target smaller devices.
You can use this
char name[20];
scanf("%20[^\n]", name);
Or this
void getText(char *message, char *variable, int size){
printf("\n %s: ", message);
fgets(variable, sizeof(char) * size, stdin);
sscanf(variable, "%[^\n]", variable);
}
char name[20];
getText("Your name", name, 20);
Unfortunately, it the Developer Tools in Chrome seem to be unable to "stop on all errors", as Firebug does.
Try this:
var newArr = [];
$.each(JSONObject.results.bindings, function(i, obj) {
newArr.push([obj.value]);
});
I had "ORA-12560: TNS:protocol adaptor error" problem, and I googled it for 2 hours for not paying attention to details. I opened command prompt and then I had this:
C:\Users\Frodo>set oracle_sid=<DB name>
... while it should be lie this:
C:\>set oracle_sid=<DB name>
C:> should be instead of C:\Users\Frodo> - that was my problem; so this worked:
C:\Users\Frodo> cd c:
C:\>set oracle_sid=<DB name>
C:\>exp ........
Just complementing: It's kind of obvious, but you can use static imports to give you a hand, like this:
import static javax.swing.JOptionPane.*;
public class SimpleDialog(){
public static void main(String argv[]) {
showMessageDialog(null, "Message", "Title", ERROR_MESSAGE);
}
}
It happened for me also and the reason was selecting inappropriate combination of tomcat and Dynamic web module version while creating project in eclipse. I selected Tomcat v9.0 along with Dynamic web module version 3.1 and eclipse was not able to resolve the HttpServlet type. When used Tomcat 7.0 along with Dynamic web module version 7.0, eclipse was automatically able to resolve the HttpServlet type.
Related question Dynamic Web Module option in Eclipse
To check which version of tomcat should be used along with different versions of the Servlet and JSP specifications refer http://tomcat.apache.org/whichversion.html
The function name does not reflect the semantic of the function. In fact you do not append a character. You create a new character array that contains the original array plus the given character. So if you indeed need a function that appends a character to a character array I would write it the following way
bool AppendCharToCharArray( char *array, size_t n, char c )
{
size_t sz = std::strlen( array );
if ( sz + 1 < n )
{
array[sz] = c;
array[sz + 1] = '\0';
}
return ( sz + 1 < n );
}
If you need a function that will contain a copy of the original array plus the given character then it could look the following way
char * CharArrayPlusChar( const char *array, char c )
{
size_t sz = std::strlen( array );
char *s = new char[sz + 2];
std::strcpy( s, array );
s[sz] = c;
s[sz + 1] = '\0';
return ( s );
}
Set the CSS position: relative;
on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:
position: absolute;
bottom: 0;
right: 0;
If you need to space the text farther away from the edge, you could change 0
to 2px
or similar.
Wrap the text within the list item with a span (or some other element) and apply the bullet color to the list item and the text color to the span.
Complete working example in Kotlin, I have replaced my API keys with 1111...
val apiService = API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
val params = HashMap<String, String>()
params["q"] = "munich,de"
params["APPID"] = "11111111111111111"
val call = apiService.getWeather(params)
call.enqueue(object : Callback<WeatherResponse> {
override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
Log.e("Error:::","Error "+t!!.message)
}
override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
if (response != null && response.isSuccessful && response.body() != null) {
Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)
temperature.setText(""+ response.body()!!.main.temp)
}
}
})
void addToSpecific()
{
int n;
int f=0; //flag
Node *temp=H; //H-Head, T-Tail
if(NULL!=H)
{
cout<<"Enter the Number"<<endl;
cin>>n;
while(NULL!=(temp->getNext()))
{
if(n==(temp->getInfo()))
{
f=1;
break;
}
temp=temp->getNext();
}
}
if(NULL==H)
{
Node *nn=new Node();
nn->setInfo();
nn->setNext(NULL);
T=H=nn;
}
else if(0==f)
{
Node *nn=new Node();
nn->setInfo();
nn->setNext(NULL);
T->setNext(nn);
T=nn;
}
else if(1==f)
{
Node *nn=new Node();
nn->setInfo();
nn->setNext(NULL);
nn->setNext((temp->getNext()));
temp->setNext(nn);
}
}
For numerical addressing of cells try to enable S1O1 checkbox in MS Excel settings. It is the second tab from top (i.e. Formulas), somewhere mid-page in my Hungarian version.
If enabled, it handles VBA addressing in both styles, i.e. Range("A1:B10") and Range(Cells(1, 1), Cells(10, 2)). I assume it handles Range("A1:B10") style only, if not enabled.
Good luck!
(Note, that Range("A1:B10") represents a 2x10 square, while Range(Cells(1, 1), Cells(10, 2)) represents 10x2. Using column numbers instead of letters will not affect the order of addresing.)
The new HTTP Client shipped with Java 9 but as part of an Incubator module named
jdk.incubator.httpclient
. Incubator modules are a means of putting non-final APIs in the hands of developers while the APIs progress towards either finalization or removal in a future release.
In Java 9, you can send a GET
request like:
// GET
HttpResponse response = HttpRequest
.create(new URI("http://www.stackoverflow.com"))
.headers("Foo", "foovalue", "Bar", "barvalue")
.GET()
.response();
Then you can examine the returned HttpResponse
:
int statusCode = response.statusCode();
String responseBody = response.body(HttpResponse.asString());
Since this new HTTP Client is in java.httpclient
jdk.incubator.httpclient
module, you should declare this dependency in your module-info.java
file:
module com.foo.bar {
requires jdk.incubator.httpclient;
}
Perhaps you need to read about interactive usage of Matplotlib. However, if you are going to build an app, you should be using the API and embedding the figures in the windows of your chosen GUI toolkit (see examples/embedding_in_tk.py
, etc).
Easiest way to reverse a string:
backwards = input("Enter string to reverse: ")
print(backwards[::-1])
Here is a variation of @zhigang's answer which does without AWK, relying only on Bash's native parsing possibilities:
function killtree {
kill -STOP "$1"
ps -e -o pid= -o ppid= | while read -r pid ppid
do
[[ $ppid = $1 ]] || continue
killtree "$pid" || true # Skip over failures
done
kill -CONT "$1"
kill -TERM "$1"
}
It seems to work fine on both Macs and Linux. In situations where you can't rely on being able to manage process groups -- like when writing scripts for testing a piece of software which must be built in multiple environments -- this tree-walking technique is definitely helpful.
You manage the list of available compilers in the Window -> Preferences -> Java -> Installed JRE's tab
.
In the project build path configuration dialog, under the libraries tab, you can delete the entry for JRE System Library
, click on Add Library
and choose the installed JRE to compile with. Some compilers can be configured to compile at a back-level compiler version. I think that's why you're seeing the addition version options.
Yes, you can.
@supports (-webkit-touch-callout: none) {
/* CSS specific to iOS devices */
}
@supports not (-webkit-touch-callout: none) {
/* CSS for other than iOS devices */
}
YMMV.
It works because only Safari Mobile implements -webkit-touch-callout
: https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-touch-callout
Please note that @supports
does not work in IE. IE will skip both of the above @support
blocks above. To find out more see https://hacks.mozilla.org/2016/08/using-feature-queries-in-css/. It is recommended to not use @supports not
because of this.
What about Chrome or Firefox on iOS? The reality is these are just skins over the WebKit rendering engine. Hence the above works everywhere on iOS as long as iOS policy does not change. See 2.5.6 in App Store Review Guidelines.
Warning: iOS may remove support for this in any new iOS release in the coming years. You SHOULD try a bit harder to not need the above CSS. An earlier version of this answer used -webkit-overflow-scrolling
but a new iOS version removed it. As a commenter pointed out, there are other options to choose from: Go to Supported CSS Properties and search for "Safari on iOS".
Using Base64 to embed images in html is awesome. Nonetheless, please notice that base64 strings can make your email size big.
Therefore,
1) If you have many images, uploading your images to a server and loading those images from the server can make your email size smaller. (You can get a lot of free services via Google)
2) If there are just a few images in your mail, using base64 strings is definitely an awesome option.
Besides the choices provided by existing answers, you can also use a command to generate a base64 string on linux:
base64 test.jpg
As with many tasks in ggplot, the general strategy is to put what you'd like to add to the plot into a data frame in a way such that the variables match up with the variables and aesthetics in your plot. So for example, you'd create a new data frame like this:
dfTab <- as.data.frame(table(df))
colnames(dfTab)[1] <- "x"
dfTab$lab <- as.character(100 * dfTab$Freq / sum(dfTab$Freq))
So that the x
variable matches the corresponding variable in df
, and so on. Then you simply include it using geom_text
:
ggplot(df) + geom_bar(aes(x,fill=x)) +
geom_text(data=dfTab,aes(x=x,y=Freq,label=lab),vjust=0) +
opts(axis.text.x=theme_blank(),axis.ticks=theme_blank(),
axis.title.x=theme_blank(),legend.title=theme_blank(),
axis.title.y=theme_blank())
This example will plot just the percentages, but you can paste
together the counts as well via something like this:
dfTab$lab <- paste(dfTab$Freq,paste("(",dfTab$lab,"%)",sep=""),sep=" ")
Note that in the current version of ggplot2, opts
is deprecated, so we would use theme
and element_blank
now.
Liquibase was getting this error for me. I resolved this after I debugged and watched liquibase try to load the libraries and found that it was erroring on the manifest files for commons-codec-1.6.jar. Essentially, there is either a corrupt zip file somewhere in your path or there is a incompatible version being used. When I did an explore on Maven repository for this library, I found there were newer versions and added the newer version to the pom.xml. I was able to proceed at this point.
Simply add style="line-height:0"
to each cell. This works in IE because it sets the line-height of both existant and non-existant text to about 19px and that forces the cells to expand vertically in most versions of IE. Regardless of whether or not you have text this needs to be done for IE to correctly display rows less than 20px high.
In bootstrap 3, this works well for me:
.btn-link.btn-anchor {
outline: none !important;
padding: 0;
border: 0;
vertical-align: baseline;
}
Used like:
<button type="button" class="btn-link btn-anchor">My Button</button>
HTML: text/html
, full-stop.
XHTML: application/xhtml+xml
, or only if following HTML compatbility guidelines, text/html
. See the W3 Media Types Note.
XML: text/xml
, application/xml
(RFC 2376).
There are also many other media types based around XML, for example application/rss+xml
or image/svg+xml
. It's a safe bet that any unrecognised but registered ending in +xml
is XML-based. See the IANA list for registered media types ending in +xml
.
(For unregistered x-
types, all bets are off, but you'd hope +xml
would be respected.)
There are very well answers here, but I want to add one line:
In android:onclick
in XML, Android uses java reflection behind the scene to handle this.
And as explained here, reflection always slows down the performance. (especially on Dalvik VM). Registering onClickListener
is a better way.
#include <stdio.h>
int main(void) {
printf("size of int: %d", (int)sizeof(int));
return 0;
}
This returns 4, but it's probably machine dependant.
You have to add parameters since it is needed for the SP to execute
using (SqlConnection con = new SqlConnection(dc.Con))
{
using (SqlCommand cmd = new SqlCommand("SP_ADD", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FirstName", txtfirstname.Text);
cmd.Parameters.AddWithValue("@LastName", txtlastname.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}