Try to change Tomcat version, in my case tomcat "8.0.41" and "8.5.8" didn't work. But "8.5.37" worked fine.
I had this problem when using X2Go. The problem happened in a folder that was shared between the remote computer and my local PC.
Solution: cd out of that folder and in again. That fixed it.
You can use have both CASE
statements as follows.
case text1:
case text4:{
//blah
break;
}
SEE THIS EXAMPLE:The code example calculates the number of days in a particular month:
class SwitchDemo {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}
This is the output from the code:
Number of Days = 29
FALLTHROUGH:
Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks
fall through
: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
EXAMPLE CODE:
public class SwitchFallThrough {
public static void main(String[] args) {
java.util.ArrayList<String> futureMonths =
new java.util.ArrayList<String>();
int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
default: break;
}
if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}
This is the output from the code:
August
September
October
November
December
Using Strings in switch Statements
In Java SE 7 and later, you can use a String object in the switch statement's expression. The following code example, , displays the number of the month based on the value of the String named month:
public class StringSwitchDemo {
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
return monthNumber;
}
public static void main(String[] args) {
String month = "August";
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
The output from this code is 8.
What you really want to do is to remove any string that starts with either http://
or https://
plus any combination of non white space characters. Here is how I would solve it. My solution is very similar to that of @tolgayilmaz
#Define the text from which you want to replace the url with "".
text ='''The link to this post is https://stackoverflow.com/questions/11331982/how-to-remove-any-url-within-a-string-in-python'''
import re
#Either use:
re.sub('http://\S+|https://\S+', '', text)
#OR
re.sub('http[s]?://\S+', '', text)
And the result of running either code above is
>>> 'The link to this post is '
I prefer the second one because it is more readable.
To simply append to a file in powershell,you can use add-content.
So, to only add a new line to the file, try the following, where $YourNewDate and $YourDescription contain the desired values.
$NewLine = "{0},{1}" -f $YourNewDate,$YourDescription
$NewLine | add-content -path $file
Or,
"{0},{1}" -f $YourNewDate,$YourDescription | add-content -path $file
This will just tag the new line to the end of the .csv, and will not work for creating new .csv files where you will need to add the header.
For Asp.Net MVC
@Html.ListBox("parameterName", ViewBag.ParameterValueList as MultiSelectList,
new {
@class = "chosen-select form-control"
})
or
@Html.ListBoxFor(model => model.parameterName,
ViewBag.ParameterValueList as MultiSelectList,
new{
data_placeholder = "Select Options ",
@class = "chosen-select form-control"
})
you can try like this...you can use Array.IndexOf() , if you want to know the position also
string [] arr = {"One","Two","Three"};
var target = "One";
var results = Array.FindAll(arr, s => s.Equals(target));
Well, x.parentNode
returns the HEAD element, so you are inserting the script just before the head tag. Maybe that's the problem.
Try x.parentNode.appendChild()
instead.
If you could not found run the command,
CentOS:
# yum install dos2unix*
# dos2unix filename.sh
dos2unix: converting file filename.sh to Unix format ...
Ubuntu / Debian:
# apt-get install dos2unix
String expression = "((A+B)*C-D)*E";
expression = expression.replaceAll("\\+", "~+~");
expression = expression.replaceAll("\\*", "~*~");
expression = expression.replaceAll("-", "~-~");
expression = expression.replaceAll("/+", "~/~");
expression = expression.replaceAll("\\(", "~(~"); //also you can use [(] instead of \\(
expression = expression.replaceAll("\\)", "~)~"); //also you can use [)] instead of \\)
expression = expression.replaceAll("~~", "~");
if(expression.startsWith("~")) {
expression = expression.substring(1);
}
String[] expressionArray = expression.split("~");
System.out.println(Arrays.toString(expressionArray));
I found that this works for Java:
WebDriverWait waiter = new WebDriverWait(driver, 5000);
waiter.until( ExpectedConditions.presenceOfElementLocated(by) );
driver.FindElement(by);
This will spool the output from the anonymous block into a file called output_<YYYYMMDD>.txt
located in the root of the local PC C: drive where <YYYYMMDD>
is the current date:
SET SERVEROUTPUT ON FORMAT WRAPPED
SET VERIFY OFF
SET FEEDBACK OFF
SET TERMOUT OFF
column date_column new_value today_var
select to_char(sysdate, 'yyyymmdd') date_column
from dual
/
DBMS_OUTPUT.ENABLE(1000000);
SPOOL C:\output_&today_var..txt
DECLARE
ab varchar2(10) := 'Raj';
cd varchar2(10);
a number := 10;
c number;
d number;
BEGIN
c := a+10;
--
SELECT ab, c
INTO cd, d
FROM dual;
--
DBMS_OUTPUT.put_line('cd: '||cd);
DBMS_OUTPUT.put_line('d: '||d);
END;
SPOOL OFF
SET TERMOUT ON
SET FEEDBACK ON
SET VERIFY ON
PROMPT
PROMPT Done, please see file C:\output_&today_var..txt
PROMPT
Hope it helps...
EDIT:
After your comment to output a value for every iteration of a cursor (I realise each value will be the same in this example but you should get the gist of what i'm doing):
BEGIN
c := a+10;
--
FOR i IN 1 .. 10
LOOP
c := a+10;
-- Output the value of C
DBMS_OUTPUT.put_line('c: '||c);
END LOOP;
--
END;
Faced the same issue. To solve it,
$ sdk install gradle
using the package manager or $ brew install gradle
for mac. You might need to first install brew if not yet. You can use this example and change it's implementation like this:
[self enumerateAttribute:NSParagraphStyleAttributeName
inRange:NSMakeRange(0, self.length)
options:0
usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
//add your specific settings for paragraph
//...
//...
[self removeAttribute:NSParagraphStyleAttributeName range:range];
[self addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
}];
<iframe style="display: block; margin: auto;" width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen></iframe>
I just ran into this and fixed it by doing 2 things:
Removing the SPNs that previously existed on the SQL Server computer account (as opposed to the service account) using
setspn -D MSSQLSvc/HOSTNAME.domain.name.com:1234 HOSTNAME
where 1234 was the port number used by the instance (mine was not a default instance).
This will get selected value from multi-value select boxes: $("#id option:selected").val()
Just like any other simple command, [ ... ]
or test
requires spaces between its arguments.
if [ "$#" -ne 1 ]; then
echo "Illegal number of parameters"
fi
Or
if test "$#" -ne 1; then
echo "Illegal number of parameters"
fi
When in Bash, prefer using [[ ]]
instead as it doesn't do word splitting and pathname expansion to its variables that quoting may not be necessary unless it's part of an expression.
[[ $# -ne 1 ]]
It also has some other features like unquoted condition grouping, pattern matching (extended pattern matching with extglob
) and regex matching.
The following example checks if arguments are valid. It allows a single argument or two.
[[ ($# -eq 1 || ($# -eq 2 && $2 == <glob pattern>)) && $1 =~ <regex pattern> ]]
For pure arithmetic expressions, using (( ))
to some may still be better, but they are still possible in [[ ]]
with its arithmetic operators like -eq
, -ne
, -lt
, -le
, -gt
, or -ge
by placing the expression as a single string argument:
A=1
[[ 'A + 1' -eq 2 ]] && echo true ## Prints true.
That should be helpful if you would need to combine it with other features of [[ ]]
as well.
Take note that [[ ]]
and (( ))
are keywords which have same level of parsing as if
, case
, while
, and for
.
Also as Dave suggested, error messages are better sent to stderr so they don't get included when stdout is redirected:
echo "Illegal number of parameters" >&2
It's also logical to make the script exit when invalid parameters are passed to it. This has already been suggested in the comments by ekangas but someone edited this answer to have it with -1
as the returned value, so I might as well do it right.
-1
though accepted by Bash as an argument to exit
is not explicitly documented and is not right to be used as a common suggestion. 64
is also the most formal value since it's defined in sysexits.h
with #define EX_USAGE 64 /* command line usage error */
. Most tools like ls
also return 2
on invalid arguments. I also used to return 2
in my scripts but lately I no longer really cared, and simply used 1
in all errors. But let's just place 2
here since it's most common and probably not OS-specific.
if [[ $# -ne 1 ]]; then
echo "Illegal number of parameters"
exit 2
fi
Assuming I am understanding your question and setup correctly,
If you're trying to use the build number in your script, you have two options:
1) When calling ant, use: ant -Dbuild_parameter=${BUILD_NUMBER}
2) Change your script so that:
<property environment="env" />
<property name="build_parameter" value="${env.BUILD_NUMBER}"/>
To add all file at a time, use git add -A
To check git whole status, use git log
This can be done with MySQL, although it's highly unintuitive:
CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
DECLARE a,b INT;
DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET b = 1;
OPEN cur_1;
REPEAT
FETCH cur_1 INTO a;
UNTIL b = 1
END REPEAT;
CLOSE cur_1;
SET return_val = a;
END;//
Check out this guide: mysql-storedprocedures.pdf
Get store data
Mage::app()->getStore();
Store Id
Mage::app()->getStore()->getStoreId();
Store code
Mage::app()->getStore()->getCode();
Website Id
Mage::app()->getStore()->getWebsiteId();
Store Name
Mage::app()->getStore()->getName();
Store Frontend Name (see @Ben's answer)
Mage::app()->getStore()->getFrontendName();
Is Active
Mage::app()->getStore()->getIsActive();
Homepage URL of Store
Mage::app()->getStore()->getHomeUrl();
Current page URL of Store
Mage::app()->getStore()->getCurrentUrl();
All of these functions can be found in class Mage_Core_Model_Store
File: app/code/core/Mage/Core/Model/Store.php
To my knowledge, you can't mock constructors with mockito, only methods. But according to the wiki on the Mockito google code page there is a way to mock the constructor behavior by creating a method in your class which return a new instance of that class. then you can mock out that method. Below is an excerpt directly from the Mockito wiki:
Pattern 1 - using one-line methods for object creation
To use pattern 1 (testing a class called MyClass), you would replace a call like
Foo foo = new Foo( a, b, c );
with
Foo foo = makeFoo( a, b, c );
and write a one-line method
Foo makeFoo( A a, B b, C c ) { return new Foo( a, b, c ); }
It's important that you don't include any logic in the method; just the one line that creates the object. The reason for this is that the method itself is never going to be unit tested.
When you come to test the class, the object that you test will actually be a Mockito spy, with this method overridden, to return a mock. What you're testing is therefore not the class itself, but a very slightly modified version of it.
Your test class might contain members like
@Mock private Foo mockFoo; private MyClass toTest = spy(new MyClass());
Lastly, inside your test method you mock out the call to makeFoo with a line like
doReturn( mockFoo ) .when( toTest ) .makeFoo( any( A.class ), any( B.class ), any( C.class ));
You can use matchers that are more specific than any() if you want to check the arguments that are passed to the constructor.
If you're just wanting to return a mocked object of your class I think this should work for you. In any case you can read more about mocking object creation here:
Hi the problem is in FileDownloader class
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.
Latest solution for the same problem is updated Android PDF Write / Read using Android 9 (API level 28)
Attaching the working code with screenshots.
MainActivity.java
package com.example.downloadread;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void download(View v)
{
new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf");
}
public void view(View v)
{
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf"); // -> filename = maven.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
private class DownloadFile extends AsyncTask<String, Void, Void>{
@Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/maven.pdf
String fileName = strings[1]; // -> maven.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "testthreepdf");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
}
FileDownloader.java
package com.example.downloadread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadread"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.downloadread.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="download"
android:onClick="download" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/button1"
android:layout_marginTop="38dp"
android:text="view"
android:onClick="view" />
</RelativeLayout>
Breakpoints are just used to check the execution of your code, wherever you will put breakpoints the execution will stop there, so you can just check that your project execution is going forward or not. To get more details follow link:-
http://javapapers.com/core-java/top-10-java-debugging-tips-with-eclipse/
For Rails 5, you should enable the follow config code:
config.public_file_server.enabled = true
By default, Rails 5 ships with this line of config:
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
Hence, you will need to set the environment variable RAILS_SERVE_STATIC_FILES
to true.
The only working method for me:
function removeItem (array, value) {
var i = 0;
while (i < array.length) {
if(array[i] === value) {
array.splice(i, 1);
} else {
++i;
}
}
return array;
}
Usage:
var new = removeItem( ["apple","banana", "orange"], "apple");
// ---> ["banana", "orange"]
Using generator:
def primes(num):
if 2 <= num:
yield 2
for i in range(3, num + 1, 2):
if all(i % x != 0 for x in range(3, int(math.sqrt(i) + 1))):
yield i
Usage:
for i in primes(10):
print(i)
2, 3, 5, 7
You can use inotifywait
(with the modify,create,delete,move
flags enabled) and rsync
.
while inotifywait -r -e modify,create,delete,move /directory; do
rsync -avz /directory /target
done
If you don't have inotifywait
on your system, run sudo apt-get install inotify-tools
I fixed it, I'm not exactly sure what I did. I tried simply pushing and pulling using:
git pull <remote> dev
instead of
git pull <remote> master:dev
Hope this helps out someone if they are having the same issue.
In addition to Settings -> Editor -> Use soft wraps in editor I recommend Use soft wraps in console and Use custom soft wraps indent with a setting of 4 to make the wraps indented to match the line they started on.
My edit got rejected, so I'm attaching how to handle merging changes from a remote branch here.
If you have to do this after an incorrect merge, you can do something like this:
# If you did a git pull and it broke something, do this first
# Find the one before the merge, copy the SHA1
git reflog
git reset --hard <sha1>
# Get remote updates but DONT auto merge it
git fetch github
# Checkout to your mainline so your branch is correct.
git checkout develop
# Make a new branch where you'll be applying matches
git checkout -b manual-merge-github-develop
# Apply your patches
git checkout --patch github/develop path/to/file
...
# Merge changes back in
git checkout develop
git merge manual-merge-github-develop # optionally add --no-ff
# You'll probably have to
git push -f # make sure you know what you're doing.
If php_mcrypt installed on 64bit but reported missing by an installer, check the extension path:
vi /etc/php.d/mcrypt.ini
; Enable mcrypt extension module ;extension=module.so extension=/usr/lib64/php/modules/mcrypt.so
window.scrollBarWidth = function() {
document.body.style.overflow = 'hidden';
var width = document.body.clientWidth;
document.body.style.overflow = 'scroll';
width -= document.body.clientWidth;
if(!width) width = document.body.offsetWidth - document.body.clientWidth;
document.body.style.overflow = '';
return width;
}
My Solution was to 'Uri.parse' the File Path as String, instead of using Uri.fromFile().
String storage = Environment.getExternalStorageDirectory().toString() + "/test.txt";
File file = new File(storage);
Uri uri;
if (Build.VERSION.SDK_INT < 24) {
uri = Uri.fromFile(file);
} else {
uri = Uri.parse(file.getPath()); // My work-around for new SDKs, worked for me in Android 10 using Solid Explorer Text Editor as the external editor.
}
Intent viewFile = new Intent(Intent.ACTION_VIEW);
viewFile.setDataAndType(uri, "text/plain");
startActivity(viewFile);
Seems that fromFile() uses A file pointer, which I suppose could be insecure when memory addresses are exposed to all apps. But A file path String never hurt anybody, so it works without throwing FileUriExposedException.
Tested on API levels 9 to 29! Successfully opens the text file for editing in another app. Does not require FileProvider, nor the Android Support Library at all.
I have a problem that the findViewById(R.id.edit_text)
but return a TextView not a EditText. I think the problem is the R.id class has wrong id number, then, i clean the project then its works fine.
One way to speed things up is to explicitly perform multiple inserts or copy's within a transaction (say 1000). Postgres's default behavior is to commit after each statement, so by batching the commits, you can avoid some overhead. As the guide in Daniel's answer says, you may have to disable autocommit for this to work. Also note the comment at the bottom that suggests increasing the size of the wal_buffers to 16 MB may also help.
Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.
Ajax call:
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'html',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data == '') ? 'error' : 'success')
.html(data).show(500);
if (data == '') {
$('#message').html("Format your email correcly");
$('#demoForm').show(500);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
post.php
<?php
sleep(1);
function processEmail($email) {
if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
// your logic here (ex: add into database)
return true;
}
return false;
}
if (processEmail($_POST['email'])) {
echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}
-
doesnt make matter but +
sign is important when mobile user is in roaming
this is the standard format
<a href="tel:+4917640206387">+49 (0)176 - 402 063 87</a>
You can read more about it in the spec, see Make Telephone Numbers "Click-to-Call".
Thanks to Renato answer, I have created a really basic example:
const exec = require('child_process').exec
exec('git config --global user.name', (err, stdout, stderr) => console.log(stdout))
It will just print your global git username :)
Put the command
yum install php-gd
and restart the server (httpd, nginx, etc)
service httpd restart
EDIT2- Yea auto fills the DOM SOZ!
#img_box{
width:90%;
height:90%;
min-width: 400px;
min-height: 400px;
}
check out this fiddle
http://jsfiddle.net/ppumkin/4qjXv/2/
http://jsfiddle.net/ppumkin/4qjXv/3/
and this page
http://www.webmasterworld.com/css/3828593.htm
Removed original answer because it was wrong.
The width is ok- but the height resets to 0
so
min-height: 400px;
Sorry, you cannot inherit from multiple classes. You may use interfaces or a combination of one class and interface(s), where interface(s) should follow the class name in the signature.
interface A { }
interface B { }
class Base { }
class AnotherClass { }
Possible ways to inherit:
class SomeClass : A, B { } // from multiple Interface(s)
class SomeClass : Base, B { } // from one Class and Interface(s)
This is not legal:
class SomeClass : Base, AnotherClass { }
I had this same problem too, and it was tricky. For me, it was because I'm using Ext.Js javascript library. If you are doing a response.redirect in server-side code that you accessed in an Ajax call, there are problems. Ext.js has a workaround with their Ext.Redirect method.
This worked for me
input[type=text]:focus{outline: none;}
i'm using bootstrap 3
For multiple columns you can do:
df = pd.DataFrame(np.zeros([nrow, ncol])*np.nan)
The colon in your first example's url is going to cause an error (Bad Request) so you can't do exactly what you are looking for. Other than that, using a DateTime as an action parameter is most definitely possible.
If you are using the default routing, this 3rd portion of your example url is going to pickup the DateTime value as the {id} parameter. So your Action method might look like this:
public ActionResult Index(DateTime? id)
{
return View();
}
You'll probably want to use a Nullable Datetime as I have, so if this parameter isn't included it won't cause an exception. Of course, if you don't want it to be named "id" then add another route entry replacing {id} with your name of choice.
As long as the text in the url will parse to a valid DateTime value, this is all you have to do. Something like the following works fine and will be picked up in your Action method without any errors:
<%=Html.ActionLink("link", "Index", new { id = DateTime.Now.ToString("dd-MM-yyyy") }) %>
The catch, in this case of course, is that I did not include the time. I'm not sure there are any ways to format a (valid) date string with the time not represented with colons, so if you MUST include the time in the url, you may need to use your own format and parse the result back into a DateTime manually. Say we replace the colon with a "!" in the actionlink: new { id = DateTime.Now.ToString("dd-MM-yyyy HH!mm") }
.
Your action method will fail to parse this as a date so the best bet in this case would probably to accept it as a string:
public ActionResult Index(string id)
{
DateTime myDate;
if (!string.IsNullOrEmpty(id))
{
myDate = DateTime.Parse(id.Replace("!", ":"));
}
return View();
}
Edit: As noted in the comments, there are some other solutions arguably better than mine. When I originally wrote this answer I believe I was trying to preserve the essence of the date time format as best possible, but clearly URL encoding it would be a more proper way of handling this. +1 to Vlad's comment.
I also faced it and encorrected it like below successfully.
File > Settings > Build, Execution, Deployment > Gradle > Use local gradle distribution
Set the home path as : C:/Program Files/Android/Android Studio/gradle/gradle-version
You may need to upgrade your gradle version.
Step1: git rebase -i HEAD~n
to do interactive rebase for the last n
commits affected. (i.e. if you want to change a commit message 3 commits back, do git rebase -i HEAD~3
)
git will pop up an editor to handle those commits, notice this command:
# r, reword = use commit, but edit the commit message
that is exactly we need!
Step2: Change pick
to r
for those commits that you want to update the message. Don't bother changing the commit message here, it will be ignored. You'll do that on the next step. Save and close the editor.
Note that if you edit your rebase 'plan' yet it doesn't begin the process of letting you rename the files, run:
git rebase --continue
If you want to change the text editor used for the interactive session (e.g. from the default vi to nano), run:
GIT_EDITOR=nano git rebase -i HEAD~n
Step3: Git will pop up another editor for every revision you put r
before. Update the commit msg as you like, then save and close the editor.
Step4: After all commits msgs are updated. you might want to do git push -f
to update the remote.
Considering you tagged multiple products, I'd say the full correct syntax would be the one found in the ISO/ANSI SQL-92 standard:
<case expression> ::=
<case abbreviation>
| <case specification>
<case abbreviation> ::=
NULLIF <left paren> <value expression> <comma>
<value expression> <right paren>
| COALESCE <left paren> <value expression>
{ <comma> <value expression> }... <right paren>
<case specification> ::=
<simple case>
| <searched case>
<simple case> ::=
CASE <case operand>
<simple when clause>...
[ <else clause> ]
END
<searched case> ::=
CASE
<searched when clause>...
[ <else clause> ]
END
<simple when clause> ::= WHEN <when operand> THEN <result>
<searched when clause> ::= WHEN <search condition> THEN <result>
<else clause> ::= ELSE <result>
<case operand> ::= <value expression>
<when operand> ::= <value expression>
<result> ::= <result expression> | NULL
<result expression> ::= <value expression>
Syntax Rules
1) NULLIF (V1, V2) is equivalent to the following <case specification>:
CASE WHEN V1=V2 THEN NULL ELSE V1 END
2) COALESCE (V1, V2) is equivalent to the following <case specification>:
CASE WHEN V1 IS NOT NULL THEN V1 ELSE V2 END
3) COALESCE (V1, V2, . . . ,n ), for n >= 3, is equivalent to the
following <case specification>:
CASE WHEN V1 IS NOT NULL THEN V1 ELSE COALESCE (V2, . . . ,n )
END
4) If a <case specification> specifies a <simple case>, then let CO
be the <case operand>:
a) The data type of each <when operand> WO shall be comparable
with the data type of the <case operand>.
b) The <case specification> is equivalent to a <searched case>
in which each <searched when clause> specifies a <search
condition> of the form "CO=WO".
5) At least one <result> in a <case specification> shall specify a
<result expression>.
6) If an <else clause> is not specified, then ELSE NULL is im-
plicit.
7) The data type of a <case specification> is determined by ap-
plying Subclause 9.3, "Set operation result data types", to the
data types of all <result expression>s in the <case specifica-
tion>.
Access Rules
None.
General Rules
1) Case:
a) If a <result> specifies NULL, then its value is the null
value.
b) If a <result> specifies a <value expression>, then its value
is the value of that <value expression>.
2) Case:
a) If the <search condition> of some <searched when clause> in
a <case specification> is true, then the value of the <case
specification> is the value of the <result> of the first
(leftmost) <searched when clause> whose <search condition> is
true, cast as the data type of the <case specification>.
b) If no <search condition> in a <case specification> is true,
then the value of the <case expression> is the value of the
<result> of the explicit or implicit <else clause>, cast as
the data type of the <case specification>.
This seems a very old question, but I am providing an answer, so that it might help others. You can specify the variables in the second screen in the form section, as shown below or in the RAW format by appending the variables as shown in the second image.
If your variable and variable values are valid, you should see a successful response in the response section.
The return statement
stops the execution of a function and returns a value
from that function.
While updating global variables is one way to pass information back to the code that called the function
, this is not an ideal way of doing so. A much better alternative is to write the function so that values that are used by the function are passed to it as parameters and the function returns whatever value that it needs to without using or updating any global variables
.
By limiting the way in which information is passed to and from functions we can make it easier to reuse the same function from multiple places in our code.
JavaScript provides for passing one value back to the code that called it after everything in the function that needs to run has finished running.
JavaScript passes a value from a function back to the code that called it by using the return statement
. The value to be returned is specified in the return
keyword.
See this : What Python version can I use with Django?¶ https://docs.djangoproject.com/en/2.0/faq/install/
if you are using python27 you must to set django version :
try: $pip install django==1.9
If you only need to check the first element you can peek on it without iterating the whole collection:
public List<object> Foo(IEnumerable<object> objects)
{
object firstObject;
if (objects == null || !TryPeek(ref objects, out firstObject))
throw new ArgumentException();
var list = DoSomeThing(firstObject);
var secondList = DoSomeThingElse(objects);
list.AddRange(secondList);
return list;
}
public static bool TryPeek<T>(ref IEnumerable<T> source, out T first)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
IEnumerator<T> enumerator = source.GetEnumerator();
if (!enumerator.MoveNext())
{
first = default(T);
source = Enumerable.Empty<T>();
return false;
}
first = enumerator.Current;
T firstElement = first;
source = Iterate();
return true;
IEnumerable<T> Iterate()
{
yield return firstElement;
using (enumerator)
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
}
}
here is more detailed information -> [1]: https://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/
Try Following
DECLARE @formatted_datetime char(23)
SET @formatted_datetime = CONVERT(char(23), GETDATE(), 121)
print @formatted_datetime
Well, there is an array type in recent Postgres versions (not 100% about PG 7.4). You can even index them, using a GIN or GIST index. The syntaxes are:
create table foo (
bar int[] default '{}'
);
select * from foo where bar && array[1] -- equivalent to bar && '{1}'::int[]
create index on foo using gin (bar); -- allows to use an index in the above query
But as the prior answer suggests, it will be better to normalize properly.
Here's how to handle it with a random option element defined as the default value (in this case Text 2 is the default):
<select id="name2" >
<option value="">select all</option>
<option value="1">Text 1</option>
<option value="2" selected="selected">Text 2</option>
<option value="3">Text 3</option>
</select>
<script>
$('#name2 option[selected]').prop('selected', true);
</script>
in "stdapi.h"
StrToInt
This function tells you the result, and how many characters participated in the conversion.
You can use async import():
import fs = require('fs');
and then:
fs.readdir('./someDir', (err, files) => {
files.forEach(file => {
const module = import('./' + file).then(m =>
m.callSomeMethod();
);
// or const module = await import('file')
});
});
The webserver is returning an http 500 error code. These errors generally happen when an exception in thrown on the webserver and there's no logic to catch it so it spits out an http 500 error. You can usually resolve the problem by placing try-catch blocks in your code.
The inflect package can do this.
https://pypi.python.org/pypi/inflect
$ pip install inflect
and then:
>>>import inflect
>>>p = inflect.engine()
>>>p.number_to_words(99)
ninety-nine
--Try this script it works to my needs. Reformat to read it.
SELECT
SERVERPROPERTY('ComputerNamePhysicalNetBios') as 'Is_Current_Owner'
,SERVERPROPERTY('MachineName') as 'MachineName'
,case when @@ServiceName =
Right (@@Servername,len(@@ServiceName)) then @@Servername
else @@servername +' \ ' + @@Servicename
end as '@@Servername \ Servicename',
CONNECTIONPROPERTY('net_transport') AS net_transport,
CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,
dec.local_tcp_port,
CONNECTIONPROPERTY('local_net_address') AS local_net_address,
dec.local_net_address as 'dec.local_net_address'
FROM sys.dm_exec_connections AS dec
WHERE dec.session_id = @@SPID;
This solution is the combination of @Peter's solution for deleting multiple occurences and @chyno solution for removing first occurence. That's it what I'm using.
/**
* @param array $haystack
* @param mixed $value
* @param bool $only_first
* @return array
*/
function array_remove_values(array $haystack, $needle = null, $only_first = false)
{
if (!is_bool($only_first)) { throw new Exception("The parameter 'only_first' must have type boolean."); }
if (empty($haystack)) { return $haystack; }
if ($only_first) { // remove the first found value
if (($pos = array_search($needle, $haystack)) !== false) {
unset($haystack[$pos]);
}
} else { // remove all occurences of 'needle'
$haystack = array_diff($haystack, array($needle));
}
return $haystack;
}
Also have a look here: PHP array delete by value (not key)
You first have to define a JTextArea as per usual:
public final JTextArea mainConsole = new JTextArea("");
Then you put a JScrollPane over the TextArea
JScrollPane scrollPane = new JScrollPane(mainConsole);
scrollPane.setBounds(10,60,780,500);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
The last line says that the vertical scrollbar will always be there. There is a similar command for horizontal. Otherwise, the scrollbar will only show up when it is needed (or never, if you use _SCROLLBAR_NEVER). I guess it's your call which way you want to use it.
You can also add wordwrap to the JTextArea if you want to:Guide Here
Good luck,
Norm M
P.S. Make sure you add the ScrollPane to the JPanel and not add the JTextArea.
try to add this in your payload
grant_type=password&username=pippo&password=pluto
You can, under certain circumstances.
But the fact that you consider this is a strong sign that there is something wrong with your architecture: Primary keys should be pure technical and carry no business meaning whatsoever. So there should never be the need to change them.
Thomas
Okay, another hack with generators:
const value = function* () {_x000D_
let i = 0;_x000D_
while(true) yield ++i;_x000D_
}();_x000D_
_x000D_
Object.defineProperty(this, 'a', {_x000D_
get() {_x000D_
return value.next().value;_x000D_
}_x000D_
});_x000D_
_x000D_
if (a === 1 && a === 2 && a === 3) {_x000D_
console.log('yo!');_x000D_
}
_x000D_
The major concern here is that the collections don't keep the type in the definition. The types are only available in runtime. I came up with a function to test complex collections (it has one constraint though).
Check if the object is an instance of a generic collection. In order to represent a collection,
false
instanceof
evaluationList
or Set
, the type of the list comes next e.g. {List, Integer} for List<Integer>
Map
, the key and value types come next e.g. {Map, String, Integer} for Map<String, Integer>
More complex use cases could be generated using the same rules. For example in order to represent List<Map<String, GenericRecord>>
, it can be called as
Map<String, Integer> map = new HashMap<>();
map.put("S1", 1);
map.put("S2", 2);
List<Map<String, Integer> obj = new ArrayList<>();
obj.add(map);
isInstanceOfGenericCollection(obj, List.class, List.class, Map.class, String.class, GenericRecord.class);
Note that this implementation doesn't support nested types in the Map. Hence, the type of key and value should be a class and not a collection. But it shouldn't be hard to add it.
public static boolean isInstanceOfGenericCollection(Object object, Class<?>... classes) {
if (classes.length == 0) return false;
if (classes.length == 1) return classes[0].isInstance(object);
if (classes[0].equals(List.class))
return object instanceof List && ((List<?>) object).stream().allMatch(item -> isInstanceOfGenericCollection(item, Arrays.copyOfRange(classes, 1, classes.length)));
if (classes[0].equals(Set.class))
return object instanceof Set && ((Set<?>) object).stream().allMatch(item -> isInstanceOfGenericCollection(item, Arrays.copyOfRange(classes, 1, classes.length)));
if (classes[0].equals(Map.class))
return object instanceof Map &&
((Map<?, ?>) object).keySet().stream().allMatch(classes[classes.length - 2]::isInstance) &&
((Map<?, ?>) object).values().stream().allMatch(classes[classes.length - 1]::isInstance);
return false;
}
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size: 16px;_x000D_
text-align:center;_x000D_
line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size: 16px;_x000D_
text-align:center;_x000D_
line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size: 16px;_x000D_
text-align:center;_x000D_
line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
I am using it on this way:
number_to_currency(amount, unit: '€', precision: 2, format: "%u %n")
Of course that the currency symbol, precision, format and so on depends on each currency.
I believe that the configure method expects an absolute path. Anyhow, you may also try to load a Properties object first:
Properties props = new Properties();
props.load(new FileInputStream("log4j.properties"));
PropertyConfigurator.configure(props);
If the properties file is in the jar, then you could do something like this:
Properties props = new Properties();
props.load(getClass().getResourceAsStream("/log4j.properties"));
PropertyConfigurator.configure(props);
The above assumes that the log4j.properties is in the root folder of the jar file.
Microsoft Docs gives us two approaches.
Recommended HttpPost Edit code: Read and update
This is the same old way we used to do in previous versions of Entity Framework. and this is what Microsoft recommends for us.
Advantages
Modified
flag on the fields that are changed by form input.Alternative HttpPost Edit code: Create and attach
an alternative is to attach an entity created by the model binder to the EF context and mark it as modified.
As mentioned in the other answer the read-first approach requires an extra database read, and can result in more complex code for handling concurrency conflicts.
As another answer already said, call select myfunc(:y) from dual;
, but you might find declaring and setting a variable in sqlplus a little tricky:
sql> var y number
sql> begin
2 select 7 into :y from dual;
3 end;
4 /
PL/SQL procedure successfully completed.
sql> print :y
Y
----------
7
sql> select myfunc(:y) from dual;
As well you can use:
mysql> show status like '%onn%';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| Aborted_connects | 0 |
| Connections | 303 |
| Max_used_connections | 127 |
| Ssl_client_connects | 0 |
| Ssl_connect_renegotiates | 0 |
| Ssl_finished_connects | 0 |
| Threads_connected | 127 |
+--------------------------+-------+
7 rows in set (0.01 sec)
Feel free to use Mysql-server-status-variables or Too-many-connections-problem
In my case, CSS did not fix the issue. I noticed the problem while using jQuery re-render a button.
$("#myButton").html("text")
Try this
$("#myButton").html("<span>text</span>")
Typescript: following should work,
export const getTimeBetweenDates = ({
until,
format
}: {
until: number;
format: 'seconds' | 'minutes' | 'hours' | 'days';
}): number => {
const date = new Date();
const remainingTime = new Date(until * 1000);
const getFrom = moment([date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]);
const getUntil = moment([remainingTime.getUTCFullYear(), remainingTime.getUTCMonth(), remainingTime.getUTCDate()]);
const diff = getUntil.diff(getFrom, format);
return !isNaN(diff) ? diff : null;
};
Using the request module solved the issue.
// Include the request library for Node.js
var request = require('request');
// Basic Authentication credentials
var username = "vinod";
var password = "12345";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
request(
{
url : "https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
console.log(body); } );
Try javax.net.ssl.keyStorePassword
instead of javax.net.ssl.keyPassword
: the latter isn't mentioned in the JSSE ref guide.
The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmException
s are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.
You could also use -Djavax.net.debug=ssl
, or at least -Djavax.net.debug=ssl,keymanager
, to get more debugging information, if the information in the stack trace isn't sufficient.
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
I would also use navigation.navigate. If someone has the same problem and also uses nested navigators, this is how it would work:
onPress={() =>
navigation.navigate('MyStackScreen', {
// Passing params to NESTED navigator screen:
screen: 'goToScreenA',
params: { Data: data.item },
})
}
private static boolean isASCII(String s)
{
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) > 127)
return false;
return true;
}
As mentioned in previous answers, both serve almost same purpose. Personally I like git rebase and merge request (as in gitlab). It takes burden off of the reviewer/maintainer, making sure that while adding merge request, the feature branch includes all of the latest commits done on main branch after feature branch is created. Here is a very useful article explaining rebase in detail: https://git-scm.com/book/en/v2/Git-Branching-Rebasing
As @ashishduh mentioned above, using android:autoLink="phone
is also a good solution. But this option comes with one drawback, it doesn't work with all phone number lengths. For instance, a phone number of 11 numbers won't work with this option. The solution is to prefix your phone numbers with the country code.
Example:
08034448845
won't work
but +2348034448845
will
Of course, Insert
or AddFirst
will do the trick, but you could always do:
myList.Reverse();
myList.Add(item);
myList.Reverse();
UPDATE:
onActivityCreated()
is deprecated from API Level 28.
onCreate():
The onCreate()
method in a Fragment
is called after the Activity
's onAttachFragment()
but before that Fragment
's onCreateView()
.
In this method, you can assign variables, get Intent
extras, and anything else that doesn't involve the View hierarchy (i.e. non-graphical initialisations). This is because this method can be called when the Activity
's onCreate()
is not finished, and so trying to access the View hierarchy here may result in a crash.
onCreateView():
After the onCreate()
is called (in the Fragment
), the Fragment
's onCreateView()
is called. You can assign your View
variables and do any graphical initialisations. You are expected to return a View
from this method, and this is the main UI view, but if your Fragment
does not use any layouts or graphics, you can return null
(happens by default if you don't override).
onActivityCreated():
As the name states, this is called after the Activity
's onCreate()
has completed. It is called after onCreateView()
, and is mainly used for final initialisations (for example, modifying UI elements). This is deprecated from API level 28.
To sum up...
... they are all called in the Fragment
but are called at different times.
The onCreate()
is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View
variables you want to use in onCreateView()
. Afterwards, use onActivityCreated()
to do any final initialisations you want to do once everything has completed.
If you want to view the official Android documentation, it can be found here:
There are also some slightly different, but less developed questions/answers here on Stack Overflow:
If you bind the event through mootools' addEvent function your event handler will get a fixed (augmented) event passed as the parameter. It will always contain the preventDefault() method.
Try out this fiddle to see the difference in event binding. http://jsfiddle.net/pFqrY/8/
// preventDefault always works
$("mootoolsbutton").addEvent('click', function(event) {
alert(typeof(event.preventDefault));
});
// preventDefault missing in IE
<button
id="htmlbutton"
onclick="alert(typeof(event.preventDefault));">
button</button>
For all jQuery users out there you can fix an event when needed. Say that you used HTML onclick=".." and get a IE specific event that lacks preventDefault(), just use this code to get it.
e = $.event.fix(e);
After that e.preventDefault(); works fine.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
ngSanitize
module on your app
eg: var app = angular.module('myApp', ['ngSanitize']);
ng-bind-html
the original html
content. No need to do anything else in your controller. The parsing and conversion is automatically done by the ngBindHtml
directive. (Read the How does it work
section on this: $sce). So, in your case <div ng-bind-html="preview_data.preview.embed.html"></div>
would do the work.There should be a more succinct solution than the accepted answer. It shouldn't take three steps to run multiple tasks simultaneously and get their results.
Here's a method that cuts this down to two steps:
public async Task<Tuple<T1, T2>> WhenAllGeneric<T1, T2>(Task<T1> task1, Task<T2> task2)
{
await Task.WhenAll(task1, task2);
return Tuple.Create(task1.Result, task2.Result);
}
You can use it like this:
var taskResults = await Task.WhenAll(DoWorkAsync(), DoMoreWorkAsync());
var DoWorkResult = taskResults.Result.Item1;
var DoMoreWorkResult = taskResults.Result.Item2;
This removes the need for the temporary task variables. The problem with using this is that while it works for two tasks, you'd need to update it for three tasks, or any other number of tasks. Also it doesn't work well if one of the tasks doesn't return anything. Really, the .Net library should provide something that can do this
Oh, that's an interesting beast.
I've spent considerable time of getting that right, there are three main issues that differs from locale to locale: - currency symbol and direction - thousand separator - decimal point
I've written my own rather extensive implementation of this which is part of the kiwi python framework, check out the LGPL:ed source here:
http://svn.async.com.br/cgi-bin/viewvc.cgi/kiwi/trunk/kiwi/currency.py?view=markup
The code is slightly Linux/Glibc specific, but shouldn't be too difficult to adopt to windows or other unixes.
Once you have that installed you can do the following:
>>> from kiwi.datatypes import currency
>>> v = currency('10.5').format()
Which will then give you:
'$10.50'
or
'10,50 kr'
Depending on the currently selected locale.
The main point this post has over the other is that it will work with older versions of python. locale.currency was introduced in python 2.5.
Conclusion,
to_char
works in its own way
So,
Always use this format YYYY-MM-DD for comparison instead of MM-DD-YY or DD-MM-YYYY or any other format
var months = [
{
"updated_at" : "2012-01-01T06:25:24Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-09T11:25:13Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-05T04:13:24Z",
"foo" : "bar"
}];
months.sort((a, b)=>{
var keyA = new Date(a.updated_at),
keyB = new Date(b.updated_at);
// Compare the 2 dates
if(keyA < keyB) return -1;
if(keyA > keyB) return 1;
return 0;
});
console.log(months);
There's this way too (new to EcmaScript5):
dictionary.data.forEach(function(item){
console.log(item.name + ' ' + item.id);
});
Same approach for images
Box shadows can use commas to have multiple effects, just like with background images (in CSS3).
Most vanilla JS Ready functions do NOT consider the scenario where the DOMContentLoaded
handler is set after the document is already loaded - Which means the function will never run. This can happen if you look for DOMContentLoaded
within an async
external script (<script async src="file.js"></script>
).
The code below checks for DOMContentLoaded
only if the document's readyState
isn't already interactive
or complete
.
var DOMReady = function(callback) {
document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback());
};
DOMReady(function() {
//DOM ready!
});
If you want to support IE aswell:
var DOMReady = function(callback) {
if (document.readyState === "interactive" || document.readyState === "complete") {
callback();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', callback());
} else if (document.attachEvent) {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading') {
callback();
}
});
}
};
DOMReady(function() {
// DOM ready!
});
This works , this is my case ...
C:\xampp\htdocs\your_dir>SET HTTP_PROXY="http://192.168.1.103:8080"
Replace with your IP and Port
I use AngularJS v1.3.4
HTML:
<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>
JS controller:
'use strict';
angular.module('xxxxxxxxApp')
.controller('MathController', function ($scope, MathServicePDF) {
$scope.downloadPdf = function () {
var fileName = "test.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
MathServicePDF.downloadPdf().then(function (result) {
var file = new Blob([result.data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
});
};
});
JS services:
angular.module('xxxxxxxxApp')
.factory('MathServicePDF', function ($http) {
return {
downloadPdf: function () {
return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
return response;
});
}
};
});
Java REST Web Services - Spring MVC:
@RequestMapping(value = "/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<byte[]> getPDF() {
FileInputStream fileStream;
try {
fileStream = new FileInputStream(new File("C:\\xxxxx\\xxxxxx\\test.pdf"));
byte[] contents = IOUtils.toByteArray(fileStream);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "test.pdf";
headers.setContentDispositionFormData(filename, filename);
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return response;
} catch (FileNotFoundException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
return null;
}
Global.asax is the asp.net application file.
It is an optional file that handles events raised by ASP.NET or by HttpModules. Mostly used for application and session start/end events and for global error handling.
When used, it should be in the root of the website.
pt_kill
has an option for such. But it is on-demand, not continually monitoring. It does what @Rafa suggested. However see --sentinel
for a hint of how to come close with cron
.
static class Thing
will make your program work.
As it is, you've got Thing
as an inner class, which (by definition) is associated with a particular instance of Hello
(even if it never uses or refers to it), which means it's an error to say new Thing();
without having a particular Hello
instance in scope.
If you declare it as a static class instead, then it's a "nested" class, which doesn't need a particular Hello
instance.
An empty border is transparent. You need to specify a Line Border or some other visible border when you set the border in order to see it.
Based on Edit to question:
The painting does not honor the border. Add this line of code to your test and you will see the border:
jboard.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
jboard.add(new JButton("Test")); //Add this line
frame.add(jboard);
System.exit is needed
In your case, it does the exact same thing as the simple return-from-main.
passlib seems to be useful if you need to use hashes stored by an existing system. If you have control of the format, use a modern hash like bcrypt or scrypt. At this time, bcrypt seems to be much easier to use from python.
passlib supports bcrypt, and it recommends installing py-bcrypt as a backend: http://pythonhosted.org/passlib/lib/passlib.hash.bcrypt.html
You could also use py-bcrypt directly if you don't want to install passlib. The readme has examples of basic use.
see also: How to use scrypt to generate hash for password and salt in Python
I just wrote a jQuery plugin that does what you are looking for (annoyed that that I couldn't find andy solution myself (tabStop -> http://plugins.jquery.com/tabstop/)
You might want to flatten the data within your controller:
function MyCtrl ($scope) {
$scope.myData = [[1,2,3], [4,5,6], [7,8,9]];
$scope.flattened = function () {
var flat = [];
$scope.myData.forEach(function (item) {
flat.concat(item);
}
return flat;
}
}
And then in the HTML:
<table>
<tbody>
<tr ng-repeat="item in flattened()"><td>{{item}}</td></tr>
</tbody>
</table>
It is also available in general settings
Settings -> Security -> Verify Apps
Just un-check it.
( I am running 4.2.2 but most probably it should be available in 4.0 and higher. Cant say about previous versions ... )
That happens because you're setting the src of the ImageView
instead of the background.
Use this instead:
qImageView.setBackgroundResource(R.drawable.thumbs_down);
Here's a thread that talks about the differences between the two methods.
Why not use HTML-controlled items such as <input type="reset">
Credits to CommonsWare (Accepted Answer) Paul Cantrell (Create file if it doesn't exist) ahmad aghazadeh (Version name and code)
So I mashed all their ideas together and came up with this. This is the drag and drop solution to exactly what the first post asked.
It will automatically update the versionCode and versionName according to release status. Of course you can move the variables around to suite your needs.
def _versionCode=0
def versionPropsFile = file('version.properties')
def Properties versionProps = new Properties()
if(versionPropsFile.exists())
versionProps.load(new FileInputStream(versionPropsFile))
def _patch = (versionProps['PATCH'] ?: "0").toInteger() + 1
def _major = (versionProps['MAJOR'] ?: "0").toInteger()
def _minor = (versionProps['MINOR'] ?: "0").toInteger()
List<String> runTasks = gradle.startParameter.getTaskNames();
def value = 0
for (String item : runTasks)
if ( item.contains("assembleRelease")) {
value = 1;
}
_versionCode = (versionProps['VERSION_CODE'] ?: "0").toInteger() + value
if(_patch==99)
{
_patch=0
_minor=_minor+1
}
if(_major==99){
_major=0
_major=_major+1
}
versionProps['MAJOR']=_major.toString()
versionProps['MINOR']=_minor.toString()
versionProps['PATCH']=_patch.toString()
versionProps['VERSION_CODE']=_versionCode.toString()
versionProps.store(versionPropsFile.newWriter(), null)
def _versionName = "${_major}.${_versionCode}.${_minor}.${_patch}"
compileSdkVersion 24
buildToolsVersion "24.0.0"
defaultConfig {
applicationId "com.yourhost.yourapp"
minSdkVersion 16
targetSdkVersion 24
versionCode _versionCode
versionName _versionName
}
This should work:
if(gender.equals("Male")){
salutation ="Mr.";
}
else if(gender.equals("Female")){
salutation ="Ms.";
}
Remember, not to use ;
after if
statement.
I too got the same problem. When i changed the Eclipse from EE to Eclipse Classic it worked fine. in Win professional 64Bit. Have a try it may work for you too..
Your where clause should have worked. I am at a loss as to why it didn't. Let me show you how I would have figured out the problem with the where clause as it might help you for the future.
When I create triggers, I start at the query window by creating a temp table called #inserted (and or #deleted) with all the columns of the table. Then I popultae it with typical values (Always multiple records and I try to hit the test cases in the values)
Then I write my triggers logic and I can test without it actually being in a trigger. In a case like your where clause not doing what was expected, I could easily test by commenting out the insert to see what the select was returning. I would then probably be easily able to see what the problem was. I assure you that where clasues do work in triggers if they are written correctly.
Once I know that the code works properly for all the cases, I global replace #inserted with inserted and add the create trigger code around it and voila, a tested trigger.
AS I said in a comment, I have a concern that the solution you picked will not work properly in a multiple record insert or update. Triggers should always be written to account for that as you cannot predict if and when they will happen (and they do happen eventually to pretty much every table.)
Check your environment variables.
In my case I had JAVA_HOME set in the System variables as well as in my User Account variables and the latter was set to a wrong version of Java. I also had the same problem with the Path variable.
After deleting JAVA_HOME from my User Account variables and removing the wrong path from the Path variable it worked correctly.
This will put the results in tab delimited file(s) under a directory:
INSERT OVERWRITE LOCAL DIRECTORY '/home/hadoop/YourTableDir'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
STORED AS TEXTFILE
SELECT * FROM table WHERE id > 100;
To implement android Pull-to-Refresh try this piece of code,
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/pullToRefresh"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>
Activity class:
ListView lv = (ListView) findViewById(R.id.lv);
SwipeRefreshLayout pullToRefresh = (SwipeRefreshLayout) findViewById(R.id.pullToRefresh);
lv.setAdapter(mAdapter);
pullToRefresh.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
// TODO Auto-generated method stub
refreshContent();
}
});
private void refreshContent(){
new Handler().postDelayed(new Runnable() {
@Override public void run() {
pullToRefresh.setRefreshing(false);
}
}, 5000);
}
I had this problem, and the cause was rather silly. I was trying out Microsoft's demo regarding running a ServiceHost from w/in a Command Line executable. I followed the instructions, including where it says to add the appropriate Service (and interface). But I got the above error.
Turns out when I added the service class, VS automatically added the configuration to the app.config. And the demo was trying to add that info too. Since it was already in the config, I removed the demo part, and it worked.
You need to call newTest
to make the functions declared inside that method “visible” (see Functions within functions). But that are then just normal functions and no methods.
When you put <form>
tag inside you ngApp, AngularJS automatically adds form controller (actually there is a directive, called form
that add nessesary behaviour). The value of the name attribute will be bound in your scope; so something like <form name="yourformname">...</form>
will satisfy:
A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute.
So to check form validity, you can check value of $scope.yourformname.$valid
property of scope.
More information you can get at Developer's Guide section about forms.
I have created a working CodePen example to demonstrate how you might accomplish your goals.
I added ng-click
to the <form>
and removed the logic from your button:
<form name="addRelation" data-ng-click="save(model)">
...
<input class="btn" type="submit" value="SAVE" />
Here's the updated template:
<section ng-app="app" ng-controller="MainCtrl">
<form class="well" name="addRelation" data-ng-click="save(model)">
<label>First Name</label>
<input type="text" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.FirstName.$invalid">First Name is required</span><br/>
<label>Last Name</label>
<input type="text" placeholder="Last Name" data-ng-model="model.lastName" id="LastName" name="LastName" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.LastName.$invalid">Last Name is required</span><br/>
<label>Email</label>
<input type="email" placeholder="Email" data-ng-model="model.email" id="Email" name="Email" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.required">Email address is required</span>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.email">Email address is not valid</span><br/>
<input class="btn" type="submit" value="SAVE" />
</form>
</section>
and controller code:
app.controller('MainCtrl', function($scope) {
$scope.save = function(model) {
$scope.addRelation.submitted = true;
if($scope.addRelation.$valid) {
// submit to db
console.log(model);
} else {
console.log('Errors in form data');
}
};
});
I hope this helps.
The following code within a ViewGroup subclass would prevent it's parent containers from receiving touch events:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// Normal event dispatch to this container's children, ignore the return value
super.dispatchTouchEvent(ev);
// Always consume the event so it is not dispatched further up the chain
return true;
}
I used this with a custom overlay to prevent background views from responding to touch events.
What you may want to do is include a script on all pages that does the following ... 1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ... - looping through the window.frames by a for-in loop and then filter out by the properties
inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx
Add the event listeners etc..
Hope this helps
In the accepted answer you get annoying spacing between the visible rows when the expandable row is hidden. You can get rid of that by adding this to css:
.collapse-row.collapsed + tr {
display: none;
}
'+' is adjacent sibling selector, so if you want your expandable row to be the next row, this selects the next tr following tr named collapse-row.
Here is updated fiddle: http://jsfiddle.net/Nb7wy/2372/
Also google's comparison (though it's a bit old, done in 2008)
Someone give Luciano these points :) I just tested his answer -had a similar question- and worked perfectly...
I even add my 50 cents:
.error(function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
})
You can use this
File dir=new File(TestMain.class.getClassLoader().getResource("filename").getPath());
Just to update this question for C++11, this is now both possible to do and very natural:
struct Foo { Foo(int x) { /* ... */ } };
struct Baz {
Foo foo[3];
Baz() : foo{{4}, {5}, {6}} { }
};
Those braces can also be elided for an even more concise:
struct Baz {
Foo foo[3];
Baz() : foo{4, 5, 6} { }
};
Which can easily be extended to multi-dimensional arrays too:
struct Baz {
Foo foo[3][2];
Baz() : foo{1, 2, 3, 4, 5, 6} { }
};
System.Single / float - 7 digits
System.Double / double - 15-16 digits
System.Decimal / decimal - 28-29 significant digits
The way I've been stung by using the wrong type (a good few years ago) is with large amounts:
You run out at 1 million for a float.
A 15 digit monetary value:
9 trillion with a double. But with division and comparisons it's more complicated (I'm definitely no expert in floating point and irrational numbers - see Marc's point). Mixing decimals and doubles causes issues:
A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used because the floating-point number might not exactly approximate the decimal number.
When should I use double instead of decimal? has some similar and more in depth answers.
Using double
instead of decimal
for monetary applications is a micro-optimization - that's the simplest way I look at it.
setForeground
is added in API level 23. Leverage the power of RevealAnimator
in case u need to relay on foreground
property !
<View
android:id="@+id/circular_reveal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/primaryMilk_22"
android:elevation="@dimen/margin_20"
android:visibility="invisible" />
With kotlin ext function, it's way osm !
fun View.circularReveal() {
val cx: Int = width / 2
val cy: Int = height / 2
val finalRadius: Int =
width.coerceAtLeast(height)
val anim: Animator = ViewAnimationUtils.createCircularReveal(
this,
cx,
cy,
0f,
finalRadius.toFloat()
)
anim.interpolator = AccelerateDecelerateInterpolator()
anim.duration = 400
isVisible = true
anim.start()
anim.doOnEnd {
isVisible = false
}
}
Here is another solution (only relevant declarations listed):
.text span {
display:inline-block;
margin-right:100%;
}
When the margin is expressed in percentage, that percentage is taken from the width of the parent node, so 100% means as wide as the parent, which results in the next element getting "pushed" to a new line.
you cannot set this in javascript, you have to do this with html/css:
<style type="text/css" media="print">
@page { size: landscape; }
</style>
EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?
Rewrite your query to:
select iu from internal_uddi iu where iu.urn....
description: http://forum.spring.io/forum/spring-projects/data/126415-is-it-possible-to-use-query-and-pageable?p=611398#post611398
We can get the distinct similar to the example shown below
//example
var distinctValues = DetailedBreakDown_Table.AsEnumerable().Select(r => new
{
InvestmentVehicleID = r.Field<string>("InvestmentVehicleID"),
Universe = r.Field<string>("Universe"),
AsOfDate = _imqDate,
Ticker = "",
Cusip = "",
PortfolioDate = r.Field<DateTime>("PortfolioDate")
} ).Distinct();
On Ubuntu 13, the following does it, maybe a tad faster, as it reverses the sort and uses 'head' instead of 'tail', reducing the work. To show the 11 newest files in a tree:
find . -type f -printf '%T@ %p\n' | sort -n -r | head -11 | cut -f2- -d" " | sed -e 's,^./,,' | xargs ls -U -l
This gives a complete ls listing without re-sorting and omits the annoying './' that 'find' puts on every file name.
Or, as a bash function:
treecent () {
local numl
if [[ 0 -eq $# ]] ; then
numl=11 # Or whatever default you want.
else
numl=$1
fi
find . -type f -printf '%T@ %p\n' | sort -n -r | head -${numl} | cut -f2- -d" " | sed -e 's,^\./,,' | xargs ls -U -l
}
Still, most of the work was done by plundra's original solution. Thanks plundra.
Check for extra commas in your JSON response. If the last element of an array has a comma, this will break in IE
Correct expression is
"source " + (DT_STR,4,1252)DATEPART( "yyyy" , getdate() ) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".CSV"
I don't know what they're trying to say with this "React Context" stuff - they're talking Greek, to me, but here's how I did it:
Carrying values between functions, on the same page
In your constructor, bind your setter:
this.setSomeVariable = this.setSomeVariable.bind(this);
Then declare a function just below your constructor:
setSomeVariable(propertyTextToAdd) {
this.setState({
myProperty: propertyTextToAdd
});
}
When you want to set it, call this.setSomeVariable("some value");
(You might even be able to get away with this.state.myProperty = "some value";
)
When you want to get it, call var myProp = this.state.myProperty;
Using alert(myProp);
should give you some value
.
Extra scaffolding method to carry values across pages/components
You can assign a model to this
(technically this.stores
), so you can then reference it with this.state
:
import Reflux from 'reflux'
import Actions from '~/actions/actions`
class YourForm extends Reflux.Store
{
constructor()
{
super();
this.state = {
someGlobalVariable: '',
};
this.listenables = Actions;
this.baseState = {
someGlobalVariable: '',
};
}
onUpdateFields(name, value) {
this.setState({
[name]: value,
});
}
onResetFields() {
this.setState({
someGlobalVariable: '',
});
}
}
const reqformdata = new YourForm
export default reqformdata
Save this to a folder called stores
as yourForm.jsx
.
Then you can do this in another page:
import React from 'react'
import Reflux from 'reflux'
import {Form} from 'reactstrap'
import YourForm from '~/stores/yourForm.jsx'
Reflux.defineReact(React)
class SomePage extends Reflux.Component {
constructor(props) {
super(props);
this.state = {
someLocalVariable: '',
}
this.stores = [
YourForm,
]
}
render() {
const myVar = this.state.someGlobalVariable;
return (
<Form>
<div>{myVar}</div>
</Form>
)
}
}
export default SomePage
If you had set this.state.someGlobalVariable
in another component using a function like:
setSomeVariable(propertyTextToAdd) {
this.setState({
myGlobalVariable: propertyTextToAdd
});
}
that you bind in the constructor with:
this.setSomeVariable = this.setSomeVariable.bind(this);
the value in propertyTextToAdd
would be displayed in SomePage
using the code shown above.
In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode
property to None
.
subclasses
of class RuntimeException
are unchecked exception.Exception
but not RuntimeException
are considered to be checked exceptions
.checked exception
.
throws
clause containing the checked-exception
.Exception
classes are defined to be checked when they are considered important enough to catch or declare.@RequestMapping(path="/apps/add", method=RequestMethod.POST)
public String addApps(String appUrl, Model model, final RedirectAttributes redirectAttrs) {
if (!validate(appUrl)) {
redirectAttrs.addFlashAttribute("error", "Validation failed");
}
return "redirect:/apps/add"
}
@RequestMapping(path="/apps/add", method=RequestMethod.GET)
public String addAppss(Model model) {
String error = model.asMap().get("error");
}
Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:
var temp1;
if ( temp1 )... // false
var temp2 = true;
if ( temp2 )... // true
var temp3 = "";
if ( temp3 ).... // false
var temp4 = "hello world";
if ( temp4 )... // true
Hopefully that helps?
Also, its worth checking out these videos from Douglas Crockford
update: thanks @cphpython for spotting the broken links - I've updated to point at working versions now
@DougW has clearly answered this question, but I still like to add some codes here to explain Doug's points. (And correct errors in the code above)
Solution 1: URL-encode the POST data with a content-type header :application/x-www-form-urlencoded .
Note: you do not need to urlencode $_POST[] fields one by one, http_build_query() function can do the urlencoding job nicely.
$fields = array(
'mediaupload'=>$file_field,
'username'=>$_POST["username"],
'password'=>$_POST["password"],
'latitude'=>$_POST["latitude"],
'longitude'=>$_POST["longitude"],
'datetime'=>$_POST["datetime"],
'category'=>$_POST["category"],
'metacategory'=>$_POST["metacategory"],
'caption'=>$_POST["description"]
);
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
Solution 2: Pass the array directly as the post data without URL-encoding, while the Content-Type header will be set to multipart/form-data.
$fields = array(
'mediaupload'=>$file_field,
'username'=>$_POST["username"],
'password'=>$_POST["password"],
'latitude'=>$_POST["latitude"],
'longitude'=>$_POST["longitude"],
'datetime'=>$_POST["datetime"],
'category'=>$_POST["category"],
'metacategory'=>$_POST["metacategory"],
'caption'=>$_POST["description"]
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
Both code snippets work, but using different HTTP headers and bodies.
This should unstage a <file> for you (without removing or otherwise modifying the file):
git reset <file>
They do not do the same thing. The latter printf
statement interprets b
as an unsigned int
, which is wrong, as b
is a pointer.
Pointers and unsigned int
s are not always the same size, so these are not interchangeable. When they aren't the same size (an increasingly common case, as 64-bit CPUs and operating systems become more common), %x
will only print half of the address. On a Mac (and probably some other systems), that will ruin the address; the output will be wrong.
Always use %p
for pointers.
I use
Object.entries(GoalProgressMeasurement).filter(e => !isNaN(e[0]as any)).map(e => ({ name: e[1], id: e[0] }));
A simple 1 line that does the job.
It does the job in 3 simple steps
- Loads the combination of keys & values using Object.entries
.
- Filters out the non numbers (since typescript generates the values for reverse lookup).
- Then we map it to the array object we like.
If you use Windows, there some shortcuts, while devtools are opened:
Pressing Ctrl+Shift+D will dock all devtools to left, right, bottom in turn.
Press Ctrl+Shift+F if your JS console disappeared, and you want it docked back to bottom within dev tools.
This is annoying, I wish IntelliJ would handle this better than a startup nag..
If you are using TortoiseSVN 1.8+ on Windows, do this:
Modify
.C:\Program Files\TortoiseSVN\bin
to your Path
environment variable.Read the info.plist file of your app and get the value for key CFBundleShortVersionString. Reading info.plist will give you an NSDictionary object
Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable
Type in command line
echo %JAVA_HOME%
and
java -version
To verify whether your installation was done successfully.
This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.
Steps to resolve:
Open the Run window:
Press windows+R
Open registry window:
Type regedit
and enter.
Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\
If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.
For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:
Create a new subkey of 1.8.
For 1.8 create a String Key with name JavaHome with the value of JRE home:
Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html
When you write your main function, you typically see one of two definitions:
int main(void)
int main(int argc, char **argv)
The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).
The arguments to main
are:
int argc
- the number of arguments passed into your program when it was run. It is at least 1
.char **argv
- this is a pointer-to-char *
. It can alternatively be this: char *argv[]
, which means 'array of char *
'. This is an array of C-style-string pointers.For example, you could do this to print out the arguments passed to your C program:
#include <stdio.h>
int main(int argc, char **argv)
{
for (int i = 0; i < argc; ++i)
{
printf("argv[%d]: %s\n", i, argv[i]);
}
}
I'm using GCC 4.5 to compile a file I called args.c
. It'll compile and build a default a.out
executable.
[birryree@lilun c_code]$ gcc -std=c99 args.c
Now run it...
[birryree@lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there
So you can see that in argv
, argv[0]
is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1]
and beyond.
So basically, if you wanted a single parameter, you could say...
./myprogram integral
And you could check if argv[1]
was integral
, maybe like strcmp("integral", argv[1]) == 0
.
So in your code...
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc < 2) // no arguments were passed
{
// do something
}
if (strcmp("integral", argv[1]) == 0)
{
runIntegral(...); //or something
}
else
{
// do something else.
}
}
Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt
.
I use this script to delete last 10 commands in history:
pos=$HISTCMD; start=$(( $pos-11 )); end=$(( $pos-1 )); for i in $(eval echo "{${start}..${end}}"); do history -d $start; done
It uses $HISTCMD
environment var to get the history index and uses that to delete last 10 entries in history
.
There is a function called shift()
.
It will remove the first element of your array.
There is some good documentation and examples.
There might be neater methods, but the following could be one approach:
SELECT t.fk,
(
SELECT t1.Field1
FROM `table` t1
WHERE t1.fk = t.fk AND t1.Field1 IS NOT NULL
LIMIT 1
) Field1,
(
SELECT t2.Field2
FROM `table` t2
WHERE t2.fk = t.fk AND t2.Field2 IS NOT NULL
LIMIT 1
) Field2
FROM `table` t
WHERE t.fk = 3
GROUP BY t.fk;
Test Case:
CREATE TABLE `table` (fk int, Field1 varchar(10), Field2 varchar(10));
INSERT INTO `table` VALUES (3, 'ABC', NULL);
INSERT INTO `table` VALUES (3, NULL, 'DEF');
INSERT INTO `table` VALUES (4, 'GHI', NULL);
INSERT INTO `table` VALUES (4, NULL, 'JKL');
INSERT INTO `table` VALUES (5, NULL, 'MNO');
Result:
+------+--------+--------+
| fk | Field1 | Field2 |
+------+--------+--------+
| 3 | ABC | DEF |
+------+--------+--------+
1 row in set (0.01 sec)
Running the same query without the WHERE t.fk = 3
clause, it would return the following result-set:
+------+--------+--------+
| fk | Field1 | Field2 |
+------+--------+--------+
| 3 | ABC | DEF |
| 4 | GHI | JKL |
| 5 | NULL | MNO |
+------+--------+--------+
3 rows in set (0.01 sec)
Here it is, in as few words as possible. Focus on characters that need no escaping:
For cookies:
abdefghijklmnqrstuvxyzABDEFGHIJKLMNQRSTUVXYZ0123456789!#$%&'()*+-./:<>?@[]^_`{|}~
For urls
abdefghijklmnqrstuvxyzABDEFGHIJKLMNQRSTUVXYZ0123456789.-_~!$&'()*+,;=:@
For cookies and urls ( intersection )
abdefghijklmnqrstuvxyzABDEFGHIJKLMNQRSTUVXYZ0123456789!$&'()*+-.:@_~
That's how you answer.
Note that for cookies, the = has been removed because it is usually used to set the cookie value.
For urls this the = was kept. The intersection is obviously without.
var chars = "abdefghijklmnqrstuvxyz"; chars += chars.toUpperCase() + "0123456789" + "!$&'()*+-.:@_~";
Turns out escaping still occuring and unexpected happening, especially in a Java cookie environment where the cookie is wrapped with double quotes if it encounters the last characters.
So to be safe, just use A-Za-z1-9. That's what I am going to do.
import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')
# read bytes from archive
img_data = archive.read('img_01.png')
# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)
img = pygame.image.load(bytes_io)
I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.
http://api.jquery.com/jQuery.ajax/
jQuery.ajax()
Description: Perform an asynchronous HTTP (Ajax) request.
The full monty, lets you make any kind of Ajax request.
http://api.jquery.com/jQuery.get/
jQuery.get()
Description: Load data from the server using a HTTP GET request.
Only lets you make HTTP GET requests, requires a little less configuration.
.load()
Description: Load data from the server and place the returned HTML into the matched element.
Specialized to get data and inject it into an element.
For php 5.3+
you can use the SplFileInfo()
class
$spl = new SplFileInfo($filename);
print_r($spl->getExtension()); //gives extension
Also since you are checking extension for file uploads, I highly recommend using the mime type instead..
For php 5.3+
use the finfo
class
$finfo = new finfo(FILEINFO_MIME);
print_r($finfo->buffer(file_get_contents($file name));
For example this will start XBMC:
adb shell am start -a android.intent.action.MAIN -n org.xbmc.xbmc/android.app.NativeActivity
(More general answers are already posted, but I missed a nice example here.)
Or use new try with resources clause combined with Scanner:
try (Scanner scanner = new Scanner(value)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// process the line
}
}
For LINQ -> SQL:
SingleOrDefault
FirstOrDefault
For this html:
<div class="outer">
<div class="inner"></div>
</div>
This selector should work:
$('.outer > .inner')
You can accomplish this via layout weights. A weight dictates how the unclaimed portions of the screen are divided up. Give each EditText a layout_width of 0, and some proportional weight. I.e., give one a weight of 2, and the other a weight of 1 if you want the first to take up twice as much space.
You can also simply set your pandas column as list of id values with length same as of dataframe.
df['New_ID'] = range(880, 880+len(df))
Reference docs : https://pandas.pydata.org/pandas-docs/stable/missing_data.html
I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:$('#selectorid').val()
Exactly, you nearly got it:
GLfloat coordinates[8] = {1.0f, ..., 0.0f};
Open $CATALINA_BASE/conf/web.xml
and find this
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.
This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different
I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/
"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:
Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."
There is a JQuery plug-in that accomplishes pretty much what you're trying to do: https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js.
After including JQuery and the jquery.redirect.min.js plug-in, you can simply do something like this:
$().redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});
Use the following code on newer JQuery versions instead:
$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});
Hope this helps!
matplotlib.pyplot.vlines
vs. matplotlib.pyplot.axvline
vlines
accepts 1 or more locations for x
, while axvline
permits one location.
x=37
x=[37, 38, 39]
vlines
takes ymin
and ymax
as a position on the y-axis, while axvline
takes ymin
and ymax
as a percentage of the y-axis range.
vlines
, pass a list
to ymin
and ymax
.fig, ax = plt.subplots()
, then replace plt.vlines
or plt.axvline
with ax.vlines
or ax.axvline
, respectively.import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(1, 21, 200)
plt.figure(figsize=(10, 7))
# only one line may be specified; full height
plt.axvline(x=36, color='b', label='axvline - full height')
# only one line may be specified; ymin & ymax spedified as a percentage of y-range
plt.axvline(x=36.25, ymin=0.05, ymax=0.95, color='b', label='axvline - % of full height')
# multiple lines all full height
plt.vlines(x=[37, 37.25, 37.5], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple - full height')
# multiple lines with varying ymin and ymax
plt.vlines(x=[38, 38.25, 38.5], ymin=[0, 25, 75], ymax=[200, 175, 150], colors='teal', ls='--', lw=2, label='vline_multiple - partial height')
# single vline with full ymin and ymax
plt.vlines(x=39, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single - full height')
# single vline with specific ymin and ymax
plt.vlines(x=39.25, ymin=25, ymax=150, colors='green', ls=':', lw=2, label='vline_single - partial height')
# place legend outside
plt.legend(bbox_to_anchor=(1.0, 1), loc='upper left')
plt.show()
Hey I have answered this question here. Basically, you need to override
public Object instantiateItem(ViewGroup container, int position)
method of FragmentStatePagerAdapter.
Kotlin version
val Name: String by lazy {
val manufacturer = Build.MANUFACTURER
val model = Build.MODEL
if (model.toLowerCase().startsWith(manufacturer.toLowerCase())) {
capitalize(model)
} else {
capitalize(manufacturer) + " " + model
}
}
private fun capitalize(s: String?): String {
if (s == null || s.isEmpty()) {
return ""
}
val first = s[0]
return if (Character.isUpperCase(first)) {
s
} else {
Character.toUpperCase(first) + s.substring(1)
}
}
Interpreting newlines as <br />
used to be a feature of Github-flavored markdown, but the most recent help document no longer lists this feature.
Fortunately, you can do it manually. The easiest way is to ensure that each line ends with two spaces. So, change
a
b
c
into
a__
b__
c
(where _
is a blank space).
Or, you can add explicit <br />
tags.
a <br />
b <br />
c
You can maintain a Map
(for fast lookup) and List
(for order) but a LinkedHashMap
may be the simplest. You can also try a SortedMap
e.g. TreeMap
, which an have any order you specify.
This is usually caused by a program that writes into the event log and is then uninstalled or moved.
Just in case...
If you are using SoapUI Mock Service (as the Server), calling it from a C# WCF:
WCF --> SoapUI MockService
And in this case you are getting the same error:
The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8).
Edit your Mock Response at SoapUI and add a Header to it:
In my scenario, this fix the problem.
-- searching for weather stations with missing half-hourly records
SELECT stationid
FROM weather_data
WHERE `Timestamp` LIKE '2011-11-15 %' AND
stationid IN (SELECT `ID` FROM `weather_stations`)
GROUP BY stationid
HAVING COUNT(*) != 48;
-- variation of yapiskan with a where .. in .. select
Use a bytecode editor, like:
Be careful because you need a very good knowledge of the Java bytecode.
You can also change the class at runtime with bytecode weaving (like AspectJ).
I've compared the different options for speed and found that – much to my surprise – all options (except diag
) are equally fast. I personally use
A * b[:, None]
(or (A.T * b).T
) because it's short.
Code to reproduce the plot:
import numpy
import perfplot
def newaxis(data):
A, b = data
return A * b[:, numpy.newaxis]
def none(data):
A, b = data
return A * b[:, None]
def double_transpose(data):
A, b = data
return (A.T * b).T
def double_transpose_contiguous(data):
A, b = data
return numpy.ascontiguousarray((A.T * b).T)
def diag_dot(data):
A, b = data
return numpy.dot(numpy.diag(b), A)
def einsum(data):
A, b = data
return numpy.einsum("ij,i->ij", A, b)
perfplot.save(
"p.png",
setup=lambda n: (numpy.random.rand(n, n), numpy.random.rand(n)),
kernels=[
newaxis,
none,
double_transpose,
double_transpose_contiguous,
diag_dot,
einsum,
],
n_range=[2 ** k for k in range(13)],
xlabel="len(A), len(b)",
)
Apple is abstracting the system fonts going forward. This facility uses new generic family name -apple-system. So something like below should get you what you want.
body
{
font-family: -apple-system, "Helvetica Neue", "Lucida Grande";
}
Since 2.3.25, do it like this:
<#list user as propName, propValue>
${propName} = ${propValue}
</#list>
Note that this also works with non-string keys (unlike map[key]
, which had to be written as map?api.get(key)
then).
Before 2.3.25 the standard solution was:
<#list user?keys as prop>
${prop} = ${user[prop]}
</#list>
However, some really old FreeMarker integrations use a strange configuration, where the public Map
methods (like getClass
) appear as keys. That happens as they are using a pure BeansWrapper
(instead of DefaultObjectWrapper
) whose simpleMapWrapper
property was left on false
. You should avoid such a setup, as it mixes the methods with real Map
entries. But if you run into such unfortunate setup, the way to escape the situation is using the exposed Java methods, such as user.entrySet()
, user.get(key)
, etc., and not using the template language constructs like ?keys
or user[key]
.
OP may be true for an older version of node. However, I faced the same with node 4.4.1 as well.
It very well may be linked to the node version you are using. Try to upgrade to a latest version. Certain dependencies don't load transitively if they are incompatible with node version.
I found this by running npm update
.
After upgrading to latest version (4.4 -> 5.9); this got fixed.
Using something like selection.node().getBBox()
you get values like
{
height: 5,
width: 5,
y: 50,
x: 20
}
Use selection.node().getBoundingClientRect()
I think the code below
<item name="android:actionMenuTextAppearance">@style/MyActionBar.MenuTextStyle</item>
must be in MyAppTheme
section.
Also if you're retrieving something from intent
of another activity using getIntent
in the current activity and setting those retrieved data before/above onCreate
then this exception is thrown.
For eg. if i retrieve a string like this
final String slot1 = getIntent().getExtras().getString("Slot1");
and put this line of code before/above onCreate
then this exception is thrown.
Reference taken from this blog:
First, Create sample table and data:
CREATE TABLE tbl_RemoveExtraSpaces
(
Rno INT
,Name VARCHAR(100)
)
GO
INSERT INTO tbl_RemoveExtraSpaces VALUES (1,'I am Anvesh Patel')
INSERT INTO tbl_RemoveExtraSpaces VALUES (2,'Database Research and Development ')
INSERT INTO tbl_RemoveExtraSpaces VALUES (3,'Database Administrator ')
INSERT INTO tbl_RemoveExtraSpaces VALUES (4,'Learning BIGDATA and NOSQL ')
GO
Script to SELECT string without Extra Spaces:
SELECT
[Rno]
,[Name] AS StringWithSpace
,LTRIM(RTRIM(REPLACE(REPLACE(REPLACE([Name],CHAR(32),'()'),')(',''),'()',CHAR(32)))) AS StringWithoutSpace
FROM tbl_RemoveExtraSpaces
Result:
Rno StringWithSpace StringWithoutSpace
----------- ----------------------------------------- ---------------------------------------------
1 I am Anvesh Patel I am Anvesh Patel
2 Database Research and Development Database Research and Development
3 Database Administrator Database Administrator
4 Learning BIGDATA and NOSQL Learning BIGDATA and NOSQL
SELECT DATEDIFF(hh, firstDate, secondDate) FROM tableName WHERE ...
Ran into this exact problem.
What I ended up doing:
# starting with date string
sdt = "20190901"
std_format = '%Y%m%d'
# create naive datetime object
from datetime import datetime
dt = datetime.strptime(sdt, sdt_format)
# extract the relevant date time items
dt_formatters = ['%Y','%m','%d']
dt_vals = tuple(map(lambda formatter: int(datetime.strftime(dt,formatter)), dt_formatters))
# set timezone
import pendulum
tz = pendulum.timezone('utc')
dt_tz = datetime(*dt_vals,tzinfo=tz)
The splat and spread operators are part of ES6, the planned next version of Javascript. So far only Firefox supports them. This code works in FF16+:
var arr = ['quick', 'brown', 'lazy'];
var sprintf = function(str, ...args)
{
for (arg of args) {
str = str.replace(/%s/, arg);
}
return str;
}
sprintf.apply(null, ['The %s %s fox jumps over the %s dog.', ...arr]);
sprintf('The %s %s fox jumps over the %s dog.', 'slow', 'red', 'sleeping');
Note the awkard syntax for spread. The usual syntax of sprintf('The %s %s fox jumps over the %s dog.', ...arr);
is not yet supported. You can find an ES6 compatibility table here.
Note also the use of for...of
, another ES6 addition. Using for...in
for arrays is a bad idea.
This can be done in a single line without the use of library. Please check java.text.MessageFormat
class.
Example
String stringWithPlaceHolder = "test String with placeholders {0} {1} {2} {3}";
String formattedStrin = java.text.MessageFormat.format(stringWithPlaceHolder, "place-holder-1", "place-holder-2", "place-holder-3", "place-holder-4");
Output will be
test String with placeholders place-holder-1 place-holder-2 place-holder-3 place-holder-4
This is my solution using pure Win32/C++ based on the top answer. The idea is to wrap everything required into one function without the need for external callback functions or structures:
#include <utility>
HWND FindTopWindow(DWORD pid)
{
std::pair<HWND, DWORD> params = { 0, pid };
// Enumerate the windows using a lambda to process each window
BOOL bResult = EnumWindows([](HWND hwnd, LPARAM lParam) -> BOOL
{
auto pParams = (std::pair<HWND, DWORD>*)(lParam);
DWORD processId;
if (GetWindowThreadProcessId(hwnd, &processId) && processId == pParams->second)
{
// Stop enumerating
SetLastError(-1);
pParams->first = hwnd;
return FALSE;
}
// Continue enumerating
return TRUE;
}, (LPARAM)¶ms);
if (!bResult && GetLastError() == -1 && params.first)
{
return params.first;
}
return 0;
}
If you use the solution from @jorge and find that everything is on the same line, make sure you enclose the variable in quotes:
echo $__usage
will print everything on one line whereas
echo "$__usage"
will retain the newlines.
<div style={{ visibility: this.state.driverDetails.firstName != undefined? 'visible': 'hidden'}}></div>
Checkout the above code. That will do the trick.
I find this lecture very valuable https://vimeo.com/190275665, in point 3 it summarizes these generators and also gives some performance analysis and guideline one when you use each one.
It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.
If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate
and colMeans
, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.
However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for
loop.
> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 >
So in your case, if you just wanted to print the mean of your Tandem
object 5 times:
for (ii in 1:5) { Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL) TandemMean <- mean(Tandem) print(TandemMean) }
As mentioned above, replicate
is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.
set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) { tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) } tandem[1] tandem[100] tandem[20:25]
...creates this output:
> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { + tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } > > tandem[1] [[1]] [1] 1.511923 > tandem[100] [[1]] [1] 1.496777 > tandem[20:25] [[1]] [1] 1.500669 [[2]] [1] 1.487552 [[3]] [1] 1.503409 [[4]] [1] 1.501362 [[5]] [1] 1.499728 [[6]] [1] 1.492798 >
Another possible explanation is that you're building against x86. Right-click your Solution and choose Configuration Manager. See if you're building against x86 instead of Any CPU.
Rather than using res.send(404)
as in old versions of Express, the new method is:
res.sendStatus(404);
Express will send a very basic 404 response with "Not Found" text:
HTTP/1.1 404 Not Found
X-Powered-By: Express
Vary: Origin
Content-Type: text/plain; charset=utf-8
Content-Length: 9
ETag: W/"9-nR6tc+Z4+i9RpwqTOwvwFw"
Date: Fri, 23 Oct 2015 20:08:19 GMT
Connection: keep-alive
Not Found
Something like this might be the easiest way.
<a href="mailto:?subject=I wanted you to see this site&body=Check out this site http://www.website.com."
title="Share by Email">
<img src="http://png-2.findicons.com/files/icons/573/must_have/48/mail.png">
</a>
You could find another email image and add that if you wanted.
if you want to just "bold", Mike Hofer's answer is mostly correct.
but notice that the tag bolds its contents by default, but you can change this behavior using css, example:
p strong {
font-weight: normal;
font-style: italic;
}
Now your "bold" is italic :)
So, try to use tags by its meaning, not by its default style.
Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.
Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):
onClick=""
OR
The element css needs to have the following declaration:
cursor:pointer
Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working
It's because the CPU doesn't have so many cache misses (where it has to wait for the array data to come from the RAM chips). It would be interesting for you to adjust the size of the arrays continually so that you exceed the sizes of the level 1 cache (L1), and then the level 2 cache (L2), of your CPU and plot the time taken for your code to execute against the sizes of the arrays. The graph shouldn't be a straight line like you'd expect.
You can use sort() function. sort() exists in algorithm header file
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
string str = "sharlock";
sort(str.begin(), str.end());
cout<<str<<endl;
return 0;
}
Output:
achklors
You also can use:
element.addEventListener("click", function(){
// call execute function here...
}, false);
$('#myId').val()
should do it, failing that I would try:
$('#myId option:selected').val()
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeStamp);
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
Another approach using Array.prototype.map() and Array.prototype.filter():
var indices = array.map((e, i) => e === value ? i : '').filter(String)
change the
fieldname?: any[];
to this:
fieldname?: any;
Using LaTeX syntax directly in a Markdown cell works for me. I'm using Jypiter 4.4.0.
I don't have to use %%latex
magic command, I insist, simply a markdown cell:
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}
Renders to: