The select statement in the cost part of your select is returning more than one value. You need to add more where clauses, or use an aggregation.
Since you're accessing a web.config
you should probably use
using System.Web.Configuration;
WebConfigurationManager.AppSettings["configFile"]
Your code work fine, provided the value in Sheet2!D2
exists in Sheet1!A:A
. If it does not then error 1004 is raised.
To handle this case, try
Sub Demo()
Dim MyStringVar1 As Variant
On Error Resume Next
MyStringVar1 = Application.WorksheetFunction.VLookup(Range("D2"), _
Worksheets("Sheet1").Range("A:C"), 1, False)
On Error GoTo 0
If IsEmpty(MyStringVar1) Then
MsgBox "Value not found!"
End If
Range("E2") = MyStringVar1
End Sub
If using Android Studio, do the following (I've copied and modified @Vinayak Bs answer):
- Select the Project view in the Project sideview (instead of Packages or Android)
- Create a folder called libs in your project's root folder
- Copy your JAR files to the libs folder
- The sideview will be updated and the JAR files will show up in your project
- Now right click on each JAR file you want to import and then select "Add as Library...", which will include it in your project
- After that, all you need to do is reference the new classes in your code, eg.
import javax.mail.*
Use
System.getProperty("java.class.path")
see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
You can also split it into it's elements easily
String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);
The error shown in visual studio for the project (Let's say A) does not have issues. When I looked at the output window for the build line by line for each project, I saw that it was complaining about another project (B) that had been referred as assembly in project A. Project B added into the solution. But it had not been referred in the project A as project reference instead as assembly reference from different location. That location contains the assembly which compiled for Platform AnyCpu. Then I removed the assembly reference from the project A and added project B as a reference. It started compiling. Not sure though how this fix worked.
It happen the same thing to me. See on Gradle -> Build Gradle -> and make sure that the compatibility matches in both compile "app compat" and "support design" lines, they should have the same version.
Then to be super sure, that it will launch with no problem, go to File -> Project Structure ->app and check on tab propertie the build Tools version, it should be the same as your support compile line, just in case i put the target SDK version as 25 as well on the tab Flavors.
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-
core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
*compile 'com.android.support:appcompat-v7:25.3.1'*
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
*compile 'com.android.support:design:25.3.1'*
}
Thats what I did and worked. Good luck!
You can use ngModel
like
<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>
To update the checkbox state by updating the property checkboxValue
in your code and when the checkbox is changed by the user addProp()
is called.
We can solve it in data.table
way with tidyr::repalce_na
function and lapply
library(data.table)
library(tidyr)
setDT(df)
df[,c("a","b","c"):=lapply(.SD,function(x) replace_na(x,0)),.SDcols=c("a","b","c")]
In this way, we can also solve paste columns with NA
string. First, we replace_na(x,"")
,then we can use stringr::str_c
to combine columns!
just replaced: ;extension=pdo_mysql to extension=pdo_mysql in php.ini file.
Try BufferedReader.readLine()
instead of all this complication. It will recognize all possible line terminators.
from datetime import datetime
a = datetime.strptime(f, "%Y-%m-%d")
This appears to be a better method. "indexOf" returns -1 if nothing is matched. It doesn't overwrite existing classes on the body, just adds them.
// add a class on the body ie IE 10/11
var uA = navigator.userAgent;
if(uA.indexOf('Trident') != -1 && uA.indexOf('rv:11') != -1){
document.body.className = document.body.className+' ie11';
}
if(uA.indexOf('Trident') != -1 && uA.indexOf('MSIE 10.0') != -1){
document.body.className = document.body.className+' ie10';
}
Use this....
string popupScript = "<script language=JavaScript>";
popupScript += "alert('Please enter valid Email Id');";
popupScript += "</";
popupScript += "script>";
Page.RegisterStartupScript("PopupScript", popupScript);
You can do this more easy way. And 100% works that you want
<?php
$servername = "localhost";
$username = "root";
$password = ""; //your database password
$dbname = "demo"; //your database name
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
//echo ("Connect Successfully");
}
$query = "SELECT Date_time, Tempout FROM alarm_value"; // select column
$aresult = $con->query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Massive Electronics</title>
<script type="text/javascript" src="loder.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
var data = google.visualization.arrayToDataTable([
['Date_time','Tempout'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Date_time"]."', ".$row["Tempout"]."],";
}
?>
]);
var options = {
title: 'Date_time Vs Room Out Temp',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.AreaChart(document.getElementById('areachart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="areachart" style="width: 900px; height: 400px"></div>
</body>
</html>
loder.js link here loder.js
Most of the answers here seem to lack awareness of the namespace change that happened between EF 6.2 and 6.3.
I was intentionally upgrading from EF 6.1 to 6.3 to be able to target .NET Standard 2.1. However, I accidentally used .NET Standard 2.0 for the new target in my lib and then got the The type or namespace name 'Entity' does not exist in the namespace 'System.Data'
. This GH issue comment gave me the clue I needed to fix. I changed my lib target to .NET Standard 2.1 and the project compiled. No re-installs, uninstalls, or restarts were required.
Why don't you use your values from the DB and store them on an ArrayList and then just use:
yourSpinner.setSelection(yourArrayList.indexOf("Category 1"));
If you are using Chrome, you could also use
console.log( yourArray );
As for this date (February 2017), it seems that mailchimp has integrated something similar to what gbinflames suggests into their own javascript generated form.
You don't need any further intervention now as mailchimp will convert the form to an ajax submitted one when javascript is enabled.
All you need to do now is just paste the generated form from the embed menu into your html page and NOT modify or add any other code.
This simply works. Thanks MailChimp!
On the anaconda prompt, do a
conda -V
or conda --version
to get the conda version.python -V
or python --version
to get the python version.conda list anaconda$
to get the Anaconda version.conda list
to get the Name, Version, Build & Channel details of all the packages installed (in the current environment).conda info
to get all the current environment details.conda info --envs
To see a list of all your environmentsUsing SwiftyJSON library, you could make it like
if let path : String = Bundle.main.path(forResource: "tiles", ofType: "json") {
if let data = NSData(contentsOfFile: path) {
let optData = try? JSON(data: data as Data)
guard let json = optData else {
return
}
for (_, object) in json {
let name = object["name"].stringValue
print(name)
}
}
}
A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY.
An example of this solution can be found at this answer: https://stackoverflow.com/a/62485644/1178478
The following should suffice:
[^ ]
If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):
[^\s]
or
\S # Note this is a CAPITAL 'S'!
The first thing Apple mentions is that you cache your formatter...
Link to Apple doco stating exactly how to do this:
Cache Formatters for Efficiency Creating a date formatter is not a cheap operation. ...cache a single instance...
Use a global...
let df : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
Then simply use that formatter anywhere...
let s = df.string(from: someDate)
or
let d = df.date(from: someString)
Or use any of the other many, many convenient methods on DateFormatter.
(If you write an extension on String, your code is completely "upside down" - you can't use any dateFormatter calls!)
Note that usually you will have a few of those globals .. such as "formatForClient" "formatForPubNub" "formatForDisplayOnInvoiceScreen" .. etc.
How about create a bat file, run the batch file before closing, and then close the current instance.
The batch file does this:
TestClass.methods(false)
to get only methods that belong to that class only.
TestClass.instance_methods(false)
would return the methods from your given example (since they are instance methods of TestClass).
Depends on what it's doing. If it has parameters, pass in mocks that you could ask later on if they have been called with the right set of parameters.
I used String
and I converted initially the int
to String
.Then I used the reverse method. I found the reverse of the number in String
and then I converted the string back to int
. Here is the program.
import java.util.*;
public class Panathinaikos {
public static void my_try()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number you want to be reversed");
int number = input.nextInt();
String sReverse = Integer.toString(number);
String reverse = new StringBuffer(sReverse).reverse().toString();
int Reversed = Integer.parseInt(reverse);
System.out.print("The number " + number+ " reversed is " + Reversed);
}
}
void remove_dir(char *path)
{
struct dirent *entry = NULL;
DIR *dir = NULL;
dir = opendir(path);
while(entry = readdir(dir))
{
DIR *sub_dir = NULL;
FILE *file = NULL;
char abs_path[100] = {0};
if(*(entry->d_name) != '.')
{
sprintf(abs_path, "%s/%s", path, entry->d_name);
if(sub_dir = opendir(abs_path))
{
closedir(sub_dir);
remove_dir(abs_path);
}
else
{
if(file = fopen(abs_path, "r"))
{
fclose(file);
remove(abs_path);
}
}
}
}
remove(path);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERE_REQUEST && resultCode == RESULT_OK && data != null)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
You can check if the resultCode equals RESULT_OK this will only be the case if a picture is taken and selected and everything worked. This if clause here should check every condition.
Use gettimeofday()
to get the time in seconds and microseconds. Combining and rounding to milliseconds is left as an exercise.
@GET
does support List of Strings
Setup:
Java : 1.7
Jersey version : 1.9
Resource
@Path("/v1/test")
Subresource:
// receive List of Strings
@GET
@Path("/receiveListOfStrings")
public Response receiveListOfStrings(@QueryParam("list") final List<String> list){
log.info("receieved list of size="+list.size());
return Response.ok().build();
}
Jersey testcase
@Test
public void testReceiveListOfStrings() throws Exception {
WebResource webResource = resource();
ClientResponse responseMsg = webResource.path("/v1/test/receiveListOfStrings")
.queryParam("list", "one")
.queryParam("list", "two")
.queryParam("list", "three")
.get(ClientResponse.class);
Assert.assertEquals(200, responseMsg.getStatus());
}
Return the list directly. Benefits:
You should use the iterator (yield) from when you think you probably won't have to iterate all the way to the end of the list, or when it has no end. For example, the client calling is going to be searching for the first product that satisfies some predicate, you might consider using the iterator, although that's a contrived example, and there are probably better ways to accomplish it. Basically, if you know in advance that the whole list will need to be calculated, just do it up front. If you think that it won't, then consider using the iterator version.
Creation of notification channels are compulsory for Android versions after Android 8.1 (Oreo) for making notifications visible. If notifications are not visible in your app for Oreo+ Androids, you need to call the following function when your app starts -
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name,
importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviours after this
NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
to start, i used the Code posted posted in the first Comment but i changed it like this:
public class LockableScrollView extends ScrollView {
public LockableScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public LockableScrollView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public LockableScrollView(Context context)
{
super(context);
}
// true if we can scroll (not locked)
// false if we cannot scroll (locked)
private boolean mScrollable = true;
public void setScrollingEnabled(boolean enabled) {
mScrollable = enabled;
}
public boolean isScrollable() {
return mScrollable;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
// if we can scroll pass the event to the superclass
if (mScrollable) return super.onTouchEvent(ev);
// only continue to handle the touch event if scrolling enabled
return mScrollable; // mScrollable is always false at this point
default:
return super.onTouchEvent(ev);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
// if we can scroll pass the event to the superclass
if (mScrollable) return super.onInterceptTouchEvent(ev);
// only continue to handle the touch event if scrolling enabled
return mScrollable; // mScrollable is always false at this point
default:
return super.onInterceptTouchEvent(ev);
}
}
}
then i called it in by this way
((LockableScrollView)findViewById(R.id.scrollV)).setScrollingEnabled(false);
because i tried
((LockableScrollView)findViewById(R.id.scrollV)).setIsScrollable(false);
but it said that setIsScrollable is undefined
i hope this will help you
The first method
if (isset($arr['1']))
will not work on an associative array.
For example, the following code displays "Nope, not more than one."
$arr = array(
'a' => 'apple',
'b' => 'banana',
);
if (isset($arr['1'])) {
echo "Yup, more than one.";
} else {
echo "Nope, not more than one.";
}
Although this question is related to string conversion, I stumbled upon this while wanting an easy way to write arrays to my log files. If you just want the info, and don't care about the exact cleanliness of a string you might consider:
json_encode($array)
You can pass parameters in a function like this also:
function FunctionName()
{
Param ([string]$ParamName);
# Operations
}
Placing @EdChum's very nice answer into a function count_unique_index
.
The unique method only works on pandas series, not on data frames.
The function below reproduces the behavior of the unique function in R:
unique returns a vector, data frame or array like x but with duplicate elements/rows removed.
And adds a count of the occurrences as requested by the OP.
df1 = pd.DataFrame({'A':['yes','yes','yes','yes','no','no','yes','yes','yes','no'],
'B':['yes','no','no','no','yes','yes','no','yes','yes','no']})
def count_unique_index(df, by):
return df.groupby(by).size().reset_index().rename(columns={0:'count'})
count_unique_index(df1, ['A','B'])
A B count
0 no no 1
1 no yes 2
2 yes no 4
3 yes yes 3
Use strlen
to get the length of a null-terminated string.
sizeof
returns the length of the array not the string. If it's a pointer (char *s
), not an array (char s[]
), it won't work, since it will return the size of the pointer (usually 4 bytes on 32-bit systems). I believe an array will be passed or returned as a pointer, so you'd lose the ability to use sizeof
to check the size of the array.
So, only if the string spans the entire array (e.g. char s[] = "stuff"
), would using sizeof
for a statically defined array return what you want (and be faster as it wouldn't need to loop through to find the null-terminator) (if the last character is a null-terminator, you will need to subtract 1). If it doesn't span the entire array, it won't return what you want.
An alternative to all this is actually storing the size of the string.
I found a different way to handle this error. (the variables is according to the original question)
JsonNode parsedNodes = mapper.readValue(jsonMessage , JsonNode.class);
Response response = xmlMapper.enable(ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,ACCEPT_SINGLE_VALUE_AS_ARRAY )
.disable(FAIL_ON_UNKNOWN_PROPERTIES, FAIL_ON_IGNORED_PROPERTIES)
.convertValue(parsedNodes, Response.class);
The only illegal characters are &
, <
and >
(as well as "
or '
in attributes, depending on which character is used to delimit the attribute value: attr="must use " here, ' is allowed"
and attr='must use ' here, " is allowed'
).
They're escaped using XML entities, in this case you want &
for &
.
Really, though, you should use a tool or library that writes XML for you and abstracts this kind of thing away for you so you don't have to worry about it.
Using some of the info in here I ended up creating my own function to use.
Could be used as...
custom_alert();
custom_alert( 'Display Message' );
custom_alert( 'Display Message', 'Set Title' );
jQuery UI Alert Replacement
function custom_alert( message, title ) {
if ( !title )
title = 'Alert';
if ( !message )
message = 'No Message to Display.';
$('<div></div>').html( message ).dialog({
title: title,
resizable: false,
modal: true,
buttons: {
'Ok': function() {
$( this ).dialog( 'close' );
}
}
});
}
A better approach from the correct solution here in order to not alter target:
function extend(){
let sources = [].slice.call(arguments, 0), result = {};
sources.forEach(function (source) {
for (let prop in source) {
result[prop] = source[prop];
}
});
return result;
}
Use parse_url() and parse_str().
(You can use regexes for just about anything, but they are very easy to make an error in, so if there are PHP functions specifically for what you are trying to accomplish, use those.)
parse_url takes a string and cuts it up into an array that has a bunch of info. You can work with this array, or you can specify the one item you want as a second argument. In this case we're interested in the query, which is PHP_URL_QUERY
.
Now we have the query, which is v=C4kxS1ksqtw&feature=relate
, but we only want the part after v=
. For this we turn to parse_str
which basically works like GET
on a string. It takes a string and creates the variables specified in the string. In this case $v
and $feature
is created. We're only interested in $v
.
To be safe, you don't want to just store all the variables from the parse_url
in your namespace (see mellowsoon's comment). Instead store the variables as elements of an array, so that you have control over what variables you are storing, and you cannot accidentally overwrite an existing variable.
Putting everything together, we have:
<?php
$url = "http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=relate";
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
echo $my_array_of_vars['v'];
// Output: C4kxS1ksqtw
?>
Edit:
hehe - thanks Charles. That made me laugh, I've never seen the Zawinski quote before:
Some people, when confronted with a problem, think ‘I know, I’ll use regular expressions.’ Now they have two problems.
– Jamie Zawinski
The straightforward way to do this correctly and securely is to use Open3.capture2()
, Open3.capture2e()
, or Open3.capture3()
.
Using ruby's backticks and its %x
alias are NOT SECURE UNDER ANY CIRCUMSTANCES if used with untrusted data. It is DANGEROUS, plain and simple:
untrusted = "; date; echo"
out = `echo #{untrusted}` # BAD
untrusted = '"; date; echo"'
out = `echo "#{untrusted}"` # BAD
untrusted = "'; date; echo'"
out = `echo '#{untrusted}'` # BAD
The system
function, in contrast, escapes arguments properly if used correctly:
ret = system "echo #{untrusted}" # BAD
ret = system 'echo', untrusted # good
Trouble is, it returns the exit code instead of the output, and capturing the latter is convoluted and messy.
The best answer in this thread so far mentions Open3, but not the functions that are best suited for the task. Open3.capture2
, capture2e
and capture3
work like system
, but returns two or three arguments:
out, err, st = Open3.capture3("echo #{untrusted}") # BAD
out, err, st = Open3.capture3('echo', untrusted) # good
out_err, st = Open3.capture2e('echo', untrusted) # good
out, st = Open3.capture2('echo', untrusted) # good
p st.exitstatus
Another mentions IO.popen()
. The syntax can be clumsy in the sense that it wants an array as input, but it works too:
out = IO.popen(['echo', untrusted]).read # good
For convenience, you can wrap Open3.capture3()
in a function, e.g.:
#
# Returns stdout on success, false on failure, nil on error
#
def syscall(*cmd)
begin
stdout, stderr, status = Open3.capture3(*cmd)
status.success? && stdout.slice!(0..-(1 + $/.size)) # strip trailing eol
rescue
end
end
Example:
p system('foo')
p syscall('foo')
p system('which', 'foo')
p syscall('which', 'foo')
p system('which', 'which')
p syscall('which', 'which')
Yields the following:
nil
nil
false
false
/usr/bin/which <— stdout from system('which', 'which')
true <- p system('which', 'which')
"/usr/bin/which" <- p syscall('which', 'which')
I don't think that you really want an iframe, do you?
Unless you're doing something weird, you should be getting your results back as JSON or (in the worst case) XML, right?
For your white box / extra space issue, try
style="display: none;"
instead of
style="visibility: hidden;"
Try that:
bool IsValidURL(string URL)
{
string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return Rgx.IsMatch(URL);
}
It will accept URL like that:
extension UIViewController {
var topbarHeight: CGFloat {
if #available(iOS 13.0, *) {
return (view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0.0) +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
} else {
let topBarHeight = UIApplication.shared.statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
return topBarHeight
}
}
}
Considering only one row is returned, only one loop will be done in both cases. Though it will check for the loop entering condition twice on each.
Because you didn't tell the linker about location of math library. Compile with gcc test.c -o test -lm
You must link an event in your onClick. Additionally, the click function must receive the event. See the example
export default function Component(props) {
function clickEvent (event, variable){
console.log(variable);
}
return (
<div>
<IconButton
key="close"
aria-label="Close"
color="inherit"
onClick={e => clickEvent(e, 10)}
>
</div>
)
}
See this article on alistapart.com. (Ed: The article has been updated since originally linked)
self
is being used to maintain a reference to the original this
even as the context is changing. It's a technique often used in event handlers (especially in closures).
Edit: Note that using self
is now discouraged as window.self
exists and has the potential to cause errors if you are not careful.
What you call the variable doesn't particularly matter. var that = this;
is fine, but there's nothing magic about the name.
Functions declared inside a context (e.g. callbacks, closures) will have access to the variables/function declared in the same scope or above.
For example, a simple event callback:
function MyConstructor(options) {_x000D_
let that = this;_x000D_
_x000D_
this.someprop = options.someprop || 'defaultprop';_x000D_
_x000D_
document.addEventListener('click', (event) => {_x000D_
alert(that.someprop);_x000D_
});_x000D_
}_x000D_
_x000D_
new MyConstructor({_x000D_
someprop: "Hello World"_x000D_
});
_x000D_
a null string is null, an empty string is ""
isNullOrEmpty requires an intimate understanding about the implementation of a string. If you want one, you can write one yourself for your object, but you have to make your own definition for whether your object is "empty" or not.
ask yourself: What does it mean for an object to be empty?
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=2; //try to decrease decoded image
Bitmap bitmap=BitmapFactory.decodeStream(is, null, options);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos); //compressed bitmap to file
What about:
Dynamically grab the #hash
<script>
var urlhash = window.location.hash, //get the hash from url
txthash = urlhash.replace("#", ""); //remove the #
//alert(txthash);
</script>
<?php
$hash = "<script>document.writeln(txthash);</script>";
echo $hash;
?>
To make it more fluent:
Full Example using just Javascript and PHP
<script>
var urlhash = window.location.hash, //get the hash from url
txthash = urlhash.replace("#", ""); //remove the #
function changehash(a,b){
window.location.hash = b; //add hash to url
//alert(b); //alert to test
location.reload(); //reload page to show the current hash
}
</script>
<?php $hash = "<script>document.writeln(txthash);</script>";?>
<a onclick="changehash(this,'#hash1')" style="text-decoration: underline;cursor: pointer;" >Change to #hash1</a><br/>
<a onclick="changehash(this,'#hash2')" style="text-decoration: underline;cursor: pointer;">Change to #hash2</a><br/>
<?php echo "This is the current hash: " . $hash; ?>
This could be an answer to your question:
JSONArray msg1 = (JSONArray) json.get("source");
for(int i = 0; i < msg1.length(); i++){
String name = msg1.getString("name");
int age = msg1.getInt("age");
}
CAUTION: ONLY FOR WINDOWS
I came across this problem today and all the answers mentioned here helped me, but I personally had to dig a lot to solve it. So let me help all others by putting out the solution to it in a very simple form:
Download the executable 64 bit (32-bit if your computer is of 32 bit) exe from here.
(Name of the file would be tesseract-ocr-w64-setup-v5.0.0.20190526 (alpha))
Install it. Let it install itself in the default C directory.
Now go to your Environment variable (Reach there by just searching it in the start menu or Go to Control Panel > System > Advanced System Settings > Environment Variables
)
a) Select PATH and then Edit it. Click on NEW and add the path where it is installed (Usually C:\Program Files\Tesseract-OCR\
)
Now you will not get the error!
For second highest salary, This one work for me:
SELECT salary
FROM employee
WHERE salary
NOT IN (
SELECT MAX( salary )
FROM employee
ORDER BY salary DESC
)
LIMIT 1
HTML:
<input type="text" name="task[]" class="form-control" id="task">
JS:
var tasks= new Array();
$('input[name^="task"]').each(function()
{
tasks.push($(this).val());
});
Since the event object "evt" is not passed from the parameter, is it still possible to obtain this object?
No, not reliably. IE and some other browsers make it available as window.event
(not $(window.event)
), but that's non-standard and not supported by all browsers (famously, Firefox does not).
You're better off passing the event object into the function:
<a href="#" onclick="myFunc(event, 1,2,3)">click</a>
That works even on non-IE browsers because they execute the code in a context that has an event
variable (and works on IE because event
resolves to window.event
). I've tried it in IE6+, Firefox, Chrome, Safari, and Opera. Example: http://jsbin.com/iwifu4
But your best bet is to use modern event handling:
HTML:
<a href="#">click</a>
JavaScript using jQuery (since you're using jQuery):
$("selector_for_the_anchor").click(function(event) {
// Call `myFunc`
myFunc(1, 2, 3);
// Use `event` here at the event handler level, for instance
event.stopPropagation();
});
...or if you really want to pass event
into myFunc
:
$("selector_for_the_anchor").click(function(event) {
myFunc(event, 1, 2, 3);
});
The selector can be anything that identifies the anchor. You have a very rich set to choose from (nearly all of CSS3, plus some). You could add an id
or class
to the anchor, but again, you have other choices. If you can use where it is in the document rather than adding something artificial, great.
If you simply want a Uri for a method that has a route annotation, the following worked for me.
Noting the Route name of the target action, get the relative URL using the controller's URL property as follows:
var routeUrl = Url.RouteUrl("*Route Name Here*", new { *Route parameters here* });
var absUrl = string.Format("{0}://{1}{2}", Request.Scheme,
Request.Host, routeUrl);
var uri = new Uri(absUrl, UriKind.Absolute)
[Produces("application/json")]
[Route("api/Children")]
public class ChildrenController : Controller
{
private readonly ApplicationDbContext _context;
public ChildrenController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/Children
[HttpGet]
public IEnumerable<Child> GetChild()
{
return _context.Child;
}
[HttpGet("uris")]
public IEnumerable<Uri> GetChildUris()
{
return from c in _context.Child
select
new Uri(
$"{Request.Scheme}://{Request.Host}{Url.RouteUrl("GetChildRoute", new { id = c.ChildId })}",
UriKind.Absolute);
}
// GET: api/Children/5
[HttpGet("{id}", Name = "GetChildRoute")]
public IActionResult GetChild([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
Child child = _context.Child.Single(m => m.ChildId == id);
if (child == null)
{
return HttpNotFound();
}
return Ok(child);
}
}
I finally found out how to do this! Basically you need to run adb shell
first and then while you're in the shell run su
, which will switch the shell to run as root!
$: adb shell
$: su
The one problem I still have is that sqlite3 is not installed so the command is not recognized.
Updating a pull request in GitHub is as easy as committing the wanted changes into existing branch (that was used with pull request), but often it is also wanted to squash the changes into single commit:
git checkout yourbranch
git rebase -i origin/master
# Edit command names accordingly
pick 1fc6c95 My pull request
squash 6b2481b Hack hack - will be discarded
squash dd1475d Also discarded
git push -f origin yourbranch
...and now the pull request contains only one commit.
Related links about rebasing:
Execution is not related to laravel go to the php.ini file In php.ini file set max_execution_time=360 (time may be variable depends on need) if you want to increase execution of a specific page then write ini_set('max_execution_time',360) at top of page
otherwise in htaccess php_value max_execution_time 360
SQLFiddle will let you test out your queries, while it doesn't explicitly correct syntax etc. per se it does let you play around with the script and will definitely let you know if things are working or not.
Suppose you were only allowed to use array then you could find the size of 2-d array by the following way.
int ary[][5] = { {1, 2, 3, 4, 5},
{6, 7, 8, 9, 0}
};
int rows = sizeof ary / sizeof ary[0]; // 2 rows
int cols = sizeof ary[0] / sizeof(int); // 5 cols
byte[] bytes = File.ReadAllBytes(filename)
or ...
var bytes = File.ReadAllBytes(filename)
I came up with a unique solution because:
sudo -E "$@"
was leaking variables that was causing problems for my commandsudo VAR1="$VAR1" ... VAR42="$VAR42" "$@"
was long and ugly in my case#!/bin/bash
function sudo_exports(){
eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) "$@"
}
# create a test script to call as sudo
echo 'echo Forty-Two is $VAR42' > sudo_test.sh
chmod +x sudo_test.sh
export VAR42="The Answer to the Ultimate Question of Life, The Universe, and Everything."
export _EXPORTS="_EXPORTS VAR1 VAR2 VAR3 VAR4 VAR5 VAR6 VAR7 VAR8 VAR9 VAR10 VAR11 VAR12 VAR13 VAR14 VAR15 VAR16 VAR17 VAR18 VAR19 VAR20 VAR21 VAR22 VAR23 VAR24 VAR25 VAR26 VAR27 VAR28 VAR29 VAR30 VAR31 VAR32 VAR33 VAR34 VAR35 VAR36 VAR37 VAR38 VAR39 VAR40 VAR41 VAR42"
# clean function style
sudo_exports ./sudo_test.sh
# or just use the content of the function
eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) ./sudo_test.sh
$ ./demo.sh
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.
This is made possible by a feature of the bash builtin printf
. The %q
produces a shell quoted string. Unlike the parameter expansion in bash 4.4, this works in bash versions < 4.0
The Java XML parser that spring uses will read the schemaLocation
values and try to load them from the internet, in order to validate the XML file. Spring, in turn, intercepts those load requests and serves up versions from inside its own JAR files.
If you omit the schemaLocation
, then the XML parser won't know where to get the schema in order to validate the config.
Here is an example I used to connect node.js to my Postgres database.
The interface in node.js that I used can be found here https://github.com/brianc/node-postgres
var pg = require('pg');
var conString = "postgres://YourUserName:YourPassword@localhost:5432/YourDatabase";
var client = new pg.Client(conString);
client.connect();
//queries are queued and executed one after another once the connection becomes available
var x = 1000;
while (x > 0) {
client.query("INSERT INTO junk(name, a_number) values('Ted',12)");
client.query("INSERT INTO junk(name, a_number) values($1, $2)", ['John', x]);
x = x - 1;
}
var query = client.query("SELECT * FROM junk");
//fired after last row is emitted
query.on('row', function(row) {
console.log(row);
});
query.on('end', function() {
client.end();
});
//queries can be executed either via text/parameter values passed as individual arguments
//or by passing an options object containing text, (optional) parameter values, and (optional) query name
client.query({
name: 'insert beatle',
text: "INSERT INTO beatles(name, height, birthday) values($1, $2, $3)",
values: ['George', 70, new Date(1946, 02, 14)]
});
//subsequent queries with the same name will be executed without re-parsing the query plan by postgres
client.query({
name: 'insert beatle',
values: ['Paul', 63, new Date(1945, 04, 03)]
});
var query = client.query("SELECT * FROM beatles WHERE name = $1", ['john']);
//can stream row results back 1 at a time
query.on('row', function(row) {
console.log(row);
console.log("Beatle name: %s", row.name); //Beatle name: John
console.log("Beatle birth year: %d", row.birthday.getYear()); //dates are returned as javascript dates
console.log("Beatle height: %d' %d\"", Math.floor(row.height / 12), row.height % 12); //integers are returned as javascript ints
});
//fired after last row is emitted
query.on('end', function() {
client.end();
});
UPDATE:- THE query.on
function is now deprecated and hence the above code will not work as intended. As a solution for this look at:- query.on is not a function
It seems that your eclipse-workspace
(or at least your Project
) is broken somehow.
Have you moved your android-sdk/Project
recently? If it's not an Android Project anymore, try to look at Preferences->Android
for a valid android sdk-location
.
If this is correct, try to open a complete new Workspace, and import your sources with File->import->Android Project
from existing Source.
If this still doesn't help, make a new android Project
and copy the sources manually inside your Project
from outside Eclipse
. Re-open Eclipse after that, and make a Project->clean
You have to add click event to an exist element. You can not add event to dom elements dynamic created. I you want to add event to them, you should bind event to an existed element using ".on".
$('p').on('click','selector_you_dynamic_created',function(){...});
.delegate should work,too.
Check this one (Password should be password):
<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-6138db82-5a4c-4bf7-915f-af7a10d9ae96">
<wsse:Username>user</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">CBb7a2itQDgxVkqYnFtggUxtuqk=</wsse:Password>
<wsse:Nonce>5ABcqPZWb6ImI2E6tob8MQ==</wsse:Nonce>
<wsu:Created>2010-06-08T07:26:50Z</wsu:Created>
</wsse:UsernameToken>
This is a late answer, but by looking at the source code, I noticed that when the video is fullscreen, the "mejs-container-fullscreen" class is added to the "mejs-container" element. It is thus possible to change the styling based on this class.
.mejs-container.mejs-container-fullscreen {
// This rule applies only to the container when in fullscreen
padding-top: 57%;
}
Also, if you wish to make your MediaElement video fluid using CSS, below is a great trick by Chris Coyier: http://css-tricks.com/rundown-of-handling-flexible-media/
Just add this to your CSS:
.mejs-container {
width: 100% !important;
height: auto !important;
padding-top: 57%;
}
.mejs-overlay, .mejs-poster {
width: 100% !important;
height: 100% !important;
}
.mejs-mediaelement video {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
width: 100% !important;
height: 100% !important;
}
I hope it helps.
@gdbj's answer is a great explanation and the most up to date answer. Here's however a simpler approach.
So if you want to redirect all traffic from nginx listening to 80
to another container exposing 8080
, minimum configuration can be as little as:
nginx.conf:
server {
listen 80;
location / {
proxy_pass http://client:8080; # this one here
proxy_redirect off;
}
}
docker-compose.yml
version: "2"
services:
entrypoint:
image: some-image-with-nginx
ports:
- "80:80"
links:
- client # will use this one here
client:
image: some-image-with-api
ports:
- "8080:8080"
If you're using the wonderful ondrej/php
ubuntu repository with php7.0:
sudo apt-get install php7.0-pgsql
For ondrej/php
Ubuntu repository with php7.1:
sudo apt-get install php7.1-pgsql
Same repository, but for php5.6:
sudo apt-get install php5.6-pgsql
Concise and easy to remember. I love this repository.
Could you give some indication of what platforms you are writing for? This should weigh heavily on what is 'best'. You might find a super 'xml-foo' library that does not ship commonly on most systems by default .. while its great, the lack of the library might prevent (or at least) annoy users.
Mostly, I use libxml2 .. because its standard or easy to install on the platforms that I target.
As you see, 'best' is also determined by the library being available on your target platforms.
You said that you can’t use HTML comments because the CMS filters them out. So I assume that you really want to hide this content and you don’t need to display it ever.
In that case, you shouldn’t use CSS (only), as you’d only play on the presentation level, not affecting the content level. Your content should also be hidden for user-agents ignoring the CSS (people using text browsers, feed readers, screen readers; bots; etc.).
In HTML5 there is the global hidden
attribute:
When specified on an element, it indicates that the element is not yet, or is no longer, directly relevant to the page's current state, or that it is being used to declare content to be reused by other parts of the page as opposed to being directly accessed by the user. User agents should not render elements that have the
hidden
attribute specified.
Example (using the small
element here, because it’s an "attribution"):
<small hidden>Thanks to John Doe for this idea.</small>
As a fallback (for user-agents that don’t know the hidden
attribute), you can specify in your CSS:
[hidden] {display:none;}
An general element for plain text could be the script
element used as "data block":
<script type="text/plain" hidden>
Thanks to John Doe for this idea.
</script>
Alternatively, you could also use data-*
attributes on existing elements (resp. on new div
elements if you want to group some elements for the attribution):
<p data-attribution="Thanks to John Doe for this idea!">This is some visible example content …</p>
See http://www.oracle.com/technetwork/java/javase/tsg-vm-149989.pdf. You can use "jdb" directly on the core file.
What should I do to prepare my website for https. (Do I need to alter the code / Config)
You should keep best practices for secure coding in mind (here is a good intro: http://www.owasp.org/index.php/Secure_Coding_Principles ), otherwise all you need is a correctly set up SSL certificate.
Is SSL and https one and the same..
Pretty much, yes.
Do I need to apply with someone to get some license or something.
You can buy an SSL certificate from a certificate authority or use a self-signed certificate. The ones you can purchase vary wildly in price - from $10 to hundreds of dollars a year. You would need one of those if you set up an online shop, for example. Self-signed certificates are a viable option for an internal application. You can also use one of those for development. Here's a good tutorial on how to set up a self-signed certificate for IIS: Enabling SSL on IIS 7.0 Using Self-Signed Certificates
Do I need to make all my pages secured or only the login page..
Use HTTPS for everything, not just the initial user login. It's not going to be too much of an overhead and it will mean the data that the users send/receive from your remotely hosted application cannot be read by outside parties if it is intercepted. Even Gmail now turns on HTTPS by default.
The documentation for writelines()
states:
writelines()
does not add line separators
So you'll need to add them yourself. For example:
line_list.append(new_line + "\n")
whenever you append a new item to line_list
.
Your best bet is
$(document).keyup(function(e) {
if (e.which === 13) $('.save').click(); // enter
if (e.which === 27) $('.cancel').click(); // esc
/* OPTIONAL: Only if you want other elements to ignore event */
e.preventDefault();
e.stopPropagation();
});
Summary
which
is more preferable than keyCode
because it is normalizedkeyup
is more preferable than keydown
because keydown may occur multiple times if user keeps it pressed.keypress
unless you want to capture actual characters.Interestingly Bootstrap uses keydown and keyCode in its dropdown component (as of 3.0.2)! I think it's probably poor choice there.
Related snippet from JQuery doc
While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows. For catching actual text entry, .keypress() may be a better choice.
Other item of interest: JavaScript Keypress Library
(<HTMLInputElement>document.getElementById('loginInput')).value = '123';
Angular cannot take HTML elements directly thereby you need to specify the element type by binding the above generic to it.
UPDATE::
This can also be done using ViewChild with #localvariable as shown here, as mentioned in here
<textarea #someVar id="tasknote"
name="tasknote"
[(ngModel)]="taskNote"
placeholder="{{ notePlaceholder }}"
style="background-color: pink"
(blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }}
</textarea>
import {ElementRef,Renderer2} from '@angular/core';
@ViewChild('someVar') el:ElementRef;
constructor(private rd: Renderer2) {}
ngAfterViewInit() {
console.log(this.rd);
this.el.nativeElement.focus(); //<<<=====same as oldest way
}
Source script has some problem with subshell. First example, you probably do not need subshell. But We don't know what is hidden under "Some more action". The most popular answer has hidden bug, that will increase I/O, and won't work with subshell, because it restores couter inside loop.
Do not fortot add '\' sign, it will inform bash interpreter about line continuation. I hope it will help you or anybody. But in my opinion this script should be fully converted to AWK script, or else rewritten to python using regexp, or perl, but perl popularity over years is degraded. Better do it with python.
Corrected Version without subshell:
#!/bin/bash
WFY_PATH=/var/log/nginx
WFY_FILE=error.log
COUNTER=0
grep 'GET /log_' $WFY_PATH/$WFY_FILE | grep 'upstream timed out' |\
awk -F ', ' '{print $2,$4,$0}' |\
awk '{print "http://example.com"$5"&ip="$2"&date="$7"&time="$8"&end=1"}' |\
awk -F '&end=1' '{print $1"&end=1"}' |\
#( #unneeded bracket
while read WFY_URL
do
echo $WFY_URL #Some more action
COUNTER=$((COUNTER+1))
done
# ) unneeded bracket
echo $COUNTER # output = 0
Version with subshell if it is really needed
#!/bin/bash
TEMPFILE=/tmp/$$.tmp #I've got it from the most popular answer
WFY_PATH=/var/log/nginx
WFY_FILE=error.log
COUNTER=0
grep 'GET /log_' $WFY_PATH/$WFY_FILE | grep 'upstream timed out' |\
awk -F ', ' '{print $2,$4,$0}' |\
awk '{print "http://example.com"$5"&ip="$2"&date="$7"&time="$8"&end=1"}' |\
awk -F '&end=1' '{print $1"&end=1"}' |\
(
while read WFY_URL
do
echo $WFY_URL #Some more action
COUNTER=$((COUNTER+1))
done
echo $COUNTER > $TEMPFILE #store counter only once, do it after loop, you will save I/O
)
COUNTER=$(cat $TEMPFILE) #restore counter
unlink $TEMPFILE
echo $COUNTER # output = 0
I am implementing old http (0.9, 1.0, 1.1) request and response reader/writer. Request URI is the most problematic place.
You can't just use RFC 1738, 2396 or 3986 as it is. There are many old HTTP clients and servers that allows more characters. So I've made research based on accidentally published webserver access logs: "GET URI HTTP/1.0" 200
.
I've found that the following non-standard characters are often used in URI:
\ { } < > | ` ^ "
These characters were described in RFC 1738 as unsafe.
If you want to be compatible with all old HTTP clients and servers - you have to allow these characters in request URI.
Please read more information about this research in oghttp-request-collector.
I think a combination of xdg-open as described by shellholic and - if it fails - the solution to finding a browser using the which
command as described here is probably the best solution.
The easiest way to add a text to a JFrame:
JFrame window = new JFrame("JFrame with text");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new BorderLayout());
window.add(new JLabel("Hello World"), BorderLayout.CENTER);
window.pack();
window.setVisible(true);
window.setLocationRelativeTo(null);
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); //copy
In this case, list1
is of type ArrayList
.
List<Integer> list2 = Arrays.asList(ia);
Here, the list is returned as a List
view, meaning it has only the methods attached to that interface. Hence why some methods are not allowed on list2
.
ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));
Here, you ARE creating a new ArrayList
. You're simply passing it a value in the constructor. This is not an example of casting. In casting, it might look more like this:
ArrayList list1 = (ArrayList)Arrays.asList(ia);
The first argument of all methods is usually called self
. It refers to the instance for which the method is being called.
Let's say you have:
class A(object):
def foo(self):
print 'Foo'
def bar(self, an_argument):
print 'Bar', an_argument
Then, doing:
a = A()
a.foo() #prints 'Foo'
a.bar('Arg!') #prints 'Bar Arg!'
There's nothing special about this being called self
, you could do the following:
class B(object):
def foo(self):
print 'Foo'
def bar(this_object):
this_object.foo()
Then, doing:
b = B()
b.bar() # prints 'Foo'
In your specific case:
dangerous_device = MissileDevice(some_battery)
dangerous_device.move(dangerous_device.RIGHT)
(As suggested in comments MissileDevice.RIGHT
could be more appropriate here!)
You could declare all your constants at module level though, so you could do:
dangerous_device.move(RIGHT)
This, however, is going to depend on how you want your code to be organized!
Synchronized locks does not offer any mechanism of waiting queue in which after the execution of one thread any thread running in parallel can acquire the lock. Due to which the thread which is there in the system and running for a longer period of time never gets chance to access the shared resource thus leading to starvation.
Reentrant locks are very much flexible and has a fairness policy in which if a thread is waiting for a longer time and after the completion of the currently executing thread we can make sure that the longer waiting thread gets the chance of accessing the shared resource hereby decreasing the throughput of the system and making it more time consuming.
If you have already got the cursor, then this is how you may get the last record from cursor:
cursor.moveToPosition(cursor.getCount() - 1);
//then use cursor to read values
So it turns out that the problem comes from one line in modules\imgproc\src\imgwarp.cpp
:
CV_Assert( ssize.area() > 0 );
When the product of rows and columns of the image to be resized is larger than 2^31, ssize.area() results in a negative number. This appears to be a bug in OpenCV and hopefully will be fixed in the future release. A temporary fix is to build OpenCV with this line commented out. While not ideal, it works for me.
And I just recently found out that the above applies only to image whose width is larger than height. For images with height larger than width, it's the following line that causes error:
CV_Assert( dsize.area() > 0 );
So this has to be commented out as well.
If you do not want to hardcode calls to each getter and setter, reflection is the only way to call these methods (but it is not hard).
Can you refactor the class in question to use a Properties object to hold the actual data, and let each getter and setter just call get/set on it? Then you have a structure well suited for what you want to do. There is even methods to save and load them in the key-value form.
Is null an instance of anything?
No, there is no type which null
is an instanceof
.
instanceof
RelationalExpression: RelationalExpression instanceof ReferenceType
At run time, the result of the
instanceof
operator istrue
if the value of the RelationalExpression is notnull
and the reference could be cast to the ReferenceType without raising aClassCastException
. Otherwise the result isfalse
.
This means that for any type E
and R
, for any E o
, where o == null
, o instanceof R
is always false
.
What set does 'null' belong to?
There is also a special null type, the type of the expression
null
, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. Thenull
reference is the only possible value of an expression of null type. Thenull
reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend thatnull
is merely a special literal that can be of any reference type.
What is null?
As the JLS quote above says, in practice you can simply pretend that it's "merely a special literal that can be of any reference type".
In Java, null == null
(this isn't always the case in other languages). Note also that by contract, it also has this special property (from java.lang.Object
):
public boolean equals(Object obj)
For any non-
null
reference valuex
,x.equals(null)
shouldreturn false
.
It is also the default value (for variables that have them) for all reference types:
- Each class variable, instance variable, or array component is initialized with a default value when it is created:
- For all reference types, the default value is
null
.
How this is used varies. You can use it to enable what is called lazy initialization of fields, where a field would have its initial value of null
until it's actually used, where it's replaced by the "real" value (which may be expensive to compute).
There are also other uses. Let's take a real example from java.lang.System
:
public static Console console()
Returns: The system console, if any, otherwise
null
.
This is a very common use pattern: null
is used to denote non-existence of an object.
Here's another usage example, this time from java.io.BufferedReader
:
public String readLine() throws IOException
Returns: A
String
containing the contents of the line, not including any line-termination characters, ornull
if the end of the stream has been reached.
So here, readLine()
would return instanceof String
for each line, until it finally returns a null
to signify the end. This allows you to process each line as follows:
String line;
while ((line = reader.readLine()) != null) {
process(line);
}
One can design the API so that the termination condition doesn't depend on readLine()
returning null
, but one can see that this design has the benefit of making things concise. Note that there is no problem with empty lines, because an empty line "" != null
.
Let's take another example, this time from java.util.Map<K,V>
:
V get(Object key)
Returns the value to which the specified key is mapped, or
null
if this map contains no mapping for the key.If this map permits
null
values, then a return value ofnull
does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key tonull
. ThecontainsKey
operation may be used to distinguish these two cases.
Here we start to see how using null
can complicate things. The first statement says that if the key isn't mapped, null
is returned. The second statement says that even if the key is mapped, null
can also be returned.
In contrast, java.util.Hashtable
keeps things simpler by not permitting null
keys and values; its V get(Object key)
, if returns null
, unambiguously means that the key isn't mapped.
You can read through the rest of the APIs and find where and how null
is used. Do keep in mind that they aren't always the best practice examples.
Generally speaking, null
are used as a special value to signify:
How is it represented in the memory?
In Java? None of your concern. And it's best kept that way.
null
a good thing?This is now borderline subjective. Some people say that null
causes many programmer errors that could've been avoided. Some say that in a language that catches NullPointerException
like Java, it's good to use it because you will fail-fast on programmer errors. Some people avoid null
by using Null object pattern, etc.
This is a huge topic on its own, so it's best discussed as answer to another question.
I will end this with a quote from the inventor of null
himself, C.A.R Hoare (of quicksort fame):
I call it my billion-dollar mistake. It was the invention of the
null
reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in anull
reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.
The video of this presentation goes deeper; it's a recommended watch.
The problem here is that you are trying to await
an array of promises rather than a promise. This doesn't do what you expect.
When the object passed to await
is not a Promise, await
simply returns the value as-is immediately instead of trying to resolve it. So since you passed await
an array (of Promise objects) here instead of a Promise, the value returned by await is simply that array, which is of type Promise<number>[]
.
What you need to do here is call Promise.all
on the array returned by map
in order to convert it to a single Promise before await
ing it.
According to the MDN docs for Promise.all
:
The
Promise.all(iterable)
method returns a promise that resolves when all of the promises in the iterable argument have resolved, or rejects with the reason of the first passed promise that rejects.
So in your case:
var arr = [1, 2, 3, 4, 5];
var results: number[] = await Promise.all(arr.map(async (item): Promise<number> => {
await callAsynchronousOperation(item);
return item + 1;
}));
This will resolve the specific error you are encountering here.
Added streaming support based on the answer of @dunes:
import re
from json import JSONDecoder, JSONDecodeError
NOT_WHITESPACE = re.compile(r"[^\s]")
def stream_json(file_obj, buf_size=1024, decoder=JSONDecoder()):
buf = ""
ex = None
while True:
block = file_obj.read(buf_size)
if not block:
break
buf += block
pos = 0
while True:
match = NOT_WHITESPACE.search(buf, pos)
if not match:
break
pos = match.start()
try:
obj, pos = decoder.raw_decode(buf, pos)
except JSONDecodeError as e:
ex = e
break
else:
ex = None
yield obj
buf = buf[pos:]
if ex is not None:
raise ex
If it is asking you for a username and password, your origin remote is pointing at the HTTPS URL rather than the SSH URL.
Change it to ssh.
For example, a GitHub project like Git will have an HTTPS URL:
https://github.com/<Username>/<Project>.git
And the SSH one:
[email protected]:<Username>/<Project>.git
You can do:
git remote set-url origin [email protected]:<Username>/<Project>.git
to change the URL.
Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)
example:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new WebBrowser());
}
}
If you want to use a format that allows you to keep the number like your entry this format works for me:
"# \\%"
There are 4 methods you can use:
Consider the following sample TABLE
with test data:
/** Create test table */
CREATE TEMPORARY TABLE dupes(word text, num int, id int);
/** Add test data with duplicates */
INSERT INTO dupes(word, num, id)
VALUES ('aaa', 100, 1)
,('bbb', 200, 2)
,('ccc', 300, 3)
,('bbb', 400, 4)
,('bbb', 200, 5) -- duplicate
,('ccc', 300, 6) -- duplicate
,('ddd', 400, 7)
,('bbb', 400, 8) -- duplicate
,('aaa', 100, 9) -- duplicate
,('ccc', 300, 10); -- duplicate
This is the most simple and straight forward, but also the most limited way:
SELECT DISTINCT word, num
FROM dupes
ORDER BY word, num;
/*
word|num|
----|---|
aaa |100|
bbb |200|
bbb |400|
ccc |300|
ddd |400|
*/
Grouping allows you to add aggregated data, like the min(id)
, max(id)
, count(*)
, etc:
SELECT word, num, min(id), max(id), count(*)
FROM dupes
GROUP BY word, num
ORDER BY word, num;
/*
word|num|min|max|count|
----|---|---|---|-----|
aaa |100| 1| 9| 2|
bbb |200| 2| 5| 2|
bbb |400| 4| 8| 2|
ccc |300| 3| 10| 3|
ddd |400| 7| 7| 1|
*/
Using a subquery, you can first identify the duplicate rows to ignore, and then filter them out in the outer query with the WHERE NOT IN (subquery)
construct:
/** Find the higher id values of duplicates, distinct only added for clarity */
SELECT distinct d2.id
FROM dupes d1
INNER JOIN dupes d2 ON d2.word=d1.word AND d2.num=d1.num
WHERE d2.id > d1.id
/*
id|
--|
5|
6|
8|
9|
10|
*/
/** Use the previous query in a subquery to exclude the dupliates with higher id values */
SELECT *
FROM dupes
WHERE id NOT IN (
SELECT d2.id
FROM dupes d1
INNER JOIN dupes d2 ON d2.word=d1.word AND d2.num=d1.num
WHERE d2.id > d1.id
)
ORDER BY word, num;
/*
word|num|id|
----|---|--|
aaa |100| 1|
bbb |200| 2|
bbb |400| 4|
ccc |300| 3|
ddd |400| 7|
*/
In the Common Table Expression (CTE), select the ROW_NUMBER(), partitioned by the group column and ordered in the desired order. Then SELECT only the records that have ROW_NUMBER() = 1
:
WITH CTE AS (
SELECT *
,row_number() OVER(PARTITION BY word, num ORDER BY id) AS row_num
FROM dupes
)
SELECT word, num, id
FROM cte
WHERE row_num = 1
ORDER BY word, num;
/*
word|num|id|
----|---|--|
aaa |100| 1|
bbb |200| 2|
bbb |400| 4|
ccc |300| 3|
ddd |400| 7|
*/
Based on Nicolas Gauthier answer:
var strng = 'someobj.someCallback';
var data = 'someData';
var func = window;
var funcSplit = strng.split('.');
for(i = 0;i < funcSplit.length;i++){
//We maybe can check typeof and break the bucle if typeof != function
func = func[funcSplit[i]];
}
func(data);
It helped me
function IsIE8Browser() {
var rv = -1;
var ua = navigator.userAgent;
var re = new RegExp("Trident\/([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null) {
rv = parseFloat(RegExp.$1);
}
return (rv == 4);
}
As @nizantz previously mentioned, using Date.parse() wasn't working for me in Safari. After a bit of research, I learned that the lastDateModified property for the File object has been deprecated, and is no longer supported by Safari. Using the lastModified property of the File object resolved my issues. Sure dislike it when bad info is found online.
Thanks to all who contributed to this post that assisted me in going down the path I needed to learn about my issue. Had it not been for this info, I never would have probably figured out my root issue. Maybe this will help someone else in my similar situation.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse("file.xml");
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getChildNodes();
int length = nl.getLength();
for (int i = 0; i < length; i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) nl.item(i);
if (el.getNodeName().contains("staff")) {
String name = el.getElementsByTagName("name").item(0).getTextContent();
String phone = el.getElementsByTagName("phone").item(0).getTextContent();
String email = el.getElementsByTagName("email").item(0).getTextContent();
String area = el.getElementsByTagName("area").item(0).getTextContent();
String city = el.getElementsByTagName("city").item(0).getTextContent();
}
}
}
Iterate over all children and nl.item(i).getNodeType() == Node.ELEMENT_NODE
is used to filter text nodes out. If there is nothing else in XML what remains are staff nodes.
For each node under stuff (name, phone, email, area, city)
el.getElementsByTagName("name").item(0).getTextContent();
el.getElementsByTagName("name")
will extract the "name" nodes under stuff,
.item(0)
will get you the first node
and .getTextContent()
will get the text content inside.
Edit: Since we have jackson I would do this in a different way. Define a pojo for the object:
public class Staff {
private String name;
private String phone;
private String email;
private String area;
private String city;
...getters setters
}
Then using jackson:
JsonNode root = new XmlMapper().readTree(xml.getBytes());
ObjectMapper mapper = new ObjectMapper();
root.forEach(node -> consume(node, mapper));
private void consume(JsonNode node, ObjectMapper mapper) {
try {
Staff staff = mapper.treeToValue(node, Staff.class);
//TODO your job with staff
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
There is no simple way to do this, you basically need to subclass UITabBar and implement custom drawing to do what you want. It is quite a bit of work for the effect, but it may be worth it. I recommend filing a bug with Apple to get it added to a future iPhone SDK.
You have to dot source
them:
. .\build_funtions.ps1
. .\build_builddefs.ps1
Note the extra .
This heyscriptingguy
article should be of help - How to Reuse Windows PowerShell Functions in Scripts
like @nd says but using the built-in function of int to convert to a different base
>>> [ int(i,16) for i in '0123456789ABCDEF' ]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>> [int(i,2) for i in "100 010 110 111".split()]
[4, 2, 6, 7]
I don't know what is the final objective but take a look also inside the decimal module of python for doing stuff like
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
<a href="<?php echo $_SERVER['DOCUMENT_ROOT'].'/hello.html'; ?>">go with php</a>
<br />
<a href="/hello.html">go to with html</a>
Try this yourself and find that they are not exactly the same.
$_SERVER['DOCUMENT_ROOT']
renders an actual file path (on my computer running as it's own server, C:/wamp/www/
HTML's /
renders the root of the server url, in my case, localhost/
But C:/wamp/www/hello.html
and localhost/hello.html
are in fact the same file
The below function would return '0' if there is no match and a 'positive integer' in case of matching:
Function IsInArray(stringToBeFound As String, arr As Variant) As Integer
IsInArray = InStr(Join(arr, ""), stringToBeFound)
End Function
______________________________________________________________________________
Note: the function first concatenates the entire array content to a string using 'Join' (not sure if the join method uses looping internally or not) and then checks for a macth within this string using InStr.
Just put in the function using GLOBAL keyword:
global $site_url;
Axivion Bauhaus Suite is a static analysis tool that works with C# (as well as C, C++ and Java).
It provides the following capabilities:
These features can be run on a one-off basis or as part of a Continuous Integration process. Issues can be highlighted on a per project basis or per developer basis when the system is integrated with a source code control system.
For .NET 4.6.2 or lower, .NET Core 1.x, and .NET Standard 1.x you need to install the NuGet package System.ValueTuple
:
Install-Package "System.ValueTuple"
Or using a package reference in VS 2017:
<PackageReference Include="System.ValueTuple" Version="4.4.0" />
.NET Framework 4.7, .NET Core 2.0, and .NET Standard 2.0 include these types.
As KhAn SaAb has stated, you need to set your path.
But in order for your JDK to take advantage of tools such as Maven in the future, I would assign a JAVA_HOME
path to point to your JDK folder and then just add the %JAVA_HOME%\bin
directory to your PATH
.
JAVA_HOME = "C:\Program Files\Java\jdk1.8.0"
PATH = %PATH%\%JAVA_HOME%\bin
In Windows:
blah;blah;blah;
C:\Program Files\Java\jdk1.8.0\bin;blah,blah;blah
to:
blah;blah;blah;
%JAVA_HOME%\bin;blah,blah;blah
$('#timePicker').datetimepicker({
// dateFormat: 'dd-mm-yy',
format:'DD/MM/YYYY HH:mm:ss',
minDate: getFormattedDate(new Date())
});
function getFormattedDate(date) {
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear().toString().slice(2);
return day + '-' + month + '-' + year;
}
You need to pass datepicker() the date formatted correctly.
See the documentation for the print function: print()
The content of end
is printed after the thing you want to print. By default it contains a newline ("\n"
) but it can be changed to something else, like an empty string.
In your build.gradle add this dependency:
compile 'com.android.support:multidex:1.0.1'
again in your build.gradle file add this line to defaultConfig block:
multiDexEnabled true
Instead of extending your application class from Application extend it from MultiDexApplication ; like :
public class AppConfig extends MultiDexApplication {
now you're good to go! And in case you need it, all MultiDexApplication
does is
public class MultiDexApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
If you need to remove white spaces at the end then here is a solution: https://www.geeksforgeeks.org/urlify-given-string-replace-spaces/
const stringQ1 = (string)=>{_x000D_
//remove white space at the end _x000D_
const arrString = string.split("")_x000D_
for(let i = arrString.length -1 ; i>=0 ; i--){_x000D_
let char = arrString[i];_x000D_
_x000D_
if(char.indexOf(" ") >=0){_x000D_
arrString.splice(i,1)_x000D_
}else{_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
let start =0;_x000D_
let end = arrString.length -1;_x000D_
_x000D_
_x000D_
//add %20_x000D_
while(start < end){_x000D_
if(arrString[start].indexOf(' ') >=0){_x000D_
arrString[start] ="%20"_x000D_
_x000D_
}_x000D_
_x000D_
start++;_x000D_
}_x000D_
_x000D_
return arrString.join('');_x000D_
}_x000D_
_x000D_
console.log(stringQ1("Mr John Smith "))
_x000D_
Check out Pathname and in particular Pathname#exist?
.
File and its FileTest module are perhaps simpler/more direct, but I find Pathname
a nicer interface in general.
You can do it with Linq, as mamoo showed, but the oldies are good too:
var filteredDataTable = dt.Select(@"EmpId > 2
AND (EmpName <> 'abc' OR EmpName <> 'xyz')
AND EmpName like '%il%'" );
To optimize the EXISTS
, be very literal; something just has to be there, but you don't actually need any data returned from the correlated sub-query. You're just evaluating a Boolean condition.
So:
WHERE EXISTS (SELECT TOP 1 1 FROM Base WHERE bx.BoxID = Base.BoxID AND [Rank] = 2)
Because the correlated sub-query is RBAR
, the first result hit makes the condition true, and it is processed no further.
WARNING: size()
was deprecated in jQuery 1.8 and removed in jQuery 3.0, use .length
instead
Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/
$(document).ready(function () {
size_li = $("#myList li").size();
x=3;
$('#myList li:lt('+x+')').show();
$('#loadMore').click(function () {
x= (x+5 <= size_li) ? x+5 : size_li;
$('#myList li:lt('+x+')').show();
});
$('#showLess').click(function () {
x=(x-5<0) ? 3 : x-5;
$('#myList li').not(':lt('+x+')').hide();
});
});
$(document).ready(function () {
size_li = $("#myList li").size();
x=3;
$('#myList li:lt('+x+')').show();
$('#loadMore').click(function () {
x= (x+5 <= size_li) ? x+5 : size_li;
$('#myList li:lt('+x+')').show();
$('#showLess').show();
if(x == size_li){
$('#loadMore').hide();
}
});
$('#showLess').click(function () {
x=(x-5<0) ? 3 : x-5;
$('#myList li').not(':lt('+x+')').hide();
$('#loadMore').show();
$('#showLess').show();
if(x == 3){
$('#showLess').hide();
}
});
});
CSS
#showLess {
color:red;
cursor:pointer;
display:none;
}
Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/2/
Blue forrest makes for a very good dark theme, because it has appealing blues with yellows and greens mixed in. Highly recommended.
http://www.decodified.com/misc/2011/06/15/blueforest-a-dark-color-scheme-for-intellij-idea.html
I would do this the other way round.
In the OnLoad event for your Main form show the Logon form as a dialog. If the dialog result of that is OK then allow Main to continue loading, if the result is authentication failure then abort the load and show the message box.
EDIT Code sample(s)
private void MainForm_Load(object sender, EventArgs e)
{
this.Hide();
LogonForm logon = new LogonForm();
if (logon.ShowDialog() != DialogResult.OK)
{
//Handle authentication failures as necessary, for example:
Application.Exit();
}
else
{
this.Show();
}
}
Another solution would be to show the LogonForm from the Main method in program.cs, something like this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LogonForm logon = new LogonForm();
Application.Run(logon);
if (logon.LogonSuccessful)
{
Application.Run(new MainForm());
}
}
In this example your LogonForm would have to expose out a LogonSuccessful bool property that is set to true when the user has entered valid credentials
Good question. But I think there is no good answer which fits your criteria. The best I can think of is to use an extra vars file.
A task like this:
- include_vars: concat.yml
And in concat.yml
you have your definition:
newvar: "{{ var1 }}-{{ var2 }}-{{ var3 }}"
You have to use Kendo UI DropDownList select
method (documentation in here).
Basically you should:
// get a reference to the dropdown list
var dropdownlist = $("#Instrument").data("kendoDropDownList");
If you know the index you can use:
// selects by index
dropdownlist.select(1);
If not, use:
// selects item if its text is equal to "test" using predicate function
dropdownlist.select(function(dataItem) {
return dataItem.symbol === "test";
});
JSFiddle example here
If you want to use location.href
to avoid popup problems, you can use an empty <a>
ref and then use javascript to click it.
something like in HTML
<a id="anchorID" href="mynewurl" target="_blank"></a>
Then javascript click it as follows
document.getElementById("anchorID").click();
In case you want unix timestamp
let now : Date = Date()
let currentCalendar : NSCalendar = Calendar.current as NSCalendar
let nowPlusAddTime : Date = currentCalendar.date(byAdding: .second, value: accessTime, to: now, options: .matchNextTime)!
let unixTime = nowPlusAddTime.timeIntervalSince1970
To add to the valuable content, I would like to create this reminder on why sometimes RegEx within VBA is not ideal. Not all expressions are supported, but instead may throw an Error 5017
and may leave the author guessing (which I am a victim of myself).
Whilst we can find some sources on what is supported, it would be helpfull to know which metacharacters etc. are not supported. A more in-depth explaination can be found here. Mentioned in this source:
"Although "VBScript’s regular expression ... version 5.5 implements quite a few essential regex features that were missing in previous versions of VBScript. ... JavaScript and VBScript implement Perl-style regular expressions. However, they lack quite a number of advanced features available in Perl and other modern regular expression flavors:"
So, not supported are:
\A
, alternatively use the ^
caret to match postion before 1st char in string\Z
, alternatively use the $
dollar sign to match postion after last char in string(?<=a)b
(whilst postive LookAhead is supported)(?<!a)b
(whilst negative LookAhead is supported)\{uFFFF}
/i
(case sensitivity) or /g
(global) etc. Set these through the RegExp
object properties > RegExp.Global = True
and RegExp.IgnoreCase = True
if available.'
comments in script I already hit a wall more than once using regular expressions within VBA. Usually with LookBehind
but sometimes I even forget the modifiers. I have not experienced all these above mentioned backdrops myself but thought I would try to be extensive referring to some more in-depth information. Feel free to comment/correct/add. Big shout out to regular-expressions.info for a wealth of information.
P.S. You have mentioned regular VBA methods and functions, and I can confirm they (at least to myself) have been helpful in their own ways where RegEx would fail.
An even better idea is to use the requests_toolbelt library, which can dump out both requests and responses as strings for you to print to the console. It handles all the tricky cases with files and encodings which the above solution does not handle well.
It's as easy as this:
import requests
from requests_toolbelt.utils import dump
resp = requests.get('https://httpbin.org/redirect/5')
data = dump.dump_all(resp)
print(data.decode('utf-8'))
Source: https://toolbelt.readthedocs.org/en/latest/dumputils.html
You can simply install it by typing:
pip install requests_toolbelt
For Each row As DataGridViewRow In yourDGV.SelectedRows
yourDGV.Rows.Remove(row)
Next
This will delete all rows that had been selected.
$1, $2, etc will contain the value of captures from the last successful match - it's important to check whether the match succeeded before accessing them, i.e.
if ( $var =~ m/( )/ ) { # use $1 etc... }
An example of the problem - $1 contains 'Quick' in both print statements below:
#!/usr/bin/perl
'Quick brown fox' =~ m{ ( quick ) }ix;
print "Found: $1\n";
'Lazy dog' =~ m{ ( quick ) }ix;
print "Found: $1\n";
This works too.
const $el = $(".myclass");
const className = $el[0].className;
you have to create an entry inside res/menu,
override onCreateOptionsMenu
and inflate it
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.yourentry, menu);
return true;
}
an entry for the menu could be:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_cart"
android:icon="@drawable/cart"
android:orderInCategory="100"
android:showAsAction="always"/>
</menu>
This is how I did it:
curl -v \
--key ./admin-key.pem \
--cert ./admin.pem \
https://xxxx/api/v1/
You can also add underscore.js to your project and will be able to do it in one line:
_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})
I spent a day on this and here's how I got it fixed:
I found that global value of build.pg was set to: /opt/local/lib/postgresql91/bin/pg_config
and that was not where postgres was installed.
I fixed it with replacing the value of build.pg to:
bundle config build.pg --with-pg-config=/usr/local/Cellar/postgresql/9.4.4/bin/pg_config
which is where my postgresql installation is.
You're pretty close:
var myTag = $(':selected', element).attr("myTag");
my solution works as follows:
import UIKit
class LoginViewController: UIViewController, NSURLConnectionDataDelegate {
@IBOutlet var usernameTextField: UITextField
@IBOutlet var passwordTextField: UITextField
@IBAction func login(sender: AnyObject) {
var url = NSURL(string: "YOUR_URL")
var request = NSURLRequest(URL: url)
var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)
}
func connection(connection:NSURLConnection!, willSendRequestForAuthenticationChallenge challenge:NSURLAuthenticationChallenge!) {
if challenge.previousFailureCount > 1 {
} else {
let creds = NSURLCredential(user: usernameTextField.text, password: passwordTextField.text, persistence: NSURLCredentialPersistence.None)
challenge.sender.useCredential(creds, forAuthenticationChallenge: challenge)
}
}
func connection(connection:NSURLConnection!, didReceiveResponse response: NSURLResponse) {
let status = (response as NSHTTPURLResponse).statusCode
println("status code is \(status)")
// 200? Yeah authentication was successful
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
You can use this class as the implementation of a ViewController. Connect your fields to the IBOutlet annotated vars and your Button to the IBAction annotated function.
Explanation: In function login you create your request with NSURL, NSURLRequest and NSURLConnection. Essential here is the delegate which references to this class (self). For receiving the delegates calls you need to
I will try to explain the results of all the commands you tried.
scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)
First of all, List
is a type alias to scala.collection.immutable.List
(defined in Predef.scala).
Using the List companion object is more straightforward way to instantiate a List
. Ex: List(1.0,5.5)
scala> l
res0: List[Double] = List(1.0, 5.5)
scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)
:::
returns a list resulting from the concatenation of the given list prefix and this list
The original List is NOT modified
scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)
List(l)
is a List[List[Double]]
Definitely not what you want.
:+
returns a new list consisting of all elements of this list followed by elem.
The type is List[Any]
because it is the common superclass between List[Double]
and Double
scala> l
res3: List[Double] = List(1.0, 5.5)
l is left unmodified because no method on immutable.List
modified the List.
Add gesture on that view. Add an image into that view, and then it would be detecting a gesture on the image too. You could try with the delegate method of the touch event. Then in that case it also might be detecting.
In the Native Postman app there is "Cookie manager", so that is not a problem at all,
But in the Postman extension for Chrome there is not
So the solution is just in the installing native Postman
First, which version of ubuntu are you using, it might be easiest to just upgrade to one that has it.
Next, enable backports (system menue, adminstration, software sources), and search for in in synaptic.
Last, look for a ppa for it.
TypeScript is a strict syntactical superset of JavaScript hence
Another reason could be because the filepath is empty where you are trying to write which is why it can't find it. just another reason why this error occurs.
give the td padding
You can join your array using the following:
string.Join(",", Client);
Then you can output anyway you want. You can change the comma to what ever you want, a space, a pipe, or whatever.
For SQL Server 2012, or later, an easier solution is to use FORMAT ()
Documentation.
EG:
SELECT Format(1234567.8, '##,##0')
Results in: 1,234,568
If you want to set it to LF as default, you can go to File->Preferences->Settings and under user settings you can paste this line in below your other user settings.
"files.eol": "\n"
For example.
"git.confirmSync": false,
"window.zoomLevel": -1,
"workbench.activityBar.visible": true,
"editor.wordWrap": true,
"workbench.iconTheme": "vscode-icons",
"window.menuBarVisibility": "default",
"vsicons.projectDetection.autoReload": true,
"files.eol": "\n"
The Project Facet->Java should match whatever you have in the pom.xml for the maven-compiler-plugin artifact source and target.This is perfect.But if you donot have it here then you can also fix it by matching Java compiler version in Porject-Facets from the setting: Eclispe->Preferences->Java->Compiler
There is no documented LEFT() function in Oracle. Find the full set here.
Probably what you have is a user-defined function. You can check that easily enough by querying the data dictionary:
select * from all_objects
where object_name = 'LEFT'
But there is the question of why the stored procedure works and the query doesn't. One possible solution is that the stored procedure is owned by another schema, which also owns the LEFT() function. They have granted rights on the procedure but not its dependencies. This works because stored procedures run with DEFINER privileges by default, so you run the stored procedure as if you were its owner.
If this is so then the data dictionary query I listed above won't help you: it will only return rows for objects you have rights on. In which case you will need to run the query as the stored procedure's owner or connect as a user with the rights to query DBA_OBJECTS instead.
Yes you can view XML
files of an Android APK
file. There is a tool for this: android-apktool
It is a tool for reverse engineering 3rd party, closed, binary Android apps
How to do this on your Windows System:
Now copy the APK
file also in that directory and run the following command in your command prompt:
apktool d HelloWorld.apk ./HelloWorld
This will create a directory "HelloWorld
" in your current directory. Inside it you can find the AndroidManifest.xml
file in decrypted format, and you can also find other XML
files inside the "HelloWorld/res/layout"
directory.
Here HelloWorld.apk
is your Android APK file.
See the below screen shot for more information:
** Used table to align the radio and text in one line
<div >_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td><strong>Do you want to add new server ?</strong></td>_x000D_
<td><input type="radio" name="addServer" id="serverYes" value="1"></td>_x000D_
<td>Yes</td>_x000D_
<td><input type="radio" name="addServer" id="serverNo" value="1"></td>_x000D_
<td>No</td>_x000D_
_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>
_x000D_
**
For Python 3
Remove the rb
argument and use either r
or don't pass argument (default read mode
).
with open( <path-to-file>, 'r' ) as theFile:
reader = csv.DictReader(theFile)
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
print(line)
For Python 2
import csv
with open( <path-to-file>, "rb" ) as theFile:
reader = csv.DictReader( theFile )
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
Python has a powerful built-in CSV handler. In fact, most things are already built in to the standard library.
I to was experiencing the same problem and the only thing I was able to do to make it work was to go this route:
drop user admin@localhost;
flush privileges;
create user admin@localhost identified by 'admins_password'
This allowed me to recreate my username and enter a password for the user name.
A small tweak to Glennular Extension method, so you could use the extension on other things than just ENUM's;
using System;
using System.ComponentModel;
namespace Extensions {
public static class T_Extensions {
/// <summary>
/// Gets the Description Attribute Value
/// </summary>
/// <typeparam name="T">Entity Type</typeparam>
/// <param name="val">Variable</param>
/// <returns>The value of the Description Attribute or an Empty String</returns>
public static string Description<T>(this T t) {
DescriptionAttribute[] attributes = (DescriptionAttribute[])t.GetType().GetField(t.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : string.Empty;
}
}
}
Or Using Linq
using System;
using System.ComponentModel;
using System.Linq;
namespace Extensions {
public static class T_Extensions {
public static string Description<T>(this T t) =>
((DescriptionAttribute[])t
?.GetType()
?.GetField(t?.ToString())
?.GetCustomAttributes(typeof(DescriptionAttribute), false))
?.Select(a => a?.Description)
?.FirstOrDefault()
?? string.Empty;
}
}
static variables are specific to a class . Constructors initialize attributes ESPECIALY for an instance.
You can either use a regular tuple
interface IReqularDemo: [number, string];
or if optional parameters support is needed
interface IOptionalDemo: [value1: number, value2?: string]
I think you're looking for the intersect function
array array_intersect ( array $array1 , array $array2 [, array $ ... ] )
array_intersect()
returns an array containing all values of array1 that are
present in all the arguments. Note that keys are preserved.
I took the suggestions here and created a view which can wrap a UILabel and will size it and set the number of lines so that it is top aligned. Simply put a UILabel as a subview:
@interface TopAlignedLabelContainer : UIView
{
}
@end
@implementation TopAlignedLabelContainer
- (void)layoutSubviews
{
CGRect bounds = self.bounds;
for (UILabel *label in [self subviews])
{
if ([label isKindOfClass:[UILabel class]])
{
CGSize fontSize = [label.text sizeWithFont:label.font];
CGSize textSize = [label.text sizeWithFont:label.font
constrainedToSize:bounds.size
lineBreakMode:label.lineBreakMode];
label.numberOfLines = textSize.height / fontSize.height;
label.frame = CGRectMake(0, 0, textSize.width,
fontSize.height * label.numberOfLines);
}
}
}
@end
Try using this:-
mkdir -p dir;
NOTE:- This will also create any intermediate directories that don't exist; for instance,
Check out mkdir -p
or try this:-
if [[ ! -e $dir ]]; then
mkdir $dir
elif [[ ! -d $dir ]]; then
echo "$Message" 1>&2
fi
First of all, I think it's usually \r\n
, second of all, those are not the same on all systems. That will only work on windows. It's kind-of annoying trying to figure out how to replace new lines because different systems treat them differently (see here). You might have better luck with just \n
.
If Android Studio shows you the path /Users/<name>/Library/Android/sdk
but you can not find it in your folder, just right-click and select "Show View Option". There you will be able to select "Show Library Folder"; select it and you can access the SDK.
To list all the virtual environments (if using the anaconda distribution):
conda info --envs
Hope my answer helps someone...
Your original attempt to span both tables creates an implicit JOIN. This is frowned upon by most experienced SQL programmers because it separates the tables to be combined with the condition of how.
The UNION
is a good solution for the tables as they are, but there should be no reason they can't be put into the one table with decent indexing. I've seen adding the correct index to a large table increase query speed by three orders of magnitude.
Make a connection and open it.
con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=<database_name>)));User Id =<userid>; Password =<password>");
con.Open();
Write the select query:
string sql = "select * from Pending_Tasks";
Create a command object:
OracleCommand cmd = new OracleCommand(sql, con);
Execute the command and put the result in a object to read it.
OracleDataReader r = cmd.ExecuteReader();
now start reading from it.
while (read.Read())
{
CustID.Text = (read["Customer_ID"].ToString());
CustName.Text = (read["Customer_Name"].ToString());
Add1.Text = (read["Address_1"].ToString());
Add2.Text = (read["Address_2"].ToString());
PostBox.Text = (read["Postcode"].ToString());
PassBox.Text = (read["Password"].ToString());
DatBox.Text = (read["Data_Important"].ToString());
LanNumb.Text = (read["Landline"].ToString());
MobNumber.Text = (read["Mobile"].ToString());
FaultRep.Text = (read["Fault_Report"].ToString());
}
read.Close();
Add this too using Oracle.ManagedDataAccess.Client;
Very easy with responsive voice. Just include the js and voila!
<script src='https://code.responsivevoice.org/responsivevoice.js'></script>
<input onclick="responsiveVoice.speak('This is the text you want to speak');" type='button' value=' Play' />
Download and install Eclipse, and you're good to go.
http://www.eclipse.org/downloads/
Apple provides its own version of Java, so make sure it's up-to-date.
http://developer.apple.com/java/download/
Eclipse is an integrated development environment. It has many features, but the ones that are relevant for you at this stage is:
As you gain more experience, you'll start to appreciate the rest of its rich set of features.
Flexbox spec editor here.
This is an encouraged use of flexbox, but there are a few things you should tweak for best behavior.
Don't use prefixes. Unprefixed flexbox is well-supported across most browsers. Always start with unprefixed, and only add prefixes if necessary to support it.
Since your header and footer aren't meant to flex, they should both have flex: none;
set on them. Right now you have a similar behavior due to some overlapping effects, but you shouldn't rely on that unless you want to accidentally confuse yourself later. (Default is flex:0 1 auto
, so they start at their auto height and can shrink but not grow, but they're also overflow:visible
by default, which triggers their default min-height:auto
to prevent them from shrinking at all. If you ever set an overflow
on them, the behavior of min-height:auto
changes (switching to zero rather than min-content) and they'll suddenly get squished by the extra-tall <article>
element.)
You can simplify the <article>
flex
too - just set flex: 1;
and you'll be good to go. Try to stick with the common values in https://drafts.csswg.org/css-flexbox/#flex-common unless you have a good reason to do something more complicated - they're easier to read and cover most of the behaviors you'll want to invoke.
Knockout.js validation is handy but it is not robust. You always have to create server side validation replica. In your case (as you use knockout.js) you are sending JSON data to server and back asynchronously, so you can make user think that he sees client side validation, but in fact it would be asynchronous server side validation.
Take a look at example here upida.cloudapp.net:8080/org.upida.example.knockout/order/create?clientId=1 This is a "Create Order" link. Try to click "save", and play with products. This example is done using upida library (there are spring mvc version and asp.net mvc of this library) from codeplex.
When you have two docker images "already" created and you want to put two containers to communicate with one-another.
For that, you can conveniently run each container with its own --name and use the --link flag to enable communication between them. You do not get this during docker build though.
When you are in a scenario like myself, and it is your
docker build -t "centos7/someApp" someApp/
That breaks when you try to
curl http://172.17.0.1:localPort/fileIWouldLikeToDownload.tar.gz > dump.tar.gz
and you get stuck on "curl/wget" returning no "route to host".
The reason is security that is set in place by docker that by default is banning communication from a container towards the host or other containers running on your host. This was quite surprising to me, I must say, you would expect the echosystem of docker machines running on a local machine just flawlessly can access each other without too much hurdle.
The explanation for this is described in detail in the following documentation.
http://www.dedoimedo.com/computers/docker-networking.html
Two quick workarounds are given that help you get moving by lowering down the network security.
The simplest alternative is just to turn the firewall off - or allow all. This means running the necessary command, which could be systemctl stop firewalld, iptables -F or equivalent.
Hope this information helps you.
There's a difference in invoking the click
event (does not do the redirect), and navigating to the href
location.
Navigate:
window.location = $('#myanchor').attr('href');
Open in new tab or window:
window.open($('#myanchor').attr('href'));
invoke click event (call the javascript):
$('#myanchor').click();
the Object.prototype.toString
is a good way, but its performance is the worst.
http://jsperf.com/check-js-type
Use typeof
to solve some basic problem(String, Number, Boolean...) and use Object.prototype.toString
to solve something complex(like Array, Date, RegExp).
and this is my solution:
var type = (function(global) {
var cache = {};
return function(obj) {
var key;
return obj === null ? 'null' // null
: obj === global ? 'global' // window in browser or global in nodejs
: (key = typeof obj) !== 'object' ? key // basic: string, boolean, number, undefined, function
: obj.nodeType ? 'object' // DOM element
: cache[key = ({}).toString.call(obj)] // cached. date, regexp, error, object, array, math
|| (cache[key] = key.slice(8, -1).toLowerCase()); // get XXXX from [object XXXX], and cache it
};
}(this));
use as:
type(function(){}); // -> "function"
type([1, 2, 3]); // -> "array"
type(new Date()); // -> "date"
type({}); // -> "object"
MacOS just paste in the Terminal:
keytool -list -v -alias androiddebugkey -keystore ~/.android/debug.keystore -storepass android -keypass android
Hi here is how i did it in one Project :
@Html.DropDownListFor(model => model.MyOption,
new List<SelectListItem> {
new SelectListItem { Value = "0" , Text = "Option A" },
new SelectListItem { Value = "1" , Text = "Option B" },
new SelectListItem { Value = "2" , Text = "Option C" }
},
new { @class="myselect"})
I hope it helps Somebody. Thanks
It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:
When location matches the last part of the directive’s value: it is better to use the root directive instead:
which would yield:
server {
listen 8080;
server_name www.mysite.com mysite.com;
error_log /home/www-data/logs/nginx_www.error.log;
error_page 404 /404.html;
location /public/doc/ {
autoindex on;
root /home/www-data/mysite;
}
location = /404.html {
root /home/www-data/mysite/static/html;
}
}
if(isset($_POST['form1']))
{
try
{
$user=$_POST['username'];
$pass=$_POST['password'];
$email=$_POST['email'];
$roll=$_POST['roll'];
$class=$_POST['class'];
if(empty($user)) throw new Exception("Name can not empty");
if(empty($pass)) throw new Exception("Password can not empty");
if(empty($email)) throw new Exception("Email can not empty");
if(empty($roll)) throw new Exception("Roll can not empty");
if(empty($class)) throw new Exception("Class can not empty");
$statement=$db->prepare("show table status like 'tbl_std_info'");
$statement->execute();
$result=$statement->fetchAll();
foreach($result as $row)
$new_id=$row[10];
$up_file=$_FILES["image"]["name"];
$file_basename=substr($up_file, 0 , strripos($up_file, "."));
$file_ext=substr($up_file, strripos($up_file, "."));
$f1="$new_id".$file_ext;
if(($file_ext!=".png")&&($file_ext!=".jpg")&&($file_ext!=".jpeg")&&($file_ext!=".gif"))
{
throw new Exception("Only jpg, png, jpeg or gif Logo are allow to upload / Empty Logo Field");
}
move_uploaded_file($_FILES["image"]["tmp_name"],"../std_photo/".$f1);
$statement=$db->prepare("insert into tbl_std_info (username,image,password,email,roll,class) value (?,?,?,?,?,?)");
$statement->execute(array($user,$f1,$pass,$email,$roll,$class));
$success="Registration Successfully Completed";
echo $success;
}
catch(Exception $e)
{
$msg=$e->getMessage();
}
}
The best solution for you would depend on what you require from your fake enum
.
Simple enum:
If you need the enum
as only a list of names identifying different items, the solution by Mark Harrison (above) is great:
Pen, Pencil, Eraser = range(0, 3)
Using a range
also allows you to set any starting value:
Pen, Pencil, Eraser = range(9, 12)
In addition to the above, if you also require that the items belong to a container of some sort, then embed them in a class:
class Stationery:
Pen, Pencil, Eraser = range(0, 3)
To use the enum item, you would now need to use the container name and the item name:
stype = Stationery.Pen
Complex enum:
For long lists of enum or more complicated uses of enum, these solutions will not suffice. You could look to the recipe by Will Ware for Simulating Enumerations in Python published in the Python Cookbook. An online version of that is available here.
More info:
PEP 354: Enumerations in Python has the interesting details of a proposal for enum in Python and why it was rejected.
"How can this be improved?"
Well, you need to look at every method in your class and consider what would happen if another thread was simultaneously calling that method or any other method. For example, you put a lock in the Remove method, but not in the Add method. What happens if one thread Adds at the same time as another thread Removes? Bad things.
Also consider that a method can return a second object that provides access to the first object's internal data - for example, GetEnumerator. Imagine one thread is going through that enumerator, another thread is modifying the list at the same time. Not good.
A good rule of thumb is to make this simpler to get right by cutting down the number of methods in the class to the absolute minimum.
In particular, don't inherit another container class, because you will expose all of that class's methods, providing a way for the caller to corrupt the internal data, or to see partially complete changes to the data (just as bad, because the data appears corrupted at that moment). Hide all the details and be completely ruthless about how you allow access to them.
I'd strongly advise you to use off-the-shelf solutions - get a book about threading or use 3rd party library. Otherwise, given what you're attempting, you're going to be debugging your code for a long time.
Also, wouldn't it make more sense for Remove to return an item (say, the one that was added first, as it's a queue), rather than the caller choosing a specific item? And when the queue is empty, perhaps Remove should also block.
Update: Marc's answer actually implements all these suggestions! :) But I'll leave this here as it may be helpful to understand why his version is such an improvement.
In most cases, optimistic locking is more efficient and offers higher performance. When choosing between pessimistic and optimistic locking, consider the following:
Pessimistic locking is useful if there are a lot of updates and relatively high chances of users trying to update data at the same time. For example, if each operation can update a large number of records at a time (the bank might add interest earnings to every account at the end of each month), and two applications are running such operations at the same time, they will have conflicts.
Pessimistic locking is also more appropriate in applications that contain small tables that are frequently updated. In the case of these so-called hotspots, conflicts are so probable that optimistic locking wastes effort in rolling back conflicting transactions.
Optimistic locking is useful if the possibility for conflicts is very low – there are many records but relatively few users, or very few updates and mostly read-type operations.
WITHOUT USING JAVASCRIPT
Just add #t=[(start_time), (end_time)]
to the end of your media URL. The only setback (if you want to see it that way) is you'll need to know how long your video is to indicate the end time.
Example:
<video>
<source src="splash.mp4#t=10,20" type="video/mp4">
</video>
Notes: Not supported in IE
From Java 1.5 it's always a good Idea to consider java.util.concurrent package. They are the state of the art locking mechanism in java right now. The synchronize mechanism is more heavyweight that the java.util.concurrent classes.
The example would look something like this:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Sample {
private final Lock lock = new ReentrantLock();
private String message = null;
public void newmsg(String msg) {
lock.lock();
try {
message = msg;
} finally {
lock.unlock();
}
}
public String getmsg() {
lock.lock();
try {
String temp = message;
message = null;
return temp;
} finally {
lock.unlock();
}
}
}
This is because the content of
<p myHighlight>Highlight me!</p>
has not been rendered when the constructor of the HighlightDirective is called so there is no content yet.
If you implement the AfterContentInit hook you will get the element and its content.
import { Directive, ElementRef, AfterContentInit } from '@angular/core';
@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
constructor(private el: ElementRef) {
//el.nativeElement.style.backgroundColor = 'yellow';
}
ngAfterContentInit(){
//you can get to the element content here
//this.el.nativeElement
}
}
Once check this.
Open your .plist file and check for "Bundle OS Type code" key. If that is not there, add a row and give that key and check the type it should be a string. And give "APPL" as value.
Clean the project and go for Archive.
I hope it will work for you.
use js:
$(document).ready(function ()
{ $(".class-span").each(function(i){
var len=$(this).text().trim().length;
if(len>100)
{
$(this).text($(this).text().substr(0,100)+'...');
}
});
});
In addition you can add
profile.setPreference("browser.download.panel.shown",false);
To remove the downloaded file list that gets shown by default and covers up part of the web page.
My total settings are:
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.merge(capabillities);
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setPreference("browser.download.folderList", 4);
profile.setPreference("browser.download.dir", TestConstants.downloadDir.getAbsolutePath());
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/csv, application/ris, text/csv, data:image/png, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);
profile.setPreference("browser.download.useDownloadDir", true);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.closeWhenDone", true);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("browser.download.panel.shown",false);
dc.setCapability(FirefoxDriver.PROFILE, profile);
this.driver = new FirefoxDriver(dc);
Create vector, push_back element, then modify it as so:
struct subject {
string name;
int marks;
int credits;
};
int main() {
vector<subject> sub;
//Push back new subject created with default constructor.
sub.push_back(subject());
//Vector now has 1 element @ index 0, so modify it.
sub[0].name = "english";
//Add a new element if you want another:
sub.push_back(subject());
//Modify its name and marks.
sub[1].name = "math";
sub[1].marks = 90;
}
You cant access a vector with [#] until an element exists in the vector at that index. This example populates the [#] and then modifies it afterward.
This code will work perfectly in WPF. You can use it in either page load or in button click.
string screenWidth =System.Windows.SystemParameters.PrimaryScreenWidth.ToString();
string screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight.ToString();
txtResolution.Text ="Resolution : "+screenWidth + " X " + screenHeight;
I recently ran into the similar issue with react-native application. iPhone OS version was 13.1 I uninstalled the application and tried to install the app and noticed both location and notification permissions were not prompted.
On checking the settings, I could see my application was enabled for location(from previous installation) however there was no corresponding entry against the notification Tried uninstalling and rebooting without setting the time, it didn't work. Btw, I also tried to download the Appstore app, still same behavior.
The issue was resolved only after setting the device time.
Here's what worked for me:
select visits, activations, simulations, simulations/activations
as sims_per_visit, activations/visits*100
as adoption_rate, simulations/activations*100
as completion_rate, duration/60
as minutes, m1 as month, Wk1 as week, Yr1 as year
from
(
(select count(*) as visits, year(stamp) as Yr1, week(stamp) as Wk1, month(stamp)
as m1 from sessions group by week(stamp), year(stamp)) as t3
join
(select count(*) as activations, year(stamp) as Yr2, week(stamp) as Wk2,
month(stamp) as m2 from sessions where activated='1' group by week(stamp),
year(stamp)) as t4
join
(select count(*) as simulations, year(stamp) as Yr3 , week(stamp) as Wk3,
month(stamp) as m3 from sessions where simulations>'0' group by week(stamp),
year(stamp)) as t5
join
(select avg(duration) as duration, year(stamp) as Yr4 , week(stamp) as Wk4,
month(stamp) as m4 from sessions where activated='1' group by week(stamp),
year(stamp)) as t6
)
where Yr1=Yr2 and Wk1=Wk2 and Wk1=Wk3 and Yr1=Yr3 and Yr1=Yr4 and Wk1=Wk4
I used joins, not unions (I needed different columns for each query, a join puts it all in the same column) and I dropped the quotation marks (compared to what Liam was doing) because they were giving me errors.
Thanks! I couldn't have pulled that off without this page! PS: Sorry I don't know how you're getting your statements formatted with colors. etc.
Not exactly direct answer, but strongly related:
In case the resources are in a different file - for example ResourceDictionary.xaml
You can simply add x:Class
to it:
<ResourceDictionary x:Class="Namespace.NewClassName"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<ds:MyCollection x:Key="myKey" x:Name="myName" />
</ResourceDictionary>
And then use it in code behind:
var res = new Namespace.NewClassName();
var col = res["myKey"];
On the user action:
// you have to do something along the lines of
myJFrame.getContentPane().removeAll()
myJFrame.getContentPane().invalidate()
myJFrame.getContentPane().add(newContentPanel)
myJFrame.getContentPane().revalidate()
Then you can resize your wndow as needed.
It has to do with the version of python that you use. Basically it adopts the C behavior: if you divide two integers, the results will be rounded down to an integer. Also keep in mind that Python does the operations from left to right, which plays a role when you typecast.
Example: Since this is a question that always pops in my head when I am doing arithmetic operations (should I convert to float and which number), an example from that aspect is presented:
>>> a = 1/2/3/4/5/4/3
>>> a
0
When we divide integers, not surprisingly it gets lower rounded.
>>> a = 1/2/3/4/5/4/float(3)
>>> a
0.0
If we typecast the last integer to float, we will still get zero, since by the time our number gets divided by the float has already become 0 because of the integer division.
>>> a = 1/2/3/float(4)/5/4/3
>>> a
0.0
Same scenario as above but shifting the float typecast a little closer to the left side.
>>> a = float(1)/2/3/4/5/4/3
>>> a
0.0006944444444444445
Finally, when we typecast the first integer to float, the result is the desired one, since beginning from the first division, i.e. the leftmost one, we use floats.
Extra 1: If you are trying to answer that to improve arithmetic evaluation, you should check this
Extra 2: Please be careful of the following scenario:
>>> a = float(1/2/3/4/5/4/3)
>>> a
0.0
Git stash clear will clear complete stash,
cmd: git stash clear
If you want to delete a particular stash with a stash index, you can use the drop.
cmd: git stash drop 4
(4 is stash id or stash index)
Since Java 1.5 you can use the String.format
method. For example, to do the same thing as your example:
String format = String.format("%0%d", digits);
String result = String.format(format, num);
return result;
In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:
%% --> %
0 --> 0
%d --> <value of digits>
d --> d
So if digits is equal to 5, the format string becomes %05d
which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format
for more information on the conversion specifiers.
Here is my library to do that: https://github.com/Mikhus/jsurl
var u = new Url;
u.query.param='value'; // adds or replaces the param
alert(u)