Alternatively to Link Library Dependencies
in project properties there is another way to link libraries in Visual Studio.
Add Existing Item...
).Item Type
is Library
This will include the other libraries in X as if you ran
lib /out:X.lib X.lib other1.lib other2.lib
.a are static libraries. If you use code stored inside them, it's taken from them and embedded into your own binary. In Visual Studio, these would be .lib files.
.so are dynamic libraries. If you use code stored inside them, it's not taken and embedded into your own binary. Instead it's just referenced, so the binary will depend on them and the code from the so file is added/loaded at runtime. In Visual Studio/Windows these would be .dll files (with small .lib files containing linking information).
This solution is about 3.6× faster than the top rated answer when tested on a file with 13.8 million lines. It simply reads the bytes into a buffer and counts the \n
characters. You could play with the buffer size, but on my machine, anything above 8KB didn't make the code faster.
private int countLines(File file) throws IOException {
int lines = 0;
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[BUFFER_SIZE]; // BUFFER_SIZE = 8 * 1024
int read;
while ((read = fis.read(buffer)) != -1) {
for (int i = 0; i < read; i++) {
if (buffer[i] == '\n') lines++;
}
}
fis.close();
return lines;
}
In C, there's no (real, distinct type of) strings. Every C "string" is an array of chars, zero terminated.
Therefore, to extract a character c at index i from string your_string, just use
char c = your_string[i];
Index is base 0 (first character is your_string[0], second is your_string[1]...).
Here an example with the iteration:
<?php
$colors = (object)[];
$colors->red = "#F00";
$colors->slateblue = "#6A5ACD";
$colors->orange = "#FFA500";
foreach ($colors as $key => $value) : ?>
<p style="background-color:<?= $value ?>">
<?= $key ?> -> <?= $value ?>
</p>
<?php endforeach; ?>
For the sake of completeness:
The float
property removes a element from the flow of the HTML too, e.g.
float: right
Pointing CATALINA_BASE
to a different directory from CATALINA_HOME
allows you to separate the configuration directory from the binaries directory.
By default, CATALINA_BASE
(configurations) and CATALINA_HOME
(binaries) point to the same folder, but separating the configurations from the binaries can help you to run multiple instances of Tomcat side by side without duplicating the binaries.
It is also useful when you want to update the binaries, without modifying, or needing to backup/restore your configuration files for Tomcat.
There is an easier way to set CATALINA_BASE now with the makebase
utility. I have posted a tutorial that covers this subject at http://blog.rasia.io/blog/how-to-easily-setup-lucee-in-tomcat.html along with a video tutorial at
https://youtu.be/nuugoG5c-7M
To take advantage of this feature, simply create the config directory and point to it with the CATALINA_BASE
environment variable. You will have to put some files in that directory:
conf
directory from the original Tomcat installation directory, including its contents, and ensure that Tomcat has read permissions to it. Edit the configuration files according to your needs.logs
directory if conf/logging.properties
points to ${catalina.base}/logs
, and ensure that Tomcat has read/write permissions to it.temp
directory if you are not overriding the default of $CATALINA_TMPDIR
which points to ${CATALINA_BASE}/temp
, and ensure that Tomcat has write permissions to it.work
directory which defaults to ${CATALINA_BASE}/work
, and ensure that Tomcat has write permissions to it.private
modifier will make your class inaccessible from outside, so there wouldn't be any advantage of this and I think that is why it is illegal and only public
, abstract
& final
are permitted.
Note : Even you can not make it protected
.
Here's a version using the excellent requests library:
from requests import session
payload = {
'action': 'login',
'username': USERNAME,
'password': PASSWORD
}
with session() as c:
c.post('http://example.com/login.php', data=payload)
response = c.get('http://example.com/protected_page.php')
print(response.headers)
print(response.text)
set Text box Border style to None then write this code to container form "paint" event
private void Form1_Paint(object sender, PaintEventArgs e)
{
System.Drawing.Rectangle rect = new Rectangle(TextBox1.Location.X,
TextBox1.Location.Y, TextBox1.ClientSize.Width, TextBox1.ClientSize.Height);
rect.Inflate(1, 1); // border thickness
System.Windows.Forms.ControlPaint.DrawBorder(e.Graphics, rect,
Color.DeepSkyBlue, ButtonBorderStyle.Solid);
}
You only have to set the ViewGroup with the attribute:
android:focusableInTouchMode="true"
The ViewGroup is the layout that includes every child view.
This one worked for me, try this
[RegularExpression("^[a-zA-Z &\-@.]*$", ErrorMessage = "--Your Message--")]
or MVC 2.0:
<%= Html.RadioButtonFor(model => model.blah, true) %> Yes
<%= Html.RadioButtonFor(model => model.blah, false) %> No
Put this in your CSS:
white-space:nowrap;
Get more information here: http://www.w3.org/wiki/CSS/Properties/white-space
white-space
The white-space
property declares how white space inside the element is handled.
Values
normal
This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.
pre
This value prevents user agents from collapsing sequences of white space. Lines are only broken at newlines in the source, or at occurrences of "\A" in generated content.
nowrap
This value collapses white space as for 'normal', but suppresses line breaks within text.
pre-wrap
This value prevents user agents from collapsing sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.
pre-line
This value directs user agents to collapse sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.
inherit
Takes the same specified value as the property for the element's parent.
In the first class, sayHi()
is actually an instance method which you are calling as a static method and you get away with it because sayHi()
never refers to $this
.
Static functions are associated with the class, not an instance of the class. As such, $this
is not available from a static context ($this
isn't pointing to any object).
here after a simple solution using sscanf
:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char str[256]="ab234cid*(s349*(20kd";
char tmp[256];
int main()
{
int x;
tmp[0]='\0';
while (sscanf(str,"%[^0123456789]%s",tmp,str)>1||sscanf(str,"%d%s",&x,str))
{
if (tmp[0]=='\0')
{
printf("%d\r\n",x);
}
tmp[0]='\0';
}
}
I had to make some changes to make it work, as some things seem to have changed in the meantime:
Here's a working example, hope this helps (I'm using JodaTime but in this case SimpleDate would be sufficient):
import java.util.Date;
import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.joda.time.DateTime;
public class DateAdapter extends XmlAdapter<Object, Object> {
@Override
public Object marshal(Object dt) throws Exception {
return new DateTime((Date) dt).toString("YYYY-MM-dd");
}
@Override
public Object unmarshal(Object s) throws Exception {
return DatatypeConverter.parseDate((String) s).getTime();
}
}
In the xsd, I have followed the excellent references given above, so I have included this xml annotation:
<xsd:appinfo>
<jaxb:schemaBindings>
<jaxb:package name="at.mycomp.xml" />
</jaxb:schemaBindings>
<jaxb:globalBindings>
<jaxb:javaType name="java.util.Date" xmlType="xsd:date"
parseMethod="at.mycomp.xml.DateAdapter.unmarshal"
printMethod="at.mycomp.xml.DateAdapter.marshal" />
</jaxb:globalBindings>
</xsd:appinfo>
You will need to know something about the URLs, like do they have a specific directory or some query string element because you have to match for something. Otherwise you will have to redirect on the 404. If this is what is required then do something like this in your .htaccess:
ErrorDocument 404 /index.php
An error page redirect must be relative to root so you cannot use www.mydomain.com.
If you have a pattern to match too then use 301 instead of 302 because 301 is permanent and 302 is temporary. A 301 will get the old URLs removed from the search engines and the 302 will not.
Mod Rewrite Reference: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html
src="/clock.js"
be careful it's root of the domain.
P.S. and please use lowercase for attribute names.
I think jdk has certain features which can be used along with particular framework. Well call it SDK as a whole.
Like Android or Blackberry both use java along with their framework.
Powershell provides a lot of built-in support for common parameter scenarios, including mandatory parameters, optional parameters, "switch" (aka flag) parameters, and "parameter sets."
By default, all parameters are optional. The most basic approach is to simply check each one for $null
, then implement whatever logic you want from there. This is basically what you have already shown in your sample code.
If you want to learn about all of the special support that Powershell can give you, check out these links:
Run the command prompt as admin and cd to bin directory of MySQL
Generally it is (C:\Program Files\MySQL\mysql-5.6.36-winx64\bin)
Run command : mysqld --install. (This command will install MySQL services and if services already installed it will prompt.)
Run below commands to start and stop server
To start : net start mysql
To stop : net stop mysql
Run mysql command.
Enjoy !!
Here's some variety for you with several sizes and hover animations.. demo(link)
<ul>
<li>Large</li>
<li>Medium</li>
<li>Small</li>
<li>Switch</li>
</ul>
<ul>
<li class="ele">
<div class="x large"><b></b><b></b><b></b><b></b></div>
<div class="x spin large"><b></b><b></b><b></b><b></b></div>
<div class="x spin large slow"><b></b><b></b><b></b><b></b></div>
<div class="x flop large"><b></b><b></b><b></b><b></b></div>
<div class="x t large"><b></b><b></b><b></b><b></b></div>
<div class="x shift large"><b></b><b></b><b></b><b></b></div>
</li>
<li class="ele">
<div class="x medium"><b></b><b></b><b></b><b></b></div>
<div class="x spin medium"><b></b><b></b><b></b><b></b></div>
<div class="x spin medium slow"><b></b><b></b><b></b><b></b></div>
<div class="x flop medium"><b></b><b></b><b></b><b></b></div>
<div class="x t medium"><b></b><b></b><b></b><b></b></div>
<div class="x shift medium"><b></b><b></b><b></b><b></b></div>
</li>
<li class="ele">
<div class="x small"><b></b><b></b><b></b><b></b></div>
<div class="x spin small"><b></b><b></b><b></b><b></b></div>
<div class="x spin small slow"><b></b><b></b><b></b><b></b></div>
<div class="x flop small"><b></b><b></b><b></b><b></b></div>
<div class="x t small"><b></b><b></b><b></b><b></b></div>
<div class="x shift small"><b></b><b></b><b></b><b></b></div>
<div class="x small grow"><b></b><b></b><b></b><b></b></div>
</li>
<li class="ele">
<div class="x switch"><b></b><b></b><b></b><b></b></div>
</li>
</ul>
css
.ele div.x {
-webkit-transition-duration:0.5s;
transition-duration:0.5s;
}
.ele div.x.slow {
-webkit-transition-duration:1s;
transition-duration:1s;
}
ul { list-style:none;float:left;display:block;width:100%; }
li { display:inline;width:25%;float:left; }
.ele { width:25%;display:inline; }
.x {
float:left;
position:relative;
margin:0;
padding:0;
overflow:hidden;
background:#CCC;
border-radius:2px;
border:solid 2px #FFF;
transition: all .3s ease-out;
cursor:pointer;
}
.x.large {
width:30px;
height:30px;
}
.x.medium {
width:20px;
height:20px;
}
.x.small {
width:10px;
height:10px;
}
.x.switch {
width:15px;
height:15px;
}
.x.grow {
}
.x.spin:hover{
background:#BB3333;
transform: rotate(180deg);
}
.x.flop:hover{
background:#BB3333;
transform: rotate(90deg);
}
.x.t:hover{
background:#BB3333;
transform: rotate(45deg);
}
.x.shift:hover{
background:#BB3333;
}
.x b{
display:block;
position:absolute;
height:0;
width:0;
padding:0;
margin:0;
}
.x.small b {
border:solid 5px rgba(255,255,255,0);
}
.x.medium b {
border:solid 10px rgba(255,255,255,0);
}
.x.large b {
border:solid 15px rgba(255,255,255,0);
}
.x.switch b {
border:solid 10px rgba(255,255,255,0);
}
.x b:nth-child(1){
border-top-color:#FFF;
top:-2px;
}
.x b:nth-child(2){
border-left-color:#FFF;
left:-2px;
}
.x b:nth-child(3){
border-bottom-color:#FFF;
bottom:-2px;
}
.x b:nth-child(4){
border-right-color:#FFF;
right:-2px;
}
Haven't seen this solution yet so here's how I did it without using read_csv:
df.rename(columns={'A':'','B':''})
If you rename all your column names to empty strings your table will return without a header.
And if you have a lot of columns in your table you can just create a dictionary first instead of renaming manually:
df_dict = dict.fromkeys(df.columns, '')
df.rename(columns = df_dict)
You can find the answer here: Is there a minlength validation attribute in HTML5?
Therefore this should do the job:
<input pattern=".{6,6}">
I was facing the same issue, I resolved this by replacing dependencies in App level Build.gradle file
"""
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'androidx.multidex:multidex:2.0.0'
testImplementation 'junit:junit:4.12'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
androidTestImplementation 'com.androidx.support.test:runner:1.1.0'
androidTestImplementation 'com.androidx.support.test.espresso:espresso-core:3.1.0'
BY
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation platform('com.google.firebase:firebase-bom:26.1.1')
implementation 'com.google.firebase:firebase-analytics'
implementation 'androidx.multidex:multidex:2.0.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.androidx.support.test:runner:1.1.0'
androidTestImplementation 'com.androidx.support.test.espresso:espresso-core:3.1.0'
This resolves my issue.
I am using the following code to write vertical text in a page. Firefox 3.5+, webkit, opera 10.5+ and IE
.rot-neg-90 {
-moz-transform:rotate(-270deg);
-moz-transform-origin: bottom left;
-webkit-transform: rotate(-270deg);
-webkit-transform-origin: bottom left;
-o-transform: rotate(-270deg);
-o-transform-origin: bottom left;
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
}
This is a nice example: The Repository Pattern Example in C#
Basically, repository hides the details of how exactly the data is being fetched/persisted from/to the database. Under the covers:
git rev-parse
is an ancillary plumbing
command primarily used for manipulation.
One common usage of git rev-parse
is to print the SHA1 hashes given a revision specifier. In addition, it has various options to format this output such as --short
for printing a shorter unique SHA1.
There are other use cases as well (in scripts and other tools built on top of git) that I've used for:
--verify
to verify that the specified object is a valid git object.--git-dir
for displaying the abs/relative path of the the .git
directory.--is-inside-git-dir
or within a work-tree using --is-inside-work-tree
--is-bare-repository
--branches
), tags (--tags
) and the refs can also be filtered based on the remote (using --remote
)--parse-opt
to normalize arguments in a script (kind of similar to getopt
) and print an output string that can be used with eval
Massage
just implies that it is possible to convert the info from one form into another i.e. a transformation command. These are some quick examples I can think of:
A..B
for git log
or git diff
into the equivalent arguments for the underlying plumbing command as B ^A
Use this form to ancient version of android.
ImageView myImageView;
myImageView = (ImageView) findViewById(R.id.img);
AlphaAnimation alpha = new AlphaAnimation(0.5F, 0.5F);
alpha.setDuration(0);
alpha.setFillAfter(true);
myImageView.startAnimation(alpha);
In swift 5, I used following code to disable the textfield
override func viewDidLoad() {
super.viewDidLoad()
self.textfield.isEnabled = false
//e.g
self.design.isEnabled = false
}
You can use Humanizer package with Humanize Enums possiblity. An eaxample:
enum PublishStatusses
{
[Description("Custom description")]
NotCompleted,
AlmostCompleted,
Error
};
then you can use Humanize
extension method on enum directly:
var st1 = PublishStatusses.NotCompleted;
var str1 = st1.Humanize(); // will result in Custom description
var st2 = PublishStatusses.AlmostCompleted;
var str2 = st2.Humanize(); // will result in Almost completed (calculated automaticaly)
when I started xampp on my windows 10 there were many options available, unfortunately every one of them failed. I ll list them so that you don't go through all of them again.
1) i installed xampp initially in a different drive and not c because of UAC issues so i uninstalled Xampp and installed it again in c (didn't work) 2) while reinstalling i deactivated the antivirus as setup said that some installing might not end up properly(realized it doesn't matter :) lmao) 3) i tried to change ports several times of xampp from 80 to some different number like 8080 etc. still nothing happened 4) i then tried using firefox as it is believed that internet explorer or internet edge is not a good browser for xampp 5) after that i went to config file i.e config.inc inside phpmyadmin folder and did some crap as were given in the instructions. Failure it was 6) then i closed laptop and went to sleep(XD srry leave this point) 7) then i tried searching for windows web services in the services.msc to disable it. i couldn't find it
On eighth time i got success.This is what i did 8)In control panel, where you have actions , modules PIDs, Ports you will see Services under which you will see gray boxes which are actually checkboxes but are empty initially. i checked it so that xampp services start and apache services start. now you will see them ticked. After that just change the port of xampp and apache to 80.
I hope it helps. cheers ;)
I had exactly this problem with the exception that the Person class had a embedded key class. My own solution was to join them in the query AND remove
@Fetch(FetchMode.JOIN)
My embedded id class:
@Embeddable
public class MessageRecipientId implements Serializable {
@ManyToOne(targetEntity = Message.class, fetch = FetchType.LAZY)
@JoinColumn(name="messageId")
private Message message;
private String governmentId;
public MessageRecipientId() {
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
public String getGovernmentId() {
return governmentId;
}
public void setGovernmentId(String governmentId) {
this.governmentId = governmentId;
}
public MessageRecipientId(Message message, GovernmentId governmentId) {
this.message = message;
this.governmentId = governmentId.getValue();
}
}
There is no way to elegantly handle integer-based enumerated types. You might think of using a string-based enumeration instead of your solution. Not a preferred way all the times, but it still exists.
public enum Port {
/**
* The default port for the push server.
*/
DEFAULT("443"),
/**
* The alternative port that can be used to bypass firewall checks
* made to the default <i>HTTPS</i> port.
*/
ALTERNATIVE("2197");
private final String portString;
Port(final String portString) {
this.portString = portString;
}
/**
* Returns the port for given {@link Port} enumeration value.
* @return The port of the push server host.
*/
public Integer toInteger() {
return Integer.parseInt(portString);
}
}
Without VBA...
If you can use a helper column, you can use the MATCH
function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match
To simply identify duplicates, use a helper column
Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:
=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")
Drag/copy this forumla down, and it should identify the duplicates.
To highlight cells, use conditional formatting:
With some tinkering, you can use this MATCH
function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.
Something like:
=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))
For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:
=B1="Duplicate"
This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.
While this doesn't allow you to get a datepicker ui, Mozilla does allow the use of pattern, so you can at least get date validation with something like this:
pattern='(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))'
Ultimately I agree with @SuperUberDuper in that Mozilla is way behind on including this natively.
you can try to replace -->
with a different string say, #END#
and do search and replace with your editor when you wish to return the closing tags.
I believe you are trying to compare two strings representing values, the function you are looking for is:
int atoi(const char *nptr);
or
long int strtol(const char *nptr, char **endptr, int base);
these functions will allow you to convert a string to an int/long int:
int val = strtol("555", NULL, 10);
and compare it to another value.
int main (int argc, char *argv[])
{
long int val = 0;
if (argc < 2)
{
fprintf(stderr, "Usage: %s number\n", argv[0]);
exit(EXIT_FAILURE);
}
val = strtol(argv[1], NULL, 10);
printf("%d is %s than 555\n", val, val > 555 ? "bigger" : "smaller");
return 0;
}
Add below code to following files.
app.component.ts
<input type="text" [(ngModel)]="fname" >
{{fname}}
export class appcomponent {
fname:any;
}
app.module.ts
import {FormsModule} from '@angular/forms';
@NgModule({
imports: [ BrowserModule,FormsModule ],
declarations: [ AppComponent],
bootstrap: [ AppComponent ]
})
Hope this helps
If you use NumPy 1.15 (released 2018-07-23) or newer, you can use the printoptions
context manager:
with numpy.printoptions(threshold=numpy.inf):
print(arr)
(of course, replace numpy
by np
if that's how you imported numpy
)
The use of a context manager (the with
-block) ensures that after the context manager is finished, the print options will revert to whatever they were before the block started. It ensures the setting is temporary, and only applied to code within the block.
See numpy.printoptions
documentation for details on the context manager and what other arguments it supports.
You were setting BCC but then overwriting the variable with the FROM
$to = "[email protected]";
$subject .= "".$emailSubject."";
$headers .= "Bcc: ".$emailList."\r\n";
$headers .= "From: [email protected]\r\n" .
"X-Mailer: php";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= 'THE MESSAGE FROM THE FORM';
if (mail($to, $subject, $message, $headers)) {
$sent = "Your email was sent!";
} else {
$sent = ("Error sending email.");
}
import string
print list(string.ascii_lowercase)
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
if you use mvvm and your itemssource is located in your vm. just call INotifyPropertyChanged for your collection property when you want to refresh.
OnPropertyChanged("YourCollectionProperty");
Looping through a table for each row and reading the 1st column value works by using JQuery and DOM logic.
var i = 0;
var t = document.getElementById('flex1');
$("#flex1 tr").each(function() {
var val1 = $(t.rows[i].cells[0]).text();
alert(val1) ;
i++;
});
In Notepad++ on the Language menu you will find the menu item - 'J' and under this menu item chose the language - JSON.
Once you select the JSON language then you won't have to worry about how to save it. When you save it it will by default save it as .JSON file, you have to just select the location of the file.
Thanks, -Sam
Today, in Office 365, Excel has so called 'array functions'.
The filter
function does exactly what you want. No need to use CTRL+SHIFT+ENTER
anymore, a simple enter
will suffice.
In Office 365, your problem would be simply solved by using:
=VLOOKUP(A3, FILTER(A2:C6, B2:B6="B"), 3, FALSE)
.values()
You can call the values()
method on your enum.
for (Direction dir : Direction.values()) {
// do what you want
}
This values()
method is implicitly declared by the compiler. So it is not listed on Enum
doc.
If you try joining C on a field from B before joining B, i.e.:
SELECT A.x,
A.y,
A.z
FROM A
INNER JOIN C
on B.x = C.x
INNER JOIN B
on A.x = B.x
your query will fail, so in this case the order matters.
I just spent about 1 hour to figure out possible solution for the same error.
So what I did under MS WIndows 7 is following
Uninstall all Java packages of all versions.
Download last packages Java SE or JRE for your 32 or 64 Windows and install it.
First install JRE and second is Java SE.
Open text editor and paste this code.
public class Hello {
public static void main(String[] args) {
System.out.println("test");
}
}
Save it like Hello.java
Go to Console and compile it like
javac Hello.java
java Hello
Should be no error.
The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
How would you expect recode to know that a file is Windows-1252? In theory, I believe any file is a valid Windows-1252 file, as it maps every possible byte to a character.
Now there are certainly characteristics which would strongly suggest that it's UTF-8 - if it starts with the UTF-8 BOM, for example - but they wouldn't be definitive.
One option would be to detect whether it's actually a completely valid UTF-8 file first, I suppose... again, that would only be suggestive.
I'm not familiar with the recode tool itself, but you might want to see whether it's capable of recoding a file from and to the same encoding - if you do this with an invalid file (i.e. one which contains invalid UTF-8 byte sequences) it may well convert the invalid sequences into question marks or something similar. At that point you could detect that a file is valid UTF-8 by recoding it to UTF-8 and seeing whether the input and output are identical.
Alternatively, do this programmatically rather than using the recode utility - it would be quite straightforward in C#, for example.
Just to reiterate though: all of this is heuristic. If you really don't know the encoding of a file, nothing is going to tell you it with 100% accuracy.
As a rule of thumb, value for non-class types and const reference for classes. If a class is really small it's probably better to pass by value, but the difference is minimal. What you really want to avoid is passing some gigantic class by value and having it all duplicated - this will make a huge difference if you're passing, say, a std::vector with quite a few elements in it.
After searching, I got this clue: https://instructobit.com/tutorial/108/How-to-share-global-variables-between-files-in-Python
the key is: turn on the function to call the variabel that set to global if a function activated.
then import the variabel again from that file.
i give you the hard example so you can understood:
file chromy.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def opennormal():
global driver
options = Options()
driver = webdriver.Chrome(chrome_options=options)
def gotourl(str):
url = str
driver.get(url)
file tester.py
from chromy import * #this command call all function in chromy.py, but the 'driver' variable in opennormal function is not exists yet. run: dir() to check what you call.
opennormal() #this command activate the driver variable to global, but remember, at the first import you not import it
#then do this, this is the key to solve:
from chromy import driver #run dir() to check what you call and compare with the first dir() result.
#because you already re-import the global that you need, you can use it now
url = 'https://www.google.com'
gotourl(url)
That's the way you call the global variable that you set in a function. cheers don't forget to give credit
Here's a simple example function using python. You can stick in ~/.bashrc
You gotta have a space after the first left curly bracket
The python command needs to be in double quotes to get the variable substitution
Don't forget that semicolon at the end
function count(){ python -c "for num in xrange($1):print num";}
$ count 6
0
1
2
3
4
5
$
I'm using the following
type Props = { children: React.ReactNode };
const MyComponent: React.FC<Props> = ({children}) => {
return (
<div>
{ children }
</div>
);
export default MyComponent;
Go in your project's build.cradle
file and add
defaultConfig {
minSdkVersion versions.minSdk
}`
This makes it that your application conforms to the minimum SDK your device is running.
preg_replace('/[\s]+/mu', ' ', $var);
\s
already contains tabs and new lines, so this above regex appears to be sufficient.
Here's a couple of suggestions:
Use date_range
for the index:
import datetime
import pandas as pd
import numpy as np
todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')
columns = ['A','B', 'C']
Note: we could create an empty DataFrame (with NaN
s) simply by writing:
df_ = pd.DataFrame(index=index, columns=columns)
df_ = df_.fillna(0) # with 0s rather than NaNs
To do these type of calculations for the data, use a numpy array:
data = np.array([np.arange(10)]*3).T
Hence we can create the DataFrame:
In [10]: df = pd.DataFrame(data, index=index, columns=columns)
In [11]: df
Out[11]:
A B C
2012-11-29 0 0 0
2012-11-30 1 1 1
2012-12-01 2 2 2
2012-12-02 3 3 3
2012-12-03 4 4 4
2012-12-04 5 5 5
2012-12-05 6 6 6
2012-12-06 7 7 7
2012-12-07 8 8 8
2012-12-08 9 9 9
Why not:
string NormalizeLength(string value, int maxLength)
{
//check String.IsNullOrEmpty(value) and act on it.
return value.PadRight(maxLength).Substring(0, maxLength);
}
i.e. in the event value.Length < maxLength
pad spaces to the end or truncate the excess.
Below is the right code. Include JS files in following manner:
$(document).ready(function() {_x000D_
$(function() {_x000D_
$('#datetimepicker6').datetimepicker();_x000D_
$('#datetimepicker7').datetimepicker({_x000D_
useCurrent: false //Important! See issue #1075_x000D_
});_x000D_
$("#datetimepicker6").on("dp.change", function(e) {_x000D_
$('#datetimepicker7').data("DateTimePicker").minDate(e.date);_x000D_
});_x000D_
$("#datetimepicker7").on("dp.change", function(e) {_x000D_
$('#datetimepicker6').data("DateTimePicker").maxDate(e.date);_x000D_
});_x000D_
});_x000D_
});
_x000D_
<html>_x000D_
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>_x000D_
_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
<div class="container">_x000D_
<div class='col-md-5'>_x000D_
<div class="form-group">_x000D_
<div class='input-group date' id='datetimepicker6'>_x000D_
<input type='text' class="form-control" />_x000D_
<span class="input-group-addon">_x000D_
<span class="glyphicon glyphicon-calendar"></span>_x000D_
</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class='col-md-5'>_x000D_
<div class="form-group">_x000D_
<div class='input-group date' id='datetimepicker7'>_x000D_
<input type='text' class="form-control" />_x000D_
<span class="input-group-addon">_x000D_
<span class="glyphicon glyphicon-calendar"></span>_x000D_
</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
_x000D_
</html>
_x000D_
If you want to apply the style even after getting struck-trough indication, you can use "!important"
to enforce the style. It may not be a right solution but solve the problem.
If you can generate the Excel file on the server, that is probably the best way. With Excel you can add formatting and get the output to look better. Several Excel options have already been mentioned. If you have a PHP backend, you might consider phpExcel.
If you are trying to do everything on the client in javascript, I don't think Excel is an option. You could create a CSV file and create a data URL to allow the user to download it.
I created a JSFiddle to demonstrate: http://jsfiddle.net/5KRf6/3/
This javascript (assuming you are using jQuery) will take the values out of input boxes in a table and build a CSV formatted string:
var csv = "";
$("table").find("tr").each(function () {
var sep = "";
$(this).find("input").each(function () {
csv += sep + $(this).val();
sep = ",";
});
csv += "\n";
});
If you wish, you can drop the data into a tag on the page (in my case a tag with an id of "csv"):
$("#csv").text(csv);
You can generate a URL to that text with this code:
window.URL = window.URL || window.webkiURL;
var blob = new Blob([csv]);
var blobURL = window.URL.createObjectURL(blob);
Finally, this will add a link to download that data:
$("#downloadLink").html("");
$("<a></a>").
attr("href", blobURL).
attr("download", "data.csv").
text("Download Data").
appendTo('#downloadLink');
Convert the image to a byte[]
and store that in the database.
Add this column to your model:
public byte[] Content { get; set; }
Then convert your image to a byte array and store that like you would any other data:
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using(var ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
public Image ByteArrayToImage(byte[] byteArrayIn)
{
using(var ms = new MemoryStream(byteArrayIn))
{
var returnImage = Image.FromStream(ms);
return returnImage;
}
}
Source: Fastest way to convert Image to Byte array
var image = new ImageEntity()
{
Content = ImageToByteArray(image)
};
_context.Images.Add(image);
_context.SaveChanges();
When you want to get the image back, get the byte array from the database and use the ByteArrayToImage
and do what you wish with the Image
This stops working when the byte[]
gets to big. It will work for files under 100Mb
To include the direction along with the orderBy function:
ng-repeat="card in cards | orderBy:myOrderbyFunction():defaultSortDirection"
where
defaultSortDirection = 0; // 0 = Ascending, 1 = Descending
According to Javax's persistence documentation:
Whether the column is included in SQL UPDATE statements generated by the persistence provider.
It would be best to understand from the official documentation here.
It is actually far easier to add an id to the label in the form itself, for example:
<label for="firstName" id="firstNameLabel">FirstName:</label>
<input type="text" id="firstName" name="firstName" class="input_Field"
pattern="^[a-zA-Z\s\-]{2,25}$" maxlength="25"
title="Alphabetic, Space, Dash Only, 2-25 Characters Long"
autocomplete="on" required
/>
Then, you can simply use something like this:
if (myvariableforpagelang == 'es') {
// set field label to spanish
document.getElementById("firstNameLabel").innerHTML = "Primer Nombre:";
// set field tooltip (title to spanish
document.getElementById("firstName").title = "Alfabética, espacio, guión Sólo, 2-25 caracteres de longitud";
}
The javascript does have to be in a body onload function to work.
Just a thought, works beautifully for me.
I know this is an old post, but I think this is a very important topic, especially nowadays where we have 10M+ records and talk about terabytes of data.
I will also weight in with the following observations. I have about 45M records in my table ([data]), and about 300 records in my [cats] table. I have extensive indexing for all of the queries I am about to talk about.
Consider Example 1:
UPDATE d set category = c.categoryname
FROM [data] d
JOIN [cats] c on c.id = d.catid
versus Example 2:
UPDATE d set category = (SELECT TOP(1) c.categoryname FROM [cats] c where c.id = d.catid)
FROM [data] d
Example 1 took about 23 mins to run. Example 2 took around 5 mins.
So I would conclude that sub-query in this case is much faster. Of course keep in mind that I am using M.2 SSD drives capable of i/o @ 1GB/sec (thats bytes not bits), so my indexes are really fast too. So this may affect the speeds too in your circumstance
If its a one-off data cleansing, probably best to just leave it run and finish. I use TOP(10000) and see how long it takes and multiply by number of records before I hit the big query.
If you are optimizing production databases, I would strongly suggest pre-processing data, i.e. use triggers or job-broker to async update records, so that real-time access retrieves static data.
Pandas Timestamp to datetime.datetime:
pd.Timestamp('2014-01-23 00:00:00', tz=None).to_pydatetime()
datetime.datetime to Timestamp
pd.Timestamp(datetime(2014, 1, 23))
It's quite simple:
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(txt, 'text/html');
// do whatever you want with htmlDoc.getElementsByTagName('a');
According to MDN, to do this in chrome you need to parse as XML like so:
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(txt, 'text/xml');
// do whatever you want with htmlDoc.getElementsByTagName('a');
It is currently unsupported by webkit and you'd have to follow Florian's answer, and it is unknown to work in most cases on mobile browsers.
Edit: Now widely supported
I find that if you're familiar with SQL syntax, using the LINQ query syntax is much clearer, more natural, and makes it easier to spot errors:
var id = 1;
var query =
from post in database.Posts
join meta in database.Post_Metas on post.ID equals meta.Post_ID
where post.ID == id
select new { Post = post, Meta = meta };
If you're really stuck on using lambdas though, your syntax is quite a bit off. Here's the same query, using the LINQ extension methods:
var id = 1;
var query = database.Posts // your starting point - table in the "from" statement
.Join(database.Post_Metas, // the source table of the inner join
post => post.ID, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
meta => meta.Post_ID, // Select the foreign key (the second part of the "on" clause)
(post, meta) => new { Post = post, Meta = meta }) // selection
.Where(postAndMeta => postAndMeta.Post.ID == id); // where statement
The notation that is used in
a[::-1]
means that for a given string/list/tuple, you can slice the said object using the format
<object_name>[<start_index>, <stop_index>, <step>]
This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.
In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.
So,
a = '1234'
print a[::2]
would print
13
Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example
a = '1234'
print a[3:0:-1]
This would return
432
Note, that it doesn't return 4321 because, the stop index is not included.
Now in your case,
str(int(a[::-1]))
would just reverse a given integer, that is stored in a string, and then convert it back to a string
i.e "1234" -> "4321" -> 4321 -> "4321"
If what you are trying to do is just reverse the given string, then simply a[::-1] would work .
You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList
for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}
<html>
<?php
echo $_POST['c']." | ".$_POST['d']." | ".$_POST['e'];
?>
<form action="test.php" method="POST">
<input type="hidden" name="c" value="toto98">
<input type="hidden" name="d" value="toto97">
<input type="hidden" name="e" value="toto aaaaaaaaaaaaaaaaaaaa">
<a href="" onclick="document.forms[0].submit();return false;">Click</a>
</form>
</html>
So easy.
So easy.
To produce the output in your comment to your post, this will do it:
use strict;
use warnings;
my @other_array = (0,0,0,1,2,2,3,3,3,4);
my @array;
my %uniqs;
$uniqs{$_}++ for @other_array;
foreach (keys %uniqs) { $array[$_]=$uniqs{$_} }
print "array[$_] = $array[$_]\n" for (0..$#array);
Output:
array[0] = 3
array[1] = 1
array[2] = 2
array[3] = 3
array[4] = 1
This is different than your stated algorithm of producing a parallel array with zero values, but it is a more Perly way of doing it...
If you must have a parallel array that is the same size as your first array with the elements initialized to 0, this statement will dynamically do it: @array=(0) x scalar(@other_array);
but really, you don't need to do that.
To multiply a column of numbers with a constant(same number), I have done like this.
Let C2
to C12
be different numbers which need to be multiplied by a single number (constant). Then type the numbers from C2
to C12.
In D2
type 1 (unity) and in E2 type formula =PRODUCT(C2:C12,CONSTANT)
. SELECT RIGHT ICON TO APPLY. NOW DRAG E2
THROUGH E12
. YOU HAVE DONE IT.
C D E=PRODUCT(C2:C12,20)
25 1 500
30 600
35 700
40 800
45 900
50 1000
55 1100
60 1200
65 1300
70 1400
75 1500
Maybe your model not linked when migration process is ongoing.
Try to import it in file urls.py
from models import your_file
When the JVM loads classes, or otherwise sees a literal string, or some code intern
s a string, it adds the string to a mostly-hidden lookup table that has one copy of each such string. If another copy is added, the runtime arranges it so that all the literals refer to the same string object. This is called "interning". If you say something like
String s = "test";
return (s == "test");
it'll return true
, because the first and second "test" are actually the same object. Comparing interned strings this way can be much, much faster than String.equals
, as there's a single reference comparison rather than a bunch of char
comparisons.
You can add a string to the pool by calling String.intern()
, which will give you back the pooled version of the string (which could be the same string you're interning, but you'd be crazy to rely on that -- you often can't be sure exactly what code has been loaded and run up til now and interned the same string). The pooled version (the string returned from intern
) will be equal to any identical literal. For example:
String s1 = "test";
String s2 = new String("test"); // "new String" guarantees a different object
System.out.println(s1 == s2); // should print "false"
s2 = s2.intern();
System.out.println(s1 == s2); // should print "true"
After going through all the solutions here, the easiest way to find the loaded php.ini
file is to go into phpinfo
on the loaded MAMP webpage, which will show you the loaded php.ini file.
This will also confirm if the parameters you change, like max_file_size, have updated correctly.
For a div-Element you could just set the opacity via a class to enable or disable the effect.
.mute-all {
opacity: 0.4;
}
By using System.Windows.Forms.Timer
class you can achieve what you need.
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();
void timer_Tick(object sender, EventArgs e)
{
//Call method
}
By using stop() method you can stop timer.
t.Stop();
You can use Javascript to get the viewport width and height. Then pass the values back via a hidden form input or ajax.
var width = $(window).width();
var height = $(window).height();
Assuming you have: JQuery framework.
First, add these hidden form inputs to store the width and height until postback.
<asp:HiddenField ID="width" runat="server" />
<asp:HiddenField ID="height" runat="server" />
Next we want to get the window (viewport) width and height. JQuery has two methods for this, aptly named width() and height().
Add the following code to your .aspx file within the head element.
<script type="text/javascript">
$(document).ready(function() {
$("#width").val() = $(window).width();
$("#height").val() = $(window).height();
});
</script>
Result
This will result in the width and height of the browser window being available on postback. Just access the hidden form inputs like this:
var TheBrowserWidth = width.Value;
var TheBrowserHeight = height.Value;
This method provides the height and width upon postback, but not on the intial page load.
Note on UpdatePanels: If you are posting back via UpdatePanels, I believe the hidden inputs need to be within the UpdatePanel.
Alternatively you can post back the values via an ajax call. This is useful if you want to react to window resizing.
Update for jquery 3.1.1
I had to change the JavaScript to:
$("#width").val($(window).width());
$("#height").val($(window).height());
The easiest way I found, summarized in a few pictures:
You could skip a few steps (up to step 4) by simply navigating to chrome://settings/languages
right away.
I vote for toFixed()
, but, for the record, here's another way that uses bit shifting to cast the number to an int. So, it always rounds towards zero (down for positive numbers, up for negatives).
var rounded = ((num * 10) << 0) * 0.1;
But hey, since there are no function calls, it's wicked fast. :)
And here's one that uses string matching:
var rounded = (num + '').replace(/(^.*?\d+)(\.\d)?.*/, '$1$2');
I don't recommend using the string variant, just sayin.
Recently default Xcode project settings set ONLY_ACTIVE_ARCH (Build Active Architecture Only) to yes for Debug configuration.
So your build can not be installed on different hardware than the one you use for development.
Change this setting and installation should go fine.
place jakarta and delete javax
if you download servlet.api.jar :
NOTICE : this answer every time is not correct ( can be javax in JEE )
Correct
jakarta.servlet.*;
Incorrect
javax.servlet.*;
else :
place jar files into JAVA_HOME/jre/lib/ext
Other way:
sudo apt-get install python-psycopg2 python-mysqldb
it seems to be the java SimpleDateFormat : http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
here are some tests i did around 11:30pm on the 20th of May 2015
${__time(dd-mmm-yyyy HHmmss)} 20-032-2015 233224
${__time(d-MMM-yyyy hhmmss)} 20-May-2015 113224
${__time(dd-m-yyyy hhmmss)} 20-32-2015 113224
${__time(D-M-yyyy hhmmss)} 140-5-2015 113224
${__time(DD-MM-yyyy)} 140-05-2015
If you're using .NET don't reivent the wheel. See System.Device.Location. Credit to fnx in the comments in another answer.
using System.Device.Location;
double lat1 = 45.421527862548828D;
double long1 = -75.697189331054688D;
double lat2 = 53.64135D;
double long2 = -113.59273D;
GeoCoordinate geo1 = new GeoCoordinate(lat1, long1);
GeoCoordinate geo2 = new GeoCoordinate(lat2, long2);
double distance = geo1.GetDistanceTo(geo2);
As already answered, this is per spec not possible with the fetch
-API, yet. But I have to note:
If you are on node
, there's the querystring
package. It can stringify/parse objects/querystrings:
var querystring = require('querystring')
var data = { key: 'value' }
querystring.stringify(data) // => 'key=value'
...then just append it to the url to request.
However, the problem with the above is, that you always have to prepend a question mark (?
). So, another way is to use the parse
method from nodes url
package and do it as follows:
var url = require('url')
var data = { key: 'value' }
url.format({ query: data }) // => '?key=value'
See query
at https://nodejs.org/api/url.html#url_url_format_urlobj
This is possible, as it does internally just this:
search = obj.search || (
obj.query && ('?' + (
typeof(obj.query) === 'object' ?
querystring.stringify(obj.query) :
String(obj.query)
))
) || ''
if you need to downloadable pdf of a specific page just add button like this
<h4 onclick="window.print();"> Print </h4>
use window.print() to print your all page not just a div
If you need to recal an Activity that is in bacgrounde, from your service, I suggest the following link. Intent.FLAG_ACTIVITY_NEW_TASK is not the solution.
In MySQL
set foreign_key_checks=0;
UPDATE patient INNER JOIN patient_address
ON patient.id_no=patient_address.id_no
SET patient.id_no='8008255601088',
patient_address.id_no=patient.id_no
WHERE patient.id_no='7008255601088';
Note that foreign_key_checks only temporarily set foreign key checking false. So it need to execute every time before update statement. We set it 0 as if we update parent first then that will not be allowed as child may have already that value. And if we update child first then that will also be not allowed as parent may not have that value from which we are updating. So we need to set foreign key check. Another thing is that if you are using command line tool to use this query then put care to mention spaces in place where i put new line or ENTER in code. As command line take it in one line, so it may happen that two words stick as patient_addressON which create syntax error.
Try this:
UPDATE mysql.user SET password=password("elephant7") where user="root"
There is no error in the following piece of code:
float arr[4];
arr[0] = 6.28;
arr[1] = 2.50;
arr[2] = 9.73;
arr[3] = 4.364;
std::vector<float*> vec = std::vector<float*>();
vec.push_back(arr);
float* ptr = vec.front();
for (int i = 0; i < 3; i++)
printf("%g\n", ptr[i]);
OUTPUT IS:
6.28
2.5
9.73
4.364
IN CONCLUSION:
std::vector<double*>
is another possibility apart from
std::vector<std::array<double, 4>>
that James McNellis suggested.
The accepted answer works for columns that are of datatype string
. For completeness: I come across this question when searching how to do this when the columns are of datatypes: date and time.
df.apply(lambda r : pd.datetime.combine(r['date_column_name'],r['time_column_name']),1)
throw
will terminate the further execution & expose message string on catch the error.
try {
throw "I'm Evil"
console.log("You'll never reach to me", 123465)
} catch (e) {
console.log(e); // I'm Evil
}
_x000D_
Console after throw will never be reached cause of termination.
throw new Error
exposes an error event with two params name & message. It also terminate further execution
try {
throw new Error("I'm Evil")
console.log("You'll never reach to me", 123465)
} catch (e) {
console.log(e.name, e.message); // Error I'm Evil
}
_x000D_
And just for completeness, this works also, though is not technically the correct way to do it -
try {
throw Error("I'm Evil")
console.log("You'll never reach to me", 123465)
} catch (e) {
console.log(e.name, e.message); // Error I'm Evil
}
console.log(typeof(new Error("hello"))) // object
console.log(typeof(Error)) // function
_x000D_
Based on my Comment here is one way to get what you want done:
Start byt selecting any cell in your range and Press Ctrl + T
This will give you this pop up:
make sure the Where is your table text is correct and click ok you will now have:
Now If you add a column header in D it will automatically be added to the table all the way to the last row:
Now If you enter a formula into this column:
After you enter it, the formula will be auto filled all the way to last row:
Now if you add a new row at the next row under your table:
Once entered it will be resized to the width of your table and all columns with formulas will be added also:
Hope this solves your problem!
select method > right click > References > Workspace/Project (your preferred context )
or
(Ctrl+Shift+G)
This will show you a Search view containing the hierarchy of class and method which using this method.
I had the same issue. And in my case the fix was pretty simple. The trick is to simply add the ".exe" to your compilers path. So, instead of :
SET(CMAKE_C_COMPILER C:/MinGW/bin/gcc)
It should be
SET(CMAKE_C_COMPILER C:/MinGW/bin/gcc.exe)
The same applies for g++.
file_name=test.log
# set first K lines:
K=1000
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K ))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so
split -l 300000 file_name
will output xaa
with 300k lines and xab
with 100k lines, for an input with 400k lines.
try this
in the php.ini file uncomment this
extension_dir = "./"
"remove semicolon"
Click "view details" to find the inner exception.
You can tell it's playing using:
AVPlayer *player = ...
if ((player.rate != 0) && (player.error == nil)) {
// player is playing
}
Swift 3 extension:
extension AVPlayer {
var isPlaying: Bool {
return rate != 0 && error == nil
}
}
View level
You can disable hardware acceleration for an individual view at runtime with the following code:
myView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
Security Settings -> Advanced Audit Policy -> System Audit -> Logon/Logoff -> Audit Other Logon/Off Events -> On Success
Enables the following:
4800 - workstation locked
4801 - workstation unlocked
4802 - screensaver invoke
4803 - screensaver dismissed
Windows 10 professional
Basically you can create a regex to fulfil your needs and then assign that pattern to your input field.
Or for a more direct approach:
<input type="number" require ng-pattern="<your regex here>">
More info @ angular docs here and here (built-in validators)
You could just comment the maven dependency for a while:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>-->
</dependencies>
It worked fine for me
Disabling it from
application.properties
is deprecated for Spring Boot 2.0
You can use Math.Ceiling
http://msdn.microsoft.com/en-us/library/system.math.ceiling%28v=VS.100%29.aspx
The CSS solutions don't appear to be widely available as of mid-2013. Instead...
Nicholas Zakas explains that Modernizr applies a no-touch
CSS class when the browser doesn’t support touch.
Or detect in JavaScript with a simple piece of code, allowing you to implement your own Modernizr-like solution:
<script>
document.documentElement.className +=
(("ontouchstart" in document.documentElement) ? ' touch' : ' no-touch');
</script>
Then you can write your CSS as:
.no-touch .myClass {
...
}
.touch .myClass {
...
}
PuTTY Session Manager is a tool that allows system administrators to organise their PuTTY sessions into folders and assign hotkeys to favourite sessions. Multiple sessions can be launched with one click. Requires MS Windows and the .NET 2.0 Runtime.
module.exports = { ClientIDUnsplash : 'SuperSecretKey' };
var { ClientIDUnsplash } = require('./FileOne');
This example works best for React.
I had the exact same issue, I have kind of the same configuration as your exemple and I got it working by removing the line :
ssl on;
To quote the doc:
If HTTP and HTTPS servers are equal, a single server that handles both HTTP and HTTPS requests may be configured by deleting the directive “ssl on” and adding the ssl parameter for *:443 port
Generally it means that you are providing an index for which a list element does not exist.
E.g, if your list was [1, 3, 5, 7]
, and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.
\l - Display database
\c - Connect to database
\dn - List schemas
\dt - List tables inside public schemas
\dt schema1. - List tables inside particular schemas. For eg: 'schema1'.
Three steps needed:
Explicitly mark SSL2.0, TLS1.0, TLS1.1 as forbidden on your server machine, by adding Enabled=0
and DisabledByDefault=1
to your registry (the full path is HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols
). See screen for details
Explicitly enable TLS1.2
by following the steps from 1. Just use Enabled=1
and DisabledByDefault=0
respectively.
NOTE: verify server version: Windows Server 2003
does not support the TLS 1.2
protocol
Enable TLS1.2
only on app level, like @John Wu suggested above.
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Hope this guide helps.
UPDATE As @Subbu mentioned: Official guide
If you want to use straight PowerShell check out the below code.
$content = Get-Content C:\Users\You\Documents\test.txt
foreach ($line in $content)
{
Write-Host $line
}
The OP needed to cast as string outside the {% set ... %}
.
But if that not your case you can do:
{% set curYear = 2013 | string() %}
Note that you need the parenthesis on that jinja filter.
If you're concatenating 2 variables, you can also use the ~
custom operator.
?Handling errors is very important in programming. You do need to show the user what went wrong. In very few cases you can ignore the errors. This is it is very bad programming practice.
I personally use a CLR implementation of the Jaro-Winkler algorithm which seems to work pretty well - it struggles a bit with strings longer than about 15 characters and doesn't like matching email addresses but otherwise is quite good - full implementation guide can be found here
If you are unable to use CLR functions for whatever reasons, maybe you could try running the data through an SSIS package (using the fuzzy transformation lookup) - detailed here
$.validator.addMethod("mydate", function (value, element) {
return this.optional(element) || /^(\d{4})(-|\/)(([0-1]{1})([1-2]{1})|([0]{1})([0-9]{1}))(-|\/)(([0-2]{1})([1-9]{1})|([3]{1})([0-1]{1}))/.test(value);
});
you can input like yyyy-mm-dd
also yyyy/mm/dd
but can't judge the the size of the month sometime Feb just 28 or 29 days.
I know this sounds a bit weird but have any of you tried to set the margin
of the form page body tag to 0.
The problem is actually pretty simple, the reason is that the body tag margin
by default is set to 8px
(depending on browser) and if you just set it to 0 then it fixes the scrollbar.
The js configuration I have is as follows and it works well without changing the css of fancybox.
$(".iframe").fancybox({
'autoScale' : false,
'autoDimensions' : false,
'transitionIn' : 'none',
'transitionOut' : 'none',
'type' : 'iframe'
});
Sorry because I cannot comment...
I had the same problem. In my case the problem was related to trying to restore in an old sql server folder (that existed on the server). This is due to old sql server backup (i.e. SQL Server 2012 Backup) restored in a new sql server (SQL Server 2014). The real issue is not too different from @marc_s answer. Anyway, I changed only the target folder to the new SQL Server DATA folder.
RubyMine is so awesome. Everything just works. I could go on and on. Code completion is fast, smooth, and accurate. Formatting is instantaneous. Project navigation is easy and without struggle. You can pop open any file with a few keystrokes. You don't even need to keep the project tree open, but it's there if you want. You can configure just about any aspect of it to behave exactly how you want.
NetBeans, Eclipse, and RubyMine all have more or less the same set of features. However, RubyMine is just so much more cleanly designed and easy to use. There's nothing awkward or clunky about it. There are all these nice little design touches that show how JetBrains really put thought into it instead of just amassing a big pile of features.
Incidentally RubyMine can do a lot of the things that Vim can do like select and edit a column of text or split the view into several editing panels with different files in them.
This is what you should do. Please do not use stringify
nor < >
.
function arraysEqual(a, b) {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length !== b.length) return false;
// If you don't care about the order of the elements inside
// the array, you should sort both arrays here.
// Please note that calling sort on an array will modify that array.
// you might want to clone your array first.
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error. (MSDN, SqlConnection.ConnectionTimeout Property, 2013)
As the other answers have described, lit
and typedLit
are how to add constant columns to DataFrames. lit
is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.
You'll commonly be using lit
to create org.apache.spark.sql.Column
objects because that's the column type required by most of the org.apache.spark.sql.functions
.
Suppose you have a DataFrame with a some_date
DateType column and would like to add a column with the days between December 31, 2020 and some_date
.
Here's your DataFrame:
+----------+
| some_date|
+----------+
|2020-09-23|
|2020-01-05|
|2020-04-12|
+----------+
Here's how to calculate the days till the year end:
val diff = datediff(lit(Date.valueOf("2020-12-31")), col("some_date"))
df
.withColumn("days_till_yearend", diff)
.show()
+----------+-----------------+
| some_date|days_till_yearend|
+----------+-----------------+
|2020-09-23| 99|
|2020-01-05| 361|
|2020-04-12| 263|
+----------+-----------------+
You could also use lit
to create a year_end
column and compute the days_till_yearend
like so:
import java.sql.Date
df
.withColumn("yearend", lit(Date.valueOf("2020-12-31")))
.withColumn("days_till_yearend", datediff(col("yearend"), col("some_date")))
.show()
+----------+----------+-----------------+
| some_date| yearend|days_till_yearend|
+----------+----------+-----------------+
|2020-09-23|2020-12-31| 99|
|2020-01-05|2020-12-31| 361|
|2020-04-12|2020-12-31| 263|
+----------+----------+-----------------+
Most of the time, you don't need to use lit
to append a constant column to a DataFrame. You just need to use lit
to convert a Scala type to a org.apache.spark.sql.Column
object because that's what's required by the function.
See the datediff
function signature:
As you can see, datediff
requires two Column arguments.
You could use Linq's Aggregate function:
string s = "the\nquick\tbrown\rdog,jumped;over the lazy fox.";
char[] chars = new char[] { ' ', ';', ',', '\r', '\t', '\n' };
string snew = chars.Aggregate(s, (c1, c2) => c1.Replace(c2, '\n'));
Here's the extension method:
public static string ReplaceAll(this string seed, char[] chars, char replacementCharacter)
{
return chars.Aggregate(seed, (str, cItem) => str.Replace(cItem, replacementCharacter));
}
Extension method usage example:
string snew = s.ReplaceAll(chars, '\n');
Perl solution similar to Chris Kannon's awk solution:
perl -lane 'print $F[$#F-1]' file
These command-line options are used:
n
loop around every line of the input file, do not automatically print every line
l
removes newlines before processing, and adds them back in afterwards
a
autosplit mode – split input lines into the @F
array. Defaults to splitting on whitespace
e
execute the perl code
The @F
autosplit array starts at index [0] while awk fields start with $1.
$#F
is the number of elements in @F
You can use the provided system views to do this:
eg
select * from INFORMATION_SCHEMA.COLUMNS
where table_name = '[table name]'
alternatively, you can use the system proc sp_help
eg
sp_help '[table name]'
There is no need to kill entire session. In Oracle 18c you could use ALTER SYSTEM CANCEL
:
Cancelling a SQL Statement in a Session
You can cancel a SQL statement in a session using the ALTER SYSTEM CANCEL SQL statement.
Instead of terminating a session, you can cancel a high-load SQL statement in a session. When you cancel a DML statement, the statement is rolled back.
ALTER SYSTEM CANCEL SQL 'SID, SERIAL[, @INST_ID][, SQL_ID]';
If @INST_ID is not specified, the instance ID of the current session is used.
If SQL_ID is not specified, the currently running SQL statement in the specified session is terminated.
Hey I had the same problem. I tried to convert '2017-02-20 12:15:32' varchar to a date with TO_DATE('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS')
and all I received was 2017-02-20 the time disappeared
My solution was to use TO_TIMESTAMP('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS')
now the time doesn't disappear.
check this out,
we can use Keychain instead of NSUserDefaults
class, to store UUID
created by CFUUIDCreate
.
with this way we could avoid for UUID
recreation with reinstallation,
and obtain always same UUID
for same application even user uninstall and reinstall again.
UUID
will recreated just when device reset by user.
I tried this method with SFHFKeychainUtils and it's works like a charm.
I use Hibernate Validator via @Valid
for all input objects (binding and @RequestBody
json, see https://dzone.com/articles/spring-31-valid-requestbody). So @org.hibernate.validator.constraints.SafeHtml
is a good solution for me.
Hibernate SafeHtmlValidator
depends on org.jsoup
, so it's needed to add one more project dependencies:
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.1</version>
</dependency>
For bean User
with field
@NotEmpty
@SafeHtml
protected String name;
for update attempt with value <script>alert(123)</script>
in controller
@PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
public void update(@Valid @RequestBody User user, @PathVariable("id") int id)
or
@PostMapping
public void createOrUpdate(@Valid User user) {
is thrown BindException
for binding and MethodArgumentNotValidException
for @RequestBody
with default message:
name may have unsafe html content
Validator works as well for binding, as before persisting. Apps could be tested at http://topjava.herokuapp.com/
UPDATE: see also comment from @GuyT
CVE-2019-10219 and status of @SafeHtml
We have been made aware of a CVE-2019-10219 related to the @SafeHtml constraint and it was fixed in both 6.0.18.Final and 6.1.0.Final....
However, we came to the conclusion that the @SafeHtml constraint was fragile, highly security-sensitive and depending on an external library that wasn’t designed for this purpose. Having it included in core Hibernate Validator was not a very good idea. That’s why we deprecated it and marked it for removal.There is no magic plan here so our users will have to maintain this constraint themselves
Resume for myself: it is safe and could be used, until solution better be found.
I was facing similar issue.
font-src - is to tell the browser to load the font's from src which is specified after that. font-src: 'self' - this tells to load font family within the same origin or system. font-src: 'self' data: - this tells load font-family within the same origin and the calls made to get data:
You might also get warning "** Failed to decode downloaded font, OTS parsing error: invalid version tag **" Add the following entry in CSP.
font-src: 'self' font
This should now load with no errors.
It is probably little bit late, but I managed to solve it this way -> open with winrar and delete ECLIPSEF.RSA and ECLIPSEF.SF in META-INF folder, moreover put "Main-class: main_class_name" (without ".class") in MANIFEST.MF. Make sure that you pressed "Enter" twice after the last line, otherwise it won't work.
Many of the answers here were valid until recently. For now, the ONLY supported param is url
, and the new share link is as follows...
https://www.linkedin.com/sharing/share-offsite/?url={url}
Make sure url
is encoded, using something like fixedEncodeURIComponent()
.
Source: Official Microsoft.com Linkedin Share Plugin Documentation. All LinkedIn.com links for developer documentation appear to be blank pages now -- perhaps related to the acquisition of LinkedIn by Microsoft.
Once upon a time, you could use these params: title
, summary
, source
. But if you look closely at all of the documentation, there is actually still a way to still set summary, title, etc.! Put these in the <head>
block of the page you want to share...
<meta property='og:title' content='Title of the article"/>
<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>
<meta property='og:description' content='Description that will show in the preview"/>
<meta property='og:url' content='//www.example.com/URL of the article" />
Then LinkedIn will use these! Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.
Not sure you did everything right? Take the URL of the page you are sharing (i.e., example.com, not linkedin.com/share?url=example.com), and input that URL into the following: LinkedIn Post Inspector. This will tell you everything about how your URL is being shared!
This also pulls/invalidates the current cache of your page, and then refreshes it (in case you have a stuck, cached version of your page in LinkedIn's database). Because it pulls the cache, then refreshes it, sometimes it's best to use the LinkedIn Post Inspector twice, and use the second result as the expected output.
Still not sure? Here's an online demo I built with 20+ social share services. Inspect the source code and find out for yourself how exactly the LinkedIn sharing is working.
I have been maintaining a Github Repo that's been tracking social-share URL formats since 2012, check it out: Github: Social Share URLs.
Why not join in on all the social share url's?
This should be faster:
DELETE * FROM table_name;
because RDBMS don't have to look where
is what.
You should be fine with truncate
though:
truncate table table_name
Hmm, from the examples you gave it seems like "$_SERVER['REQUEST_URI']" and the explode() function could help you. You could use explode to break up the URL following the domain name into an array, separating it at each forward-slash.
As a very basic example, something like this could be implemented:
$crumbs = explode("/",$_SERVER["REQUEST_URI"]);
foreach($crumbs as $crumb){
echo ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' ');
}
It is mentioned in the documentation that the builder method NotificationCompat.Builder(Context context)
has been deprecated. And we have to use the constructor which has the channelId
parameter:
NotificationCompat.Builder(Context context, String channelId)
NotificationCompat.Builder Documentation:
This constructor was deprecated in API level 26.0.0-beta1. use NotificationCompat.Builder(Context, String) instead. All posted Notifications must specify a NotificationChannel Id.
Notification.Builder Documentation:
This constructor was deprecated in API level 26. use Notification.Builder(Context, String) instead. All posted Notifications must specify a NotificationChannel Id.
If you want to reuse the builder setters, you can create the builder with the channelId
, and pass that builder to a helper method and set your preferred settings in that method.
I used this code to convert all columns to numeric except the first one:
library(dplyr)
# check structure, row and column number with: glimpse(df)
# convert to numeric e.g. from 2nd column to 10th column
df <- df %>%
mutate_at(c(2:10), as.numeric)
Since the .Rows result is marked as consisting of rows, you can "For Each" it to deal with each row individually, like this:
Function Attendance(rng As Range) As Long
Attendance = 0
For Each rRow In rng.Rows
If WorksheetFunction.Sum(rRow) > 0 Then
Attendance = Attendance + 1
End If
Next
End Function
I use this to check attendance in any of a few categories (different columns) for a list of people (different rows).
(And of course you could use .Columns to do a "For Each" over the columns in the range.)
Using CASCADE means actually telling Django to delete the referenced record. In the poll app example below: When a 'Question' gets deleted it will also delete the Choices this Question has.
e.g Question: How did you hear about us? (Choices: 1. Friends 2. TV Ad 3. Search Engine 4. Email Promotion)
When you delete this question, it will also delete all these four choices from the table. Note that which direction it flows. You don't have to put on_delete=models.CASCADE in Question Model put it in the Choice.
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.dateTimeField('date_published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_legth=200)
votes = models.IntegerField(default=0)
In fact, in R, this operation is very easy:
If the matrix 'a' contains some NaN, you just need to use the following code to replace it by 0:
a <- matrix(c(1, NaN, 2, NaN), ncol=2, nrow=2)
a[is.nan(a)] <- 0
a
If the data frame 'b' contains some NaN, you just need to use the following code to replace it by 0:
#for a data.frame:
b <- data.frame(c1=c(1, NaN, 2), c2=c(NaN, 2, 7))
b[is.na(b)] <- 0
b
Note the difference is.nan
when it's a matrix vs. is.na
when it's a data frame.
Doing
#...
b[is.nan(b)] <- 0
#...
yields: Error in is.nan(b) : default method not implemented for type 'list'
because b is a data frame.
Note: Edited for small but confusing typos
Here is the sample program.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadFromConsole {
public static void main(String[] args) {
System.out.println("Enter here : ");
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String value = bufferRead.readLine();
System.out.println(value);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
You can get it easily when you search in Internet. StackExchange recommends to do some research and put some effort before reaching it.
You can see the println()
statements in the Run
window of Android Studio.
See detailed answer with screenshot here.
All the hidden fields in your fieldset are using the same id, so jquery is only returning the first one. One way to fix this is to create a counter variable and concatenate it to each hidden field id.
You can use the EXACT
Function for exact string comparisons.
=IF(EXACT(A1, "ENG"), 1, 0)
Use the break
keyword.
response_json = ("{ \"response_json\":" + str(list_of_dict)+ "}").replace("\'","\"")
response_json = json.dumps(response_json)
response_json = json.loads(response_json)
I created a function to get an array with the values ??for the fields and to join. This goes in the model:
public function GetDataWhereExtenseJoin($table,$fields,$data) {
//pega os campos passados para o select
foreach($fields as $coll => $value){
$this->db->select($value);
}
//pega a tabela
$this->db->from($table);
//pega os campos do join
foreach($data as $coll => $value){
$this->db->join($coll, $value);
}
//obtem os valores
$query = $this->db->get();
//retorna o resultado
return $query->result();
}
This goes in the controller:
$data_field = array(
'NameProduct' => 'product.IdProduct',
'IdProduct' => 'product.NameProduct',
'NameCategory' => 'category.NameCategory',
'IdCategory' => 'category.IdCategory'
);
$data_join = array
( 'product' => 'product_category.IdProduct = product.IdProduct',
'category' => 'product_category.IdCategory = category.IdCategory',
'product' => 'product_category.IdProduct = product.IdProduct'
);
$product_category = $this->mmain->GetDataWhereExtenseJoin('product_category', $data_field, $data_join);
result:
echo '<pre>';
print_r($product_category);
die;
for VS-2017, deleting .vs folder worked for me.
To check a number is positive, negative or negative zero. Check its sign using Math.sign() method it will provide you -1,-0,0 and 1 on the basis of positive negative and negative zero or zero numbers
Math.sign(-3) // -1
Math.sign(3) // 1
Math.sign(-0) // -0
Math.sign(0) // 0
Even after 9 years of the original post, this helped me.
If you are receiving these types of errors without any clue, there should be a trigger, function related to the table, and obviously it should end up with an SP, or function with selecting/filtering data NOT USING Primary Unique column. If you are searching/filtering using the Primary Unique column there won't be any multiple results. Especially when you are assigning value for a declared variable. The SP never gives you en error but only an runtime error.
"System.Data.SqlClient.SqlException (0x80131904): Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated."
In my case obviously there was no clue, but only this error message. There was a trigger connected to the table and the table updating by the trigger also had another trigger likewise it ended up with two triggers and in the end with an SP. The SP was having a select clause which was resulting in multiple rows.
SET @Variable1 =(
SELECT column_gonna_asign
FROM dbo.your_db
WHERE Non_primary_non_unique_key= @Variable2
If this returns multiple rows, you are in trouble.
As a number of people have pointed out, disabling the submit button has some negative side effects (at least in Chrome it prevents the name/value of the button pressed from being submitted). My solution was to simply add an attribute to indicate that submit has been requested, and then check for the presence of this attribute on every submit. Because I'm using the submit function, this is only called after all HTML 5 validation is successful. Here is my code:
$("form.myform").submit(function (e) {
// Check if we have submitted before
if ( $("#submit-btn").attr('attempted') == 'true' ) {
//stop submitting the form because we have already clicked submit.
e.preventDefault();
}
else {
$("#submit-btn").attr("attempted", 'true');
}
});
Add a common class to all the div. For example add foo to all the divs.
$('.foo').each(function () {
$(this).dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
});
Check your current php version in terminal with the following command,
$ php -v
You see current php version in terminal, and next command run in terminal if you want to upgrade your php version with php concat with version liked as,
$ brew install homebrew/php/php71
Please restart terminal if you finished php version upgrade installed and run the command.
$ php -v
Now you see the current php version in terminal....thank
Unfortunately Java does not make String
implement Iterable<Character>
. This could easily be done. There is StringCharacterIterator
but that doesn't even implement Iterator
... So make your own:
public class CharSequenceCharacterIterable implements Iterable<Character> {
private CharSequence cs;
public CharSequenceCharacterIterable(CharSequence cs) {
this.cs = cs;
}
@Override
public Iterator<Character> iterator() {
return new Iterator<Character>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < cs.length();
}
@Override
public Character next() {
return cs.charAt(index++);
}
};
}
}
Now you can (somewhat) easily run for (char c : new CharSequenceCharacterIterable("xyz"))
...
With a Twig extension, you can create a parameter
Twig function:
{{ parameter('jira_host') }}
TwigExtension.php:
class TwigExtension extends \Twig_Extension
{
public $container;
public function getFunctions()
{
return [
new \Twig_SimpleFunction('parameter', function($name)
{
return $this->container->getParameter($name);
})
];
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'iz';
}
}
service.yml:
iz.twig.extension:
class: IzBundle\Services\TwigExtension
properties:
container: "@service_container"
tags:
- { name: twig.extension }
I created an extension method to the ObservableCollection
public static void MySort<TSource,TKey>(this ObservableCollection<TSource> observableCollection, Func<TSource, TKey> keySelector)
{
var a = observableCollection.OrderBy(keySelector).ToList();
observableCollection.Clear();
foreach(var b in a)
{
observableCollection.Add(b);
}
}
It seems to work and you don't need to implement IComparable
Things that can cause a delete to be slow:
So your choices are to find out what is blocking and fix it or run the deletes in off hours when they won't be interfering with the normal production load. You can run the delete in batches (useful if you have triggers, cascade delete, or a large number of records). You can drop and recreate the indexes (best if you can do that in off hours too).
I was googling about how to convert an int to char, that got me here. But my question was to convert for example int of 6 to char of '6'. For those who came here like me, this is how to do it:
int num = 6;
num.ToString().ToCharArray()[0];
setInterval()
returns an interval ID, which you can pass to clearInterval()
:
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
See the docs for setInterval()
and clearInterval()
.
Hello world :)
The best but strange way for me was to do next things.
1) Download postgres93.app or other version. Add this app into /Applications/ folder.
2) Add a row (command) into the file .bash_profile
(which is in my home directory):
export PATH=/Applications/Postgres93.app/Contents/MacOS/bin/:$PATHIt's a PATH to
psql
from Postgres93.app
. The row (command) runs every time console is started.
3) Launch Postgres93.app
from /Applications/
folder. It starts a local server (port is "5432" and host is "localhost").
4) After all of this manipulations I was glad to run $ createuser -SRDP user_name
and other commands and to see that it worked! Postgres93.app
can be made to run every time your system starts.
5) Also if you wanna see your databases graphically you should install PG Commander.app
. It's good way to see your postgres DB as pretty data-tables
Of, course, it's helpful only for local server. I will be glad if this instructions help others who has faced with this problem.
Before PHP7 you can use:
array_splice($a, count($a), 0, $b);
array_splice()
operates with reference to array (1st argument) and puts array (4th argument) values in place of list of values started from 2nd argument and number of 3rd argument. When we set 2nd argument as end of source array and 3rd as zero we append 4th argument values to 1st argument
In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page. Follow the code snippet for insight:-
caller.html
<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">
external.js
function letMeCallYou()
{
alert("Bazinga!!! you called letMeCallYou")
}
The standard .NET way of doing this is to read from the Process' StandardOutput stream. There is an example in the linked MSDN docs. Similar, you can read from StandardError, and write to StandardInput.
For people coming from Google, this question is not about data attributes - OP added a non-standard attribute to their HTML object, and wondered how to set it.
However, you should not add custom attributes to your properties - you should use data attributes - e.g. OP should have used data-icon
, data-url
, data-target
, etc.
In any event, it turns out that the way you set these attributes via JavaScript is the same for both cases. Use:
ele.setAttribute(attributeName, value);
to change the given attribute attributeName
to value
for the DOM element ele
.
For example:
document.getElementById("someElement").setAttribute("data-id", 2);
Note that you can also use .dataset
to set the values of data attributes, but as @racemic points out, it is 62% slower (at least in Chrome on macOS at the time of writing). So I would recommend using the setAttribute
method instead.
There is not a program but you can make a batch file and run a command like that :
powershell "start-process 'C:\Program Files (x86)\IIS Express\iisexpress.exe' -workingdirectory 'C:\Program Files (x86)\IIS Express\' -windowstyle Hidden"
Here's another way:
fist_segment = "hello,"
second_segment = "world."
complete_string = "#{first_segment} #{second_segment}"
My favorite method for doing this is to write it out as a batch script to combine both user variables and system variables into a single backup file like so, create an environment-backup.bat
file and put in it:
@echo off
:: RegEdit can only export into a single file at a time, so create two temporary files.
regedit /e "%CD%\environment-backup1.reg" "HKEY_CURRENT_USER\Environment"
regedit /e "%CD%\environment-backup2.reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
:: Concatenate into a single file and remove temporary files.
type "%CD%\environment-backup1.reg" "%CD%\environment-backup2.reg" > environment-backup.reg
del "%CD%\environment-backup1.reg"
del "%CD%\environment-backup2.reg"
This creates environment-backup.reg
which you can use to re-import existing environment variables. This will add & override new variables, but not delete existing ones :)
An easy fix for this is to float your H1 element left:
.centercol h1{
background: #F2EFE9;
border-left: 3px solid #C6C1B8;
color: #006BB6;
display: block;
float: left;
font-weight: normal;
font-size: 18px;
padding: 3px 3px 3px 6px;
}
I have put together a simple jsfiddle example that shows the effect of the "float: left" style on the width of your H1 element for anyone looking for a more generic answer:
I haven't tested the email part of this (my test box does not send email) but I think it will work.
<?php
if ($_POST) {
$s = md5(rand());
mail('[email protected]', 'attachment', "--$s
{$_POST['m']}
--$s
Content-Type: application/octet-stream; name=\"f\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
".chunk_split(base64_encode(join(file($_FILES['f']['tmp_name']))))."
--$s--", "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$s\"");
exit;
}
?>
<form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<textarea name="m"></textarea><br>
<input type="file" name="f"/><br>
<input type="submit">
</form>
Destination Host Unreachable
This message indicates one of two problems: either the local system has no route to the desired destination, or a remote router reports that it has no route to the destination.
If the message is simply "Destination Host Unreachable," then there is no route from the local system, and the packets to be sent were never put on the wire.
If the message is "Reply From < IP address >: Destination Host Unreachable," then the routing problem occurred at a remote router, whose address is indicated by the "< IP address >" field.
Request Timed Out
This message indicates that no Echo Reply messages were received within the default time of 1 second. This can be due to many different causes; the most common include network congestion, failure of the ARP request, packet filtering, routing error, or a silent discard.
For more info Refer: http://technet.microsoft.com/en-us/library/cc940095.aspx
Coming from the embedded world, I would like to add that the concept of processes only exists in "big" processors (desktop CPUs, ARM Cortex A-9) that have MMU (memory management unit) , and operating systems that support using MMUs (such as Linux). With small/old processors and microcontrollers and small RTOS operating system (real time operating system), such as freeRTOS, there is no MMU support and thus no processes but only threads.
Threads can access each others memory, and they are scheduled by OS in an interleaved manner so they appear to run in parallel (or with multi-core they really run in parallel).
Processes, on the other hand, live in their private sandbox of virtual memory, provided and guarded by MMU. This is handy because it enables:
You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.
You should use this request:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
C++. This should be reasonably quick, as it doesn't require iterating over the whole set, or sorting it. This should work out of the box with most modern compilers, assuming they support tr1. If not, you may need to use Boost.
The Boost docs are helpful here to explain this, even if you don't use Boost.
The trick is to make use of the fact that the data has been divided into buckets, and to quickly identify a randomly chosen bucket (with the appropriate probability).
//#include <boost/unordered_set.hpp>
//using namespace boost;
#include <tr1/unordered_set>
using namespace std::tr1;
#include <iostream>
#include <stdlib.h>
#include <assert.h>
using namespace std;
int main() {
unordered_set<int> u;
u.max_load_factor(40);
for (int i=0; i<40; i++) {
u.insert(i);
cout << ' ' << i;
}
cout << endl;
cout << "Number of buckets: " << u.bucket_count() << endl;
for(size_t b=0; b<u.bucket_count(); b++)
cout << "Bucket " << b << " has " << u.bucket_size(b) << " elements. " << endl;
for(size_t i=0; i<20; i++) {
size_t x = rand() % u.size();
cout << "we'll quickly get the " << x << "th item in the unordered set. ";
size_t b;
for(b=0; b<u.bucket_count(); b++) {
if(x < u.bucket_size(b)) {
break;
} else
x -= u.bucket_size(b);
}
cout << "it'll be in the " << b << "th bucket at offset " << x << ". ";
unordered_set<int>::const_local_iterator l = u.begin(b);
while(x>0) {
l++;
assert(l!=u.end(b));
x--;
}
cout << "random item is " << *l << ". ";
cout << endl;
}
}
Here is how its done with bootstrap, only u should put the original input somewhere...idk in head and delete the < br > if you have it, because its only hidden and its taking space anyway :)
<head> _x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
</head>_x000D_
_x000D_
<label for="file" button type="file" name="image" class="btn btn-secondary">Secondary</button> </label>_x000D_
_x000D_
<input type="file" id="file" name="image" value="Prebrskaj" style="visibility:hidden;">_x000D_
_x000D_
_x000D_
<footer>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>_x000D_
_x000D_
</footer>
_x000D_
Best could be ng new myApp --style=scss
Then Angular CLI will create any new component with scss for you...
Note that using scss
not working in the browser as you probably know.. so we need something to compile it to css
, for this reason we can use node-sass
, install it like below:
npm install node-sass --save-dev
and you should be good to go!
If you using webpack, read on here:
Command line inside project folder where your existing package.json is:
npm install node-sass sass-loader raw-loader --save-dev
In
webpack.common.js
, search for "rules:" and add this object to the end of the rules array (don't forget to add a comma to the end of the previous object):
{
test: /\.scss$/,
exclude: /node_modules/,
loaders: ['raw-loader', 'sass-loader'] // sass-loader not scss-loader
}
Then in your component:
@Component({
styleUrls: ['./filename.scss'],
})
If you want global CSS support then on the top level component (likely app.component.ts) remove encapsulation and include the SCSS:
import {ViewEncapsulation} from '@angular/core';
@Component({
selector: 'app',
styleUrls: ['./bootstrap.scss'],
encapsulation: ViewEncapsulation.None,
template: ``
})
class App {}
from Angular starter here.
The "nav nav-list" class of Twiter Bootstrap 2.0 is handy for building a side bar.
You can see a lot of documentation at http://www.w3resource.com/twitter-bootstrap/nav-tabs-and-pills-tutorial.php
I want to work with exec_query
of the ActiveRecord
class, because it returns the mapping of the query transforming into object, so it gets very practical and productive to iterate with the objects when the subject is Raw SQL.
Example:
values = ActiveRecord::Base.connection.exec_query("select * from clients")
p values
and return this complete query:
[{"id": 1, "name": "user 1"}, {"id": 2, "name": "user 2"}, {"id": 3, "name": "user 3"}]
To get only list of values
p values.rows
[[1, "user 1"], [2, "user 2"], [3, "user 3"]]
To get only fields columns
p values.columns
["id", "name"]
In SQL Server 2008,2012,2014 you can insert multiple rows using a single SQL INSERT statement.
INSERT INTO TableName ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
Another way
INSERT INTO TableName (Column1, Column2 )
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
In most of the cases, StringUtils.isBlank(str)
from apache commons library would solve it. But if there is case, where input string being checked has null value within quotes, it fails to check such cases.
Take an example where I have an input object which was converted into string using String.valueOf(obj)
API. In case obj reference is null, String.valueOf returns "null" instead of null.
When you attempt to use, StringUtils.isBlank("null")
, API fails miserably, you may have to check for such use cases as well to make sure your validation is proper.
You're saying "if it's not set or it's different from add or it's different from delete". You realize that a != x && a != y
, with x != y
is necessarily false
since a
cannot be simultaneously two different values.
Watch again:
char dest[5];
char src[5] = "test";
printf("String: %s\n", do_something(dest, src));
Focus on this line:
printf("String: %s\n", do_something(dest, src));
You can clearly see that the do_something function is not declared!
If you look a little further,
printf("String: %s\n", do_something(dest, src));
char *do_something(char *dest, const char *src)
{
return dest;
}
you will see that you declare the function after you use it.
You will need to modify this part with this code:
char *do_something(char *dest, const char *src)
{
return dest;
}
printf("String: %s\n", do_something(dest, src));
Cheers ;)
Just a variation on the answers above.
I tried the straight up node command above without success, but the suggestion from this Angular CLI issue worked for me - you create a Node script in your package.json
file to increase the memory available to Node when you run your production build.
So if you want to increase the memory available to Node to 4gb (max-old-space-size=4096
), your Node command would be node --max-old-space-size=4096 ./node_modules/@angular/cli/bin/ng build --prod
. (increase or decrease the amount of memory depending on your needs as well - 4gb worked for me, but you may need more or less). You would then add it to your package.json 'scripts' section like this:
"prod": "node --max-old-space-size=4096 ./node_modules/@angular/cli/bin/ng build --prod"
It would be contained in the scripts object along with the other scripts available - e.g.:
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"prod": "node --max-old-space-size=4096./node_modules/@angular/cli/bin/ng build --prod"
}
And you run it by calling npm run prod
(you may need to run sudo npm run prod
if you're on a Mac or Linux).
Note there may be an underlying issue which is causing Node to need more memory - this doesn't address that if that's the case - but it at least gives Node the memory it needs to perform the build.
The above solutions fix the project or work around the problem in some way. Sometimes you just don't want to fix the project and just hide the warning instead.
To do that, configure the contents of the warning panel and make sure to toggle-off the "build path"->"JRE System Path Problem" category. The UI for this dialog is a bit complex/weird/usability challenged so you might have to fiddle with a few of the options to make it do what you want.
(?!Andrea)
This is not exactly an inverted match, but it's the best you can directly do with regex. Not all platforms support them though.
The short answer is that setting grid-auto-rows: 1fr;
on the grid container solves what was asked.
Others have pointed out that INNER JOIN
helps human readability, and that's a top priority, I agree.
Let me try to explain why the join syntax is more readable.
A basic SELECT
query is this:
SELECT stuff
FROM tables
WHERE conditions
The SELECT
clause tells us what we're getting back; the FROM
clause tells us where we're getting it from, and the WHERE
clause tells us which ones we're getting.
JOIN
is a statement about the tables, how they are bound together (conceptually, actually, into a single table).
Any query elements that control the tables - where we're getting stuff from - semantically belong to the FROM
clause (and of course, that's where JOIN
elements go). Putting joining-elements into the WHERE
clause conflates the which and the where-from, that's why the JOIN
syntax is preferred.
The way I would do this manually is:
Listed below is code to do this process via VBA.
It has the advantage of handling monthly sections of data rather than individual rows. Which can result in quicker processing for larger sets of data.
Sub SeperateData()
Dim vMonthText As Variant
Dim ExcelLastCell As Range
Dim intMonth As Integer
vMonthText = Array("January", "February", "March", "April", "May", _
"June", "July", "August", "September", "October", "November", "December")
ThisWorkbook.Worksheets("Sharepoint").Select
Range("A1").Select
RowCount = ThisWorkbook.Worksheets("Sharepoint").UsedRange.Rows.Count
'Forces excel to determine the last cell, Usually only done on save
Set ExcelLastCell = ThisWorkbook.Worksheets("Sharepoint"). _
Cells.SpecialCells(xlLastCell)
'Determines the last cell with data in it
Selection.EntireColumn.Insert
Range("A1").FormulaR1C1 = "Month No."
Range("A2").FormulaR1C1 = "=MONTH(RC[1])"
Range("A2").Select
Selection.Copy
Range("A3:A" & ExcelLastCell.Row).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Calculate
'Insert a helper column to determine the month number for the date
For intMonth = 1 To 12
Range("A1").CurrentRegion.Select
Selection.AutoFilter Field:=1, Criteria1:="" & intMonth
Selection.Copy
ThisWorkbook.Worksheets("" & vMonthText(intMonth - 1)).Select
Range("A1").Select
ActiveSheet.Paste
Columns("A:A").Delete Shift:=xlToLeft
Cells.Select
Cells.EntireColumn.AutoFit
Range("A1").Select
ThisWorkbook.Worksheets("Sharepoint").Select
Range("A1").Select
Application.CutCopyMode = False
Next intMonth
'Filter the data to a particular month
'Convert the month number to text
'Copy the filtered data to the month sheet
'Delete the helper column
'Repeat for each month
Selection.AutoFilter
Columns("A:A").Delete Shift:=xlToLeft
'Get rid of the auto-filter and delete the helper column
End Sub
Gradle Scripts >> build.gradle (Module app)
Change buildToolsVersion "24.0.0" to buildToolsVersion "23.0.3"
source : experience
You can use the attr
method. For example, if you have a jQuery object called label
, you could use this code:
console.log(label.attr("year")); // logs the year
console.log(label.attr("month")); // logs the month
Yes - Why, then how(sort of):
Short answer:
System.exit(0);
This nicely and cleanly terminates the whole java machine which is dedicated to running the app. However, you should do it from the main activity, otherwise android may restart your app automatically. (Tested this on Android 7.0)
Details and explanation of why this is a good question and a programmer may have a very legitimate reason to terminate their app this way:
I really don't see the gain in speaking harshly to someone who's looking for a way to terminate their app.
Good is a friendly reminder to beginners that on Android you don't have to worry about closing your app -- but some people actually do want to terminate their app even though they know that they don't have to -- and their question of how to do so is a legitimate question with a valid answer.
Perhaps many folks live in an ideal world and don't realize that there's a real world where real people are trying to solve real problems.
The fact is that even with android, it is still a computer and that computer is still running code, and that it is perfectly understandable why someone may wish to truly exit their "app" (i.e. all of the activities and resources belonging to their app.)
It is true that the developers at Google designed a system where they believed nobody would ever need to exit their app. And maybe 99% of the time they are right!
But one of the amazing things about allowing millions of programmers to write code for a platform is that some of them will try to push the platform to its limits in order to do amazing things! -- Including things that the Android Developers never even dreamed of!
There is another need for being able to close a program, and that is for troubleshooting purposes. That is what brought me to this thread: I'm just learning how to utilize the audio input feature to do realtime DSP.
Now don't forget that I said the following: I well know that when I have everything done right, I won't need to kill my app to reset the audio interface.
BUT: Remember, perfect apps don't start out as perfect apps! They start out as just barely working apps and grow to become proper ideal apps.
So what I found was that my little audio oscilloscope test app worked great until I pressed the android Home button. When I then re-launched my oscilloscope app, there was no audio coming in anymore.
At first I would go into
Settings->Applications->Manage Applications->AppName->Force Stop.
(Note that if the actual linux process is not running, the Force Stop button will be disabled. If the button is enabled, then the Linux process is still running!)
Then I could re-launch my app and it worked again.
At first, I was just using divide by zero to crash it - and that worked great. But I decided to look for a better way - which landed me here!
So here's the ways I tried and what I found out:
Background:
Android runs on Linux.
Linux has processes and process IDs (PIDs) just like Windows does, only better.
To see what processes are running on your android (with it connected into the USB and everything) run adb shell top
and you will get an updating list of all the processes running in the linux under the android.
If you have linux on your PC as well, you can type
adb shell top | egrep -i '(User|PID|MyFirstApp)' --line-buffered
to get just the results for your app named MyFirstApp. You can see how many Linux Processes are running under that name and how much of the cpu power they are consuming.
(Like the task manager / process list in Windows)
Or if you want to see just the running apps:
adb shell top | egrep -i '(User|PID|app_)' --line-buffered
You can also kill any app on your device by running
adb shell kill 12345
where 12345 is it's PID number.
From what I can tell, each single-threaded app just uses a single Linux process.
So what I found out was that (of course) if I just activate the android Home option, my app continues to run.
And if I use the Activity.finish()
, it still leaves the process running.
Divide by zero definitely terminates the linux process that is running.
Killing the PID from within the app seems the nicest so far that I've found, at least for debugging purposes.
I initially solved my need to kill my app by adding a button that would cause a divide by zero, like this in my MainActivity.java
:
public void exit(View view)
{
int x;
x=1/0;
}
Then in my layout XML file section for that button I just set the android:onClick="exit".
Of course divide by zero is messy because it always displays the "This application stopped..." or whatever.
So then I tried the finish, like this:
public void exit(View view)
{
finish();
}
And that made the app disappear from the screen but it was still running in the background.
Then I tried:
public void exit(View view)
{
android.os.Process.killProcess(android.os.Process.myPid());
}
So far, this is the best solution I've tried.
UPDATE: This is the same as above in that it instantly terminates the Linux process and all threads for the app:
public void exit(View view)
{
System.exit(0);
}
It instantly does a nice full exit of the thread in question without telling the user that the app crashed.
All memory used by the app will be freed. (Note: Actually, you can set parameters in your manifest file to cause different threads to run in different Linux processes, so it gets more complicated then.)
At least for quick and dirty testing, if you absolutely need to know that the thread is actually fully exited, the kill process does it nicely. However, if you are running multiple threads you may have to kill each of those, probably from within each thread.
EDIT: Here is a great link to read on the topic:
http://developer.android.com/guide/components/fundamentals.html
It explains how each app runs in its own virtual machine, and each virtual machine runs under its own user ID.
Here's another great link that explains how (unless specified otherwise in manifest) an app and all of its threads runs in a single Linux process: http://developer.android.com/guide/components/processes-and-threads.html
So as a general rule, an app really is a program running on the computer and the app really can be fully killed, removing all resources from memory instantly.
(By instantly I mean ASAP -- not later whenever the ram is needed.)
PS: Ever wonder why you go to answer your android phone or launch your favorite app and it freezes for a second? Ever reboot because you get tired of it? That's probably because of all the apps you ran in the last week and thought you quit but are still hanging around using memory. Phone kills them when it needs more memory, causing a delay before whatever action you wanted to do!
Update for Android 4/Gingerbread: Same thing as above applies, except even when an app exits or crashes and its whole java virtual machine process dies, it still shows up as running in the app manager, and you still have the "force close" option or whatever it is. 4.0 must have an independent list of apps it thinks is running rather than actually checking to see if an app is really even running.
For disable trigger
ALTER TABLE table_name DISABLE TRIGGER trigger_name
For enable trigger
ALTER TABLE table_name ENABLE TRIGGER trigger_name
Add the following line at the end of your eclipse.ini file
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient4
Thread interruption is based on flag interrupt status. For every thread default value of interrupt status is set to false. Whenever interrupt() method is called on thread, interrupt status is set to true.
<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %> <i class="fa fa-facebook"> Facebook Share </i> <%end%>
I am assuming that current_article_url
is http://0.0.0.0:4567/link_to_title
Many answers provided for this question. Just wanted to add one more which uses bashism-
#! /bin/bash
while read -r || [[ -n "$REPLY" ]]; do
[[ "$REPLY" =~ ^(-rwx|drwx).*[[:digit:]]+$ ]] && echo "Got one -> $REPLY"
done <"$1"
@kurumi answer for bash, which uses case is also correct but it will not read last line of file if there is no newline sequence at the end(Just save the file without pressing 'Enter/Return' at the last line).
My builder class for create ColorStateList
private class ColorStateListBuilder {
List<Integer> colors = new ArrayList<>();
List<int[]> states = new ArrayList<>();
public ColorStateListBuilder addState(int[] state, int color) {
states.add(state);
colors.add(color);
return this;
}
public ColorStateList build() {
return new ColorStateList(convertToTwoDimensionalIntArray(states),
convertToIntArray(colors));
}
private int[][] convertToTwoDimensionalIntArray(List<int[]> integers) {
int[][] result = new int[integers.size()][1];
Iterator<int[]> iterator = integers.iterator();
for (int i = 0; iterator.hasNext(); i++) {
result[i] = iterator.next();
}
return result;
}
private int[] convertToIntArray(List<Integer> integers) {
int[] result = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; iterator.hasNext(); i++) {
result[i] = iterator.next();
}
return result;
}
}
Example Using
ColorStateListBuilder builder = new ColorStateListBuilder();
builder.addState(new int[] { android.R.attr.state_pressed }, ContextCompat.getColor(this, colorRes))
.addState(new int[] { android.R.attr.state_selected }, Color.GREEN)
.addState(..., some color);
if(// some condition){
builder.addState(..., some color);
}
builder.addState(new int[] {}, colorNormal); // must add default state at last of all state
ColorStateList stateList = builder.build(); // ColorStateList created here
// textView.setTextColor(stateList);