Alternatively,
<style type="text/css">
#example {
display: block;
width: 30px;
height: 10px;
background: url(../images/example.png) no-repeat;
text-indent: -9999px;
}
</style>
<a href="http://www.example.com" id="example">See an example!</a>
More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.
This is my solution with prepared statements and stored procedure is returning several rows not only one value.
<?php
require 'config.php';
header('Content-type:application/json');
$connection->set_charset('utf8');
$mIds = $_GET['ids'];
$stmt = $connection->prepare("CALL sp_takes_string_returns_table(?)");
$stmt->bind_param("s", $mIds);
$stmt->execute();
$result = $stmt->get_result();
$response = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($response);
$stmt->close();
$connection->close();
One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get
public class PageViewModel : IHandle<SomeMessage>
{
...
public async void Handle(SomeMessage message)
{
ShowLoadingAnimation();
// makes UI very laggy, but still not dead
await this.contentLoader.LoadContentAsync();
HideLoadingAnimation();
}
}
public class ContentLoader
{
public async Task LoadContentAsync()
{
var tasks = new List<Task>();
tasks.Add(DoCpuBoundWorkAsync());
tasks.Add(DoIoBoundWorkAsync());
tasks.Add(DoCpuBoundWorkAsync());
tasks.Add(DoSomeOtherWorkAsync());
await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.
require 'date'
current_time = DateTime.now
current_time.strftime "%d/%m/%Y %H:%M"
# => "14/09/2011 17:02"
current_time.next_month.strftime "%d/%m/%Y %H:%M"
# => "14/10/2011 17:02"
Use Java 8's removeIf(),
To remove safely,
letters.removeIf(x -> !x.equals("A"));
These two need to go together for it to work. Been scratching my head for a while.
numberView.textAlignment = View.TEXT_ALIGNMENT_CENTER
numberView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
"Case" can return single value only, but you can use complex type:
create type foo as (a int, b text);
select (case 1 when 1 then (1,'qq')::foo else (2,'ww')::foo end).*;
I've been stumped by this too. The "Download" button is to the far right, but you also need to be in the top folder in order to download what you're seeing. Go up as high as you can to the parent/root folder and then look for the download button.
where are you trying to return the value? to console in dev tools is better for debugging
<script type = 'text/javascript'>
var ask = confirm('".$message."');
function answer(){
if(ask==false){
return false;
} else {
return true;
}
}
console.log("ask : ", ask);
console.log("answer : ", answer());
</script>
You can use following code snippet
((ch.qos.logback.classic.Logger)LoggerFactory.getLogger(packageName)).setLevel(ch.qos.logback.classic.Level.toLevel(logLevel));
The problem is that salesAmount is being set to a string. If you enter the variable in the python interpreter and hit enter, you'll see the value entered surrounded by quotes. For example, if you entered 56.95 you'd see:
>>> sales_amount = raw_input("[Insert sale amount]: ")
[Insert sale amount]: 56.95
>>> sales_amount
'56.95'
You'll want to convert the string into a float before multiplying it by sales tax. I'll leave that for you to figure out. Good luck!
the best way to import .py files is by way of __init__.py
. the simplest thing to do, is to create an empty file named __init__.py
in the same directory that your.py file is located.
this post by Mike Grouchy is a great explanation of __init__.py
and its use for making, importing, and setting up python packages.
Do the following change to the jquery.validationengine-en.js
file and update the dd/mm/yyyy inline validation by including leap year:
"date": {
// Check if date is valid by leap year
"func": function (field) {
//var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
var pattern = new RegExp(/^(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.](\d{4})$/);
var match = pattern.exec(field.val());
if (match == null)
return false;
//var year = match[1];
//var month = match[2]*1;
//var day = match[3]*1;
var year = match[3];
var month = match[2]*1;
var day = match[1]*1;
var date = new Date(year, month - 1, day); // because months starts from 0.
return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
},
"alertText": "* Invalid date, must be in DD-MM-YYYY format"
To view a list of all images on your Docker host, run:
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
apache_snapshot latest 13037686eac3 22 seconds ago 249MB
ubuntu latest 00fd29ccc6f1 3 weeks ago 111MB
Now you can run the Docker image as a container in interactive mode:
$ docker run -it apache_snapshot /bin/bash
OR if you don't have any images locally,Search Docker Hub for an image to download:
$ docker search ubuntu
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
ubuntu Ubuntu is a Debian... 6759 [OK]
dorowu/ubuntu-desktop-lxde-vnc Ubuntu with openss... 141 [OK]
rastasheep/ubuntu-sshd Dockerized SSH ser... 114 [OK]
ansible/ubuntu14.04-ansible Ubuntu 14.04 LTS w... 88 [OK]
ubuntu-upstart Upstart is an even... 80 [OK]
Pull the Docker image from a repository with the docker pull command:
$ docker pull ubuntu
Run the Docker image as a container:
$ docker run -it ubuntu /bin/bash
Where is your problem??
For the stored procedure, just create:
CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
AS
SELECT * -- I would *strongly* recommend specifying the columns EXPLICITLY
FROM dbo.Emp
WHERE ID = @EmpID
That's all there is.
From your ASP.NET application, just create a SqlConnection
and a SqlCommand
(don't forget to set the CommandType = CommandType.StoredProcedure
)
DataTable tblEmployees = new DataTable();
using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
_cmd.Parameters["@EmpID"].Value = 42;
SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
_dap.Fill(tblEmployees);
}
YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();
and then fill e.g. a DataTable
with that data and bind it to e.g. a GridView.
:
is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]
[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"
Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.
Works with tuples and strings, too.
Firstly, the Instagram API endpoint "tags" required OAuth authentication.
You can query results for a particular hashtag (snowy in this case) using the following url
It is rate limited to 5000 (X-Ratelimit-Limit:5000) per hour
https://api.instagram.com/v1/tags/snowy/media/recent
Sample response
{
"pagination": {
"next_max_tag_id": "1370433362010",
"deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
"next_max_id": "1370433362010",
"next_min_id": "1370443976800",
"min_tag_id": "1370443976800",
"next_url": "https://api.instagram.com/v1/tags/snowy/media/recent?access_token=40480112.1fb234f.4866541998fd4656a2e2e2beaa5c4bb1&max_tag_id=1370433362010"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"tags": [
"snowy"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": null,
"created_time": "1370418343",
"link": "http://instagram.com/p/aK1yrGRi3l/",
"likes": {
"count": 1,
"data": [
{
"username": "iri92lol",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"id": "404174490",
"full_name": "Iri"
}
]
},
"images": {
"low_resolution": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_7.jpg",
"width": 612,
"height": 612
}
},
"users_in_photo": [],
"caption": {
"created_time": "1370418353",
"text": "#snowy",
"from": {
"username": "iri92lol",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"id": "404174490",
"full_name": "Iri"
},
"id": "471425773832908504"
},
"user_has_liked": false,
"id": "471425689728724453_404174490",
"user": {
"username": "iri92lol",
"website": "",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"full_name": "Iri",
"bio": "",
"id": "404174490"
}
}
}
You can play around here :
You need to use "Authentication" as OAuth 2 and will be prompted to signin via Instagram. Post that you might have to reneter the "tag-name" in "Template" section.
All the pagination related data is available in the "pagination" parameter in the response and use it's "next_url" to query for the next set of result.
I was getting this error in postgresql function. I had a long SQL which I broke into multiple lines with \ for better readability. However, that was the problem. I removed all and made them in one line to fix the issue. I was using pgadmin III.
I was able to solve that problem by adding this to my controller method:
$title = 'My Title Here';
View::share('title', $title);
$this->layout->title = 'Home page'; did not work either.
Skinny – Contains ONLY the bits you literally type into your code editor, and NOTHING else.
Thin – Contains all of the above PLUS the app’s direct dependencies of your app (db drivers, utility libraries, etc).
Hollow – The inverse of Thin – Contains only the bits needed to run your app but does NOT contain the app itself. Basically a pre-packaged “app server” to which you can later deploy your app, in the same style as traditional Java EE app servers, but with important differences.
Fat/Uber – Contains the bit you literally write yourself PLUS the direct dependencies of your app PLUS the bits needed to run your app “on its own”.
Source: Article from Dzone
Reposted from: https://stackoverflow.com/a/57592130/9470346
The end of the variable name is usually signified by a space or newline. But what if we don't want a space or newline after printing the variable value? The curly braces tell the shell interpreter where the end of the variable name is.
TIME=10
# WRONG: no such variable called 'TIMEsecs'
echo "Time taken = $TIMEsecs"
# What we want is $TIME followed by "secs" with no whitespace between the two.
echo "Time taken = ${TIME}secs"
# WRONG - no such variable LATESTVERSION_src
CLASSPATH=hibernate-$LATESTVERSION_src.zip:hibernate_$LATEST_VERSION.jar
# RIGHT
CLASSPATH=hibernate-${LATESTVERSION}_src.zip:hibernate_$LATEST_VERSION.jar
(Fred's answer already states this but his example is a bit too abstract)
I think the second is "proper," but to be honest I don't think it will matter. The compiler should be smart enough to compile any of those to the exact same bytecode. I use "" myself.
This combination of properties helped for me:
display: inline-block;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: normal;
line-break: strict;
hyphens: none;
-webkit-hyphens: none;
-moz-hyphens: none;
Try this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
font: Tahoma, Geneva, sans-serif;_x000D_
font-size: 64px;_x000D_
color: white;_x000D_
text-shadow:_x000D_
/* Outline */_x000D_
-1px -1px 0 #000000,_x000D_
1px -1px 0 #000000,_x000D_
-1px 1px 0 #000000,_x000D_
1px 1px 0 #000000, _x000D_
-2px 0 0 #000000,_x000D_
2px 0 0 #000000,_x000D_
0 2px 0 #000000,_x000D_
0 -2px 0 #000000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
...and you might also want to do this too:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
font: Tahoma, Geneva, sans-serif;_x000D_
font-size: 64px;_x000D_
color: white;_x000D_
text-shadow:_x000D_
/* Outline 1 */_x000D_
-1px -1px 0 #000000,_x000D_
1px -1px 0 #000000,_x000D_
-1px 1px 0 #000000,_x000D_
1px 1px 0 #000000, _x000D_
-2px 0 0 #000000,_x000D_
2px 0 0 #000000,_x000D_
0 2px 0 #000000,_x000D_
0 -2px 0 #000000, _x000D_
/* Outline 2 */_x000D_
-2px -2px 0 #ff0000,_x000D_
2px -2px 0 #ff0000,_x000D_
-2px 2px 0 #ff0000,_x000D_
2px 2px 0 #ff0000, _x000D_
-3px 0 0 #ff0000,_x000D_
3px 0 0 #ff0000,_x000D_
0 3px 0 #ff0000,_x000D_
0 -3px 0 #ff0000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
You can do as many Outlines as you like, and there's enough scope for coming up with lots of creative ideas.
Have fun!
#include <stdio.h>
#define BLUE(string) "\x1b[34m" string "\x1b[0m"
#define RED(string) "\x1b[31m" string "\x1b[0m"
int main(void)
{
printf("this is " RED("red") "!\n");
// a somewhat more complex ...
printf("this is " BLUE("%s") "!\n","blue");
return 0;
}
reading Wikipedia:
Below are two methods that are superior to looping. Both handle a "no-find" case.
VLOOKUP
with error-handling if the variable doesn't exist (INDEX/MATCH
may be a better route than VLOOKUP
, ie if your two columns A and B were in reverse order, or were far apart)VBAs FIND
method (matching a whole string in column A given I use the xlWhole
argument)
Sub Method1()
Dim strSearch As String
Dim strOut As String
Dim bFailed As Boolean
strSearch = "trees"
On Error Resume Next
strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
If Err.Number <> 0 Then bFailed = True
On Error GoTo 0
If Not bFailed Then
MsgBox "corresponding value is " & vbNewLine & strOut
Else
MsgBox strSearch & " not found"
End If
End Sub
Sub Method2()
Dim rng1 As Range
Dim strSearch As String
strSearch = "trees"
Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
Else
MsgBox strSearch & " not found"
End If
End Sub
This is very inadvisable. But if you're not a programmer, or really prefer terrible code, you could use a substitute preg_replace
function to keep your /e
flag working temporarily.
/**
* Can be used as a stopgap shim for preg_replace() calls with /e flag.
* Is likely to fail for more complex string munging expressions. And
* very obviously won't help with local-scope variable expressions.
*
* @license: CC-BY-*.*-comment-must-be-retained
* @security: Provides `eval` support for replacement patterns. Which
* poses troubles for user-supplied input when paired with overly
* generic placeholders. This variant is only slightly stricter than
* the C implementation, but still susceptible to varexpression, quote
* breakouts and mundane exploits from unquoted capture placeholders.
* @url: https://stackoverflow.com/q/15454220
*/
function preg_replace_eval($pattern, $replacement, $subject, $limit=-1) {
# strip /e flag
$pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
# warn about most blatant misuses at least
if (preg_match('/\(\.[+*]/', $pattern)) {
trigger_error("preg_replace_eval(): regex contains (.*) or (.+) placeholders, which easily causes security issues for unconstrained/user input in the replacement expression. Transform your code to use preg_replace_callback() with a sane replacement callback!");
}
# run preg_replace with eval-callback
return preg_replace_callback(
$pattern,
function ($matches) use ($replacement) {
# substitute $1/$2/… with literals from $matches[]
$repl = preg_replace_callback(
'/(?<!\\\\)(?:[$]|\\\\)(\d+)/',
function ($m) use ($matches) {
if (!isset($matches[$m[1]])) { trigger_error("No capture group for '$m[0]' eval placeholder"); }
return addcslashes($matches[$m[1]], '\"\'\`\$\\\0'); # additionally escapes '$' and backticks
},
$replacement
);
# run the replacement expression
return eval("return $repl;");
},
$subject,
$limit
);
}
In essence, you just include that function in your codebase, and edit preg_replace
to preg_replace_eval
wherever the /e
flag was used.
Pros and cons:
preg_replace_callback
.Now this is somewhat redundant. But might help those users who are still overwhelmed
with manually restructuring their code to preg_replace_callback
. While this is effectively more time consuming, a code generator has less trouble to expand the /e
replacement string into an expression. It's a very unremarkable conversion, but likely suffices for the most prevalent examples.
To use this function, edit any broken preg_replace
call into preg_replace_eval_replacement
and run it once. This will print out the according preg_replace_callback
block to be used in its place.
/**
* Use once to generate a crude preg_replace_callback() substitution. Might often
* require additional changes in the `return …;` expression. You'll also have to
* refit the variable names for input/output obviously.
*
* >>> preg_replace_eval_replacement("/\w+/", 'strtopupper("$1")', $ignored);
*/
function preg_replace_eval_replacement($pattern, $replacement, $subjectvar="IGNORED") {
$pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
$replacement = preg_replace_callback('/[\'\"]?(?<!\\\\)(?:[$]|\\\\)(\d+)[\'\"]?/', function ($m) { return "\$m[{$m[1]}]"; }, $replacement);
$ve = "var_export";
$bt = debug_backtrace(0, 1)[0];
print "<pre><code>
#----------------------------------------------------
# replace preg_*() call in '$bt[file]' line $bt[line] with:
#----------------------------------------------------
\$OUTPUT_VAR = preg_replace_callback(
{$ve($pattern, TRUE)},
function (\$m) {
return {$replacement};
},
\$YOUR_INPUT_VARIABLE_GOES_HERE
)
#----------------------------------------------------
</code></pre>\n";
}
Take in mind that mere copy&pasting is not programming. You'll have to adapt the generated code back to your actual input/output variable names, or usage context.
$OUTPUT =
assignment would have to go if the previous preg_replace
call was used in an if
.And the replacement expression may demand more readability improvements or rework.
stripslashes()
often becomes redundant in literal expressions.use
or global
reference for/within the callback."-$1-$2"
capture references will end up syntactically broken by the plain transformation into "-$m[1]-$m[2]
.The code output is merely a starting point. And yes, this would have been more useful as an online tool. This code rewriting approach (edit, run, edit, edit) is somewhat impractical. Yet could be more approachable to those who are accustomed to task-centric coding (more steps, more uncoveries). So this alternative might curb a few more duplicate questions.
BalusC's answer is right! but I have to mention according to the user instance variable such as:
rSet.last();
total = rSet.getRow();
and then which you are missing
rSet.beforeFirst();
the remaining code is same you will get your desire result.
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367077
Problem Statement
It's possible to write LINQ to SQL that gets all rows that have either null or an empty string in a given field, but it's not possible to use string.IsNullOrEmpty to do it, even though many other string methods map to LINQ to SQL.
Proposed Solution
Allow string.IsNullOrEmpty in a LINQ to SQL where clause so that these two queries have the same result:
var fieldNullOrEmpty =
from item in db.SomeTable
where item.SomeField == null || item.SomeField.Equals(string.Empty)
select item;
var fieldNullOrEmpty2 =
from item in db.SomeTable
where string.IsNullOrEmpty(item.SomeField)
select item;
Other Reading:
1. DevArt
2. Dervalp.com
3. StackOverflow Post
For those interested in the OS X solution for apps like Intelli-J where authorizations are stored by OSX:
Much easier than having to try to decrypt a password :-)
This might not be the best approach, but if you want to rename the duplicate columns(after join), you can do so using this tiny function.
def rename_duplicate_columns(dataframe):
columns = dataframe.columns
duplicate_column_indices = list(set([columns.index(col) for col in columns if columns.count(col) == 2]))
for index in duplicate_column_indices:
columns[index] = columns[index]+'2'
dataframe = dataframe.toDF(*columns)
return dataframe
The best/easy/fast solution that you can use if it's a quick debugging, is to surround your code with catching exceptions. That's what I'm doing when I want to check something fast in production.
try {
// Page code
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
If you are using the elastic search 7.7 or above version then follow below command.
curl -H "Content-Type: application/json" -XPOST "localhost:9200/bank/_bulk? pretty&refresh" --data-binary @"/Users/waseem.khan/waseem/elastic/account.json"
On above file path is /Users/waseem.khan/waseem/elastic/account.json
.
If you are using elastic search 6.x version then you can use the below command.
curl -X POST localhost:9200/bank/_bulk?pretty&refresh --data-binary @"/Users/waseem.khan/waseem/elastic/account.json" -H 'Content-Type: application/json'
Note: Make sure in your .json file at the end you will add the one empty line otherwise you will be getting below exception.
"error" : {
"root_cause" : [
{
"type" : "illegal_argument_exception",
"reason" : "The bulk request must be terminated by a newline [\n]"
}
],
"type" : "illegal_argument_exception",
"reason" : "The bulk request must be terminated by a newline [\n]"
},
`enter code here`"status" : 400
You define the class gameObject
in both your .cpp
file and your .h
file.
That is creating a redefinition error.
You should define the class, ONCE, in ONE place.
(convention says the definition is in the .h
, and all the implementation is in the .cpp
)
Please help us understand better, what part of the error message did you have trouble with?
The first part of the error says the class has been redefined in gameObject.cpp
The second part of the error says the previous definition is in gameObject.h
.
How much clearer could the message be?
//Time compare.
private int CompareTime(string t1, string t2)
{
TimeSpan s1 = TimeSpan.Parse(t1);
TimeSpan s2 = TimeSpan.Parse(t2);
return s2.CompareTo(s1);
}
In navigateExtra we can pass only some specific name as argument otherwise it showing error like below: For Ex- Here I want to pass customer key in router navigate and I pass like this-
this.Router.navigate(['componentname'],{cuskey: {customerkey:response.key}});
but it showing some error like below:
Argument of type '{ cuskey: { customerkey: any; }; }' is not assignable to parameter of type 'NavigationExtras'.
Object literal may only specify known properties, and 'cuskey' does not exist in type 'NavigationExt## Heading ##ras'
.
Solution: we have to write like this:
this.Router.navigate(['componentname'],{state: {customerkey:response.key}});
Sometimes the array element may be very long, at that time you can create an array in this way:
set list=a
set list=%list%;b
set list=%list%;c
set list=%list%;d
Then show it:
@echo off
for %%a in (%list%) do (
echo %%a
echo/
)
IP Version 4 Only ...
Imports System.Net
Module MainLine
Sub Main()
Dim hostName As String = Dns.GetHostName
Console.WriteLine("Host Name: " & hostName & vbNewLine)
Console.WriteLine("IP Version 4 Address(es):")
For Each address In Dns.GetHostEntry(hostName).AddressList().
Where(Function(p) p.AddressFamily = Sockets.AddressFamily.InterNetwork)
Console.WriteLine(vbTab & address.ToString)
Next
Console.ReadKey()
End Sub
End Module
Another easy way is to use:
mysqladmin debug
This dumps a lot of information (including locks) to the error log.
In very simple terms (because the other answers are referring you to all the official design patterns anyway, so look at them for further details):
If you want to have a class which is monitored by other classes in the ecosystem of your program you say that you want the class to be observable. I.e. there might be some changes in its state which you would want to broadcast to the rest of the program.
Now, to do this we have to call some kind of method. We don't want the Observable class to be tightly coupled with the classes that are interested in observing it. It doesn't care who it is as long as it fulfils certain criteria. (Imagine it is a radio station, it doesn't care who is listening as long as they have an FM radio tuned on their frequency). To achieve that we use an interface, referred to as the Observer.
Therefore, the Observable class will have a list of Observers (i.e. instances implementing the Observer interface methods you might have). Whenever it wants to broadcast something, it just calls the method on all the observers, one after the other.
The last thing to close the puzzle is how will the Observable class know who is interested?
So the Observable class must offer some mechanism to allow Observers to register their interest. A method such as addObserver(Observer o)
internally adds the Observer to the list of observers, so that when something important happens, it loops through the list and calls the respective notification method of the Observer interface of each instance in the list.
It might be that in the interview they did not ask you explicitly about the java.util.Observer
and java.util.Observable
but about the generic concept. The concept is a design pattern, which Java happens to provide support for directly out of the box to help you implement it quickly when you need it. So I would suggest that you understand the concept rather than the actual methods/classes (which you can look up when you need them).
UPDATE
In response to your comment, the actual java.util.Observable
class offers the following facilities:
Maintaining a list of java.util.Observer
instances. New instances interested in being notified can be added through addObserver(Observer o)
, and removed through deleteObserver(Observer o)
.
Maintaining an internal state, specifying whether the object has changed since the last notification to the observers. This is useful because it separates the part where you say that the Observable
has changed, from the part where you notify the changes. (E.g. Its useful if you have multiple changes happening and you only want to notify at the end of the process rather than at each small step). This is done through setChanged()
. So you just call it when you changed something to the Observable
and you want the rest of the Observers
to eventually know about it.
Notifying all observers that the specific Observable
has changed state. This is done through notifyObservers()
. This checks if the object has actually changed (i.e. a call to setChanged()
was made) before proceeding with the notification. There are 2 versions, one with no arguments and one with an Object
argument, in case you want to pass some extra information with the notification. Internally what happens is that it just iterates through the list of Observer
instances and calls the update(Observable o, Object arg)
method for each of them. This tells the Observer
which was the Observable object that changed (you could be observing more than one), and the extra Object arg
to potentially carry some extra information (passed through notifyObservers()
.
In a nutshell, [[ is better because it doesn't fork another process. No brackets or a single bracket is slower than a double bracket because it forks another process.
The following will return true if the element is an input:
$("#elementId").is("input")
or you can use the following to get the name of the tag:
$("#elementId").get(0).tagName
Just create a new DWORD(32) under the Fusion key. Name the DWORD to EnableLog, and set it to value 1. Then restart IIS, refresh the page giving errors, and the assembly bind logs will show in the error message.
dirname(__DIR__,level);
dirname(__DIR__,1);
level is how many times will you go back to the folder
There's no difference in the size of the memory block allocated. calloc
just fills the memory block with physical all-zero-bits pattern. In practice it is often assumed that the objects located in the memory block allocated with calloc
have initilial value as if they were initialized with literal 0
, i.e. integers should have value of 0
, floating-point variables - value of 0.0
, pointers - the appropriate null-pointer value, and so on.
From the pedantic point of view though, calloc
(as well as memset(..., 0, ...)
) is only guaranteed to properly initialize (with zeroes) objects of type unsigned char
. Everything else is not guaranteed to be properly initialized and may contain so called trap representation, which causes undefined behavior. In other words, for any type other than unsigned char
the aforementioned all-zero-bits patterm might represent an illegal value, trap representation.
Later, in one of the Technical Corrigenda to C99 standard, the behavior was defined for all integer types (which makes sense). I.e. formally, in the current C language you can initialize only integer types with calloc
(and memset(..., 0, ...)
). Using it to initialize anything else in general case leads to undefined behavior, from the point of view of C language.
In practice, calloc
works, as we all know :), but whether you'd want to use it (considering the above) is up to you. I personally prefer to avoid it completely, use malloc
instead and perform my own initialization.
Finally, another important detail is that calloc
is required to calculate the final block size internally, by multiplying element size by number of elements. While doing that, calloc
must watch for possible arithmetic overflow. It will result in unsuccessful allocation (null pointer) if the requested block size cannot be correctly calculated. Meanwhile, your malloc
version makes no attempt to watch for overflow. It will allocate some "unpredictable" amount of memory in case overflow happens.
Use the mkdtemp()
function from the tempfile
module:
import tempfile
import shutil
dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)
I have been working with our DBA to copy an audit table with 240M rows to another database.
Using a simple select/insert created a huge tempdb file.
Using a the Import/Export wizard worked but copied 8M rows in 10min
Creating a custom SSIS package and adjusting settings copied 30M rows in 10Min
The SSIS package turned out to be the fastest and most efficent for our purposes
Earl
echo "LOAD_SETTLED LOAD_INIT 2011-01-13 03:50:01" | awk -v var="test" 'BEGIN { FS = "[ \t]+" } ; { print $1 "\t" var "\t" $3 }'
Deep copying objects in JavaScript (I think the best and the simplest)
1. Using JSON.parse(JSON.stringify(object));
var obj = {
a: 1,
b: {
c: 2
}
}
var newObj = JSON.parse(JSON.stringify(obj));
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } }
2.Using created method
function cloneObject(obj) {
var clone = {};
for(var i in obj) {
if(obj[i] != null && typeof(obj[i])=="object")
clone[i] = cloneObject(obj[i]);
else
clone[i] = obj[i];
}
return clone;
}
var obj = {
a: 1,
b: {
c: 2
}
}
var newObj = cloneObject(obj);
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } }
3. Using Lo-Dash's _.cloneDeep link lodash
var obj = {
a: 1,
b: {
c: 2
}
}
var newObj = _.cloneDeep(obj);
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } }
4. Using Object.assign() method
var obj = {
a: 1,
b: 2
}
var newObj = _.clone(obj);
obj.b = 20;
console.log(obj); // { a: 1, b: 20 }
console.log(newObj); // { a: 1, b: 2 }
BUT WRONG WHEN
var obj = {
a: 1,
b: {
c: 2
}
}
var newObj = Object.assign({}, obj);
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 20 } } --> WRONG
// Note: Properties on the prototype chain and non-enumerable properties cannot be copied.
5.Using Underscore.js _.clone link Underscore.js
var obj = {
a: 1,
b: 2
}
var newObj = _.clone(obj);
obj.b = 20;
console.log(obj); // { a: 1, b: 20 }
console.log(newObj); // { a: 1, b: 2 }
BUT WRONG WHEN
var obj = {
a: 1,
b: {
c: 2
}
}
var newObj = _.cloneDeep(obj);
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 20 } } --> WRONG
// (Create a shallow-copied clone of the provided plain object. Any nested objects or arrays will be copied by reference, not duplicated.)
JSBEN.CH Performance Benchmarking Playground 1~3 http://jsben.ch/KVQLd
You can try to cast the result of GroupBy and Take into an Enumerable first then process the rest (building on the solution provided by NinjaNye
var groupByReference = (from m in context.Measurements
.GroupBy(m => m.Reference)
.Take(numOfEntries).AsEnumerable()
.Select(g => new {Creation = g.FirstOrDefault().CreationTime,
Avg = g.Average(m => m.CreationTime.Ticks),
Items = g })
.OrderBy(x => x.Creation)
.ThenBy(x => x.Avg)
.ToList() select m);
Your sql query would look similar (depending on your input) this
SELECT TOP (3) [t1].[Reference] AS [Key]
FROM (
SELECT [t0].[Reference]
FROM [Measurements] AS [t0]
GROUP BY [t0].[Reference]
) AS [t1]
GO
-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref1'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]
GO
-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref2'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]
The top post has 'as TextView' appended on the end. You might get other compiler errors if you leave this on. The following should be fine.
val text: TextView = findViewById(R.id.android_text) as TextView
Where 'android_text' is the ID of your textView
You just need to escape the period:
a <- c("NM_020506.1","NM_020519.1","NM_001030297.2","NM_010281.2","NM_011419.3", "NM_053155.2")
gsub("\\..*","",a)
[1] "NM_020506" "NM_020519" "NM_001030297" "NM_010281" "NM_011419" "NM_053155"
DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];
for (int i = 0; i < dr_art_line_2.Rows.Count; i++)
{
QuantityInIssueUnit_value = Convert.ToInt32(dr_art_line_2.Rows[i]["columnname"]);
//Similarly for QuantityInIssueUnit_uom.
}
In package specs you can do all you mentioned but not sure about INDEX BY BINARY_INTEGER;
In package body:
initialize the table in declarations:
exch_rt exch_tbl := exch_tbl();
in order to add record to the local collection, in begin - end block you can do:
exch_rt.extend;
one_row.exch_rt_usd := 2;
one_row.exch_rt_eur := 1;
one_row.currency_cd := 'dollar';
exch_rt(1) := one_row; -- 1 - number of row in the table - you can put a variable which will be incremented inside a loop
in order to get data from this table , inside package body you can use:
select exch_rt_usd, exch_rt_eur, currency_cd from table(exch_rt)
enjoy!
P.S. sorry for a late answer :D
you can also use:
<?php
ob_start();
echo "some text";
echo "\n";
// you can also use:
?>
some text can be also written here, or maybe HTML:
<div>whatever<\div>
<?php
echo "you can basically write whatever you want";
// and then:
$long_text = ob_get_clean();
This method doesn't seem to work in my browser, and looking around indicates that the whole subject of specifying headers to a mailto
link/action is sparsely supported, but maybe this can help...
HTML:
<form id="fr1">
<input type="text" id="tb1" />
<input type="text" id="tb2" />
<input type="button" id="bt1" value="click" />
</form>
JavaScript (with jQuery):
$(document).ready(function() {
$('#bt1').click(function() {
$('#fr1').attr('action',
'mailto:[email protected]?subject=' +
$('#tb1').val() + '&body=' + $('#tb2').val());
$('#fr1').submit();
});
});
Notice what I'm doing here. The form itself has no action associated with it. And the submit button isn't really a submit
type, it's just a button
type. Using JavaScript, I'm binding to that button's click event, setting the form's action attribute, and then submitting the form.
It's working in so much as it submits the form to a mailto
action (my default mail program pops up and opens a new message to the specified address), but for me (Safari, Mail.app) it's not actually specifying the Subject or Body in the resulting message.
HTML isn't really a very good medium for doing this, as I'm sure others are pointing out while I type this. It's possible that this may work in some browsers and/or some mail clients. However, it's really not even a safe assumption anymore that users will have a fat mail client these days. I can't remember the last time I opened mine. HTML's mailto
is a bit of legacy functionality and, these days, it's really just as well that you perform the mail action on the server-side if possible.
I think you're confused because you haven't declared a TimeSpan
you've declared a TimeSpan?
which is a nullable TimeSpan
. Either remove the question mark if you don't need it to be nullable or use variable.Value.TotalHours
.
If one uses the tool Linqpad, after one connects to a target database from the connections one can get a connection string to use.
Properties
Advanced
Copy Full Connection String to Clipboard
Result: Data Source=.\jabberwocky;Integrated Security=SSPI;Initial Catalog=Rasa;app=LINQPad
Remove the app=LinqPad
depending on the drivers and other items such as Server
instead of source, you may need to adjust the driver to suit the target operation; but it gives one a launching pad.
You can also use unshift() to prepend to a list
private static final String mText = "SHOP MA" + "\n" +
+ "----------------------------" + "\n" +
+ "Pannampitiya" + newline +
+ "09-10-2012 harsha no: 001" + "\n" +
+ "No Item Qty Price Amount" + "\n" +
+ "1 Bread 1 50.00 50.00" + "\n" +
+ "____________________________" + "\n";
This should work.
Unfortunately, I believe that is already the best way (although list()
is slightly better than listFiles()
, since it doesn't construct File
objects).
You can use:
<script type="text/javascript">
function prepareFrame() {
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "http://google.com/");
ifrm.style.width = "640px";
ifrm.style.height = "480px";
document.body.appendChild(ifrm);
}
</script>
also check basics of the iFrame element
Without jQuery : DEMO
<div id="parentDiv" onclick="alert('parentDiv');">
<div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
AAA
</div>
</div>
Do the following:
Dim dataTable1 As New DataTable
dataTable1.Columns.Add("FECHA")
dataTable1.Columns.Add("TT")
dataTable1.Columns.Add("DESCRIPCION")
dataTable1.Columns.Add("No. DOC")
dataTable1.Columns.Add("DEBE")
dataTable1.Columns.Add("HABER")
dataTable1.Columns.Add("SALDO")
For Each line As String In System.IO.File.ReadAllLines(objetos.url)
dataTable1.Rows.Add(line.Split(","))
Next
For me, It was an issue with the .npmrc file. Which is present in C:\Users\myname.npmrc
Somehow the content of .npmrc file got changed. I have changed the content by comparing with my colleagues laptop. So it solved.
For reference, I am adding the content of .npmrc file too
;;;;
;npm userconfig file
;this is a simple ini-formatted file
;lines that start with semi-colons are comments.
;read `npm help config` for help on the various options
;;;;
//registry.npmjs.org/:_authToken=95632bcf-3056-4538-b57d-38426736e3a0
scope=true
@true:registry=https://registry.npmjs.org/
;;;;
;all options with default values
;;;;
;access=null
;allow-same-version=false
;always-auth=false
;also=null
;audit=true
;audit-level=low
;auth-type=legacy
;before=null
;bin-links=true
;browser=null
;ca=null
;cafile=undefined
;cache=C:\Users\myname\AppData\Roaming\npm-cache
;cache-lock-stale=60000
;cache-lock-retries=10
;cache-lock-wait=10000
;cache-max=null
;cache-min=10
;cert=null
;cidr=null
;color=true
;depth=null
;description=true
;dev=false
;dry-run=false
;editor=notepad.exe
;engine-strict=false
;force=false
;fetch-retries=2
;fetch-retry-factor=10
;fetch-retry-mintimeout=10000
;fetch-retry-maxtimeout=60000
;git=git
;git-tag-version=true
;commit-hooks=true
;global=false
;globalconfig=C:\Users\myname\AppData\Roaming\npm\etc\npmrc
;global-style=false
;group=0
;ham-it-up=false
;heading=npm
;if-present=false
;ignore-prepublish=false
;ignore-scripts=false
;init-module=C:\Users\myname\.npm-init.js
;init-author-name=
;init-author-email=
;init-author-url=
;init-version=1.0.0
;init-license=ISC
;json=false
;key=null
;legacy-bundling=false
;link=false
;local-address=undefined
;loglevel=notice
;logs-max=10
;long=false
;maxsockets=50
;message=%s
;metrics-registry=null
;node-options=null
;node-version=10.15.2
;offline=false
;onload-script=null
;only=null
;optional=true
;otp=null
;package-lock=true
;package-lock-only=false
;parseable=false
;prefer-offline=false
;prefer-online=false
;prefix=C:\Program Files\nodejs
;preid=
;production=false
;progress=true
;proxy=null
;https-proxy=null
;noproxy=null
;user-agent=npm/{npm-version} node/{node-version} {platform} {arch}
;read-only=false
;rebuild-bundle=true
;registry=https://registry.npmjs.org/
;rollback=true
;save=true
;save-bundle=false
;save-dev=false
;save-exact=false
;save-optional=false
;save-prefix=^
;save-prod=false
;scope=
;script-shell=null
;scripts-prepend-node-path=warn-only
;searchopts=
;searchexclude=null
;searchlimit=20
;searchstaleness=900
;send-metrics=false
;shell=C:\windows\system32\cmd.exe
;shrinkwrap=true
;sign-git-commit=false
;sign-git-tag=false
;sso-poll-frequency=500
;sso-type=oauth
;strict-ssl=true
;tag=latest
;tag-version-prefix=v
;timing=false
;tmp=C:\Users\myname\AppData\Local\Temp
;unicode=false
;unsafe-perm=true
;update-notifier=true
;usage=false
;user=0
;userconfig=C:\Users\myname\.npmrc
;umask=0
;version=false
;versions=false
;viewer=browser
;_exit=true
;globalignorefile=C:\Users\myname\AppData\Roaming\npm\etc\npmignore
Compatible with all SDK versions (android.permission.ACCESS_FINE_LOCATION
became dangerous
permission in Android M and requires user to manually grant it).
In Android versions below Android M ContextCompat.checkSelfPermission(...)
always returns true
if you add these permission(s) in AndroidManifest.xml
)
public void onSomeButtonClick() {
...
if (!permissionsGranted()) {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 123);
} else doLocationAccessRelatedJob();
...
}
private Boolean permissionsGranted() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
}
@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 123) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
doLocationAccessRelatedJob();
} else {
// User refused to grant permission. You can add AlertDialog here
Toast.makeText(this, "You didn't give permission to access device location", Toast.LENGTH_LONG).show();
startInstalledAppDetailsActivity();
}
}
}
private void startInstalledAppDetailsActivity() {
Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I've also seen this error in solutions where I have multiple projects (usually netTiers projects where I've updated one or more of the sub-projects to target the 4.0 framework). It can be problematic to remove. Oftentimes it can be resolved, however, by first fixing all other errors in sub-projects (eg, any missing references), individually rebuilding those sub-projects, then removing/adding back any references to those sub-projects in Visual Studio. Personally, I've had little luck resolving this error by cleaning the solution alone.
Try installing the 32 bit version of Java 6. This works for version Install4J 4.0.5. Should fire right up, or allow you to re-run the installer.
Any newer version or the 64-bit version of 6 will fail, complaining that the java.exe is damaged.
This will only return 1 row, because you're just selecting a COUNT()
. you will use mysql_num_rows()
on the $query
in this case.
If you want to get a count of each of the ID
's, add GROUP BY id
to the end of the string.
Performance-wise, don't ever ever ever use *
in your queries. If there is 100 unique fields in a table and you want to get them all, you write out all 100, not *
. This is because *
has to recalculate how many fields it has to go, every single time it grabs a field, which takes a lot more time to call.
From the documentation:
Due to limitations in JavaScript, Vue cannot detect the following changes to an array:
In my case i stumbled on this problem when migrating from Angular to VUE. Fix was quite easy, but really difficult to find:
setValue(index) {
Vue.set(this.arr, index, !this.arr[index]);
this.$forceUpdate(); // Needed to force view rerendering
}
Yes Definitely. As far as i remember From kernel version 3.9 (Not sure on the version) onwards support for the SO_REUSEPORT
was introduced. SO_RESUEPORT
allows binding to the exact same port and address, As long as the first server sets this option before binding its socket.
It works for both TCP and UDP. Refer to the link for more details: SO_REUSEPORT
Note: Accepted answer no longer holds true as per my opinion.
Override the onBackPressed()
method as per the example by codeMagic, and remove the call to super.onBackPressed();
if you do not want the default action (finishing the current activity) to be executed.
var localdata = [{''}]// Your json array
for (var j = 0; j < localdata.length; j++)
{$(localdata).each(function(index,item)
{
$('#tbl').append('<tr><td>' + item.FirstName +'</td></tr>);
}
You can use following ways to setup Spark:
Though there are various ways to build Spark from Source.
First I tried building Spark source with SBT but that requires hadoop. To avoid those issues, I used pre-built release.
Instead of Source,I downloaded Prebuilt release for hadoop 2.x version and ran it. For this you need to install Scala as prerequisite.
I have collated all steps here :
How to run Apache Spark on Windows7 in standalone mode
Hope it'll help you..!!!
Well, this question is asked many times before, and the short typical answer is: It cannot be done by pure CSS. It's in the name: Cascading Style Sheets only supports styling in cascading direction, not up.
But in most circumstances where this effect is wished, like in the given example, there still is the possibility to use these cascading characteristics to reach the desired effect. Consider this pseudo markup:
<parent>
<sibling></sibling>
<child></child>
</parent>
The trick is to give the sibling the same size and position as the parent and to style the sibling instead of the parent. This will look like the parent is styled!
Now, how to style the sibling?
When the child is hovered, the parent is too, but the sibling is not. The same goes for the sibling. This concludes in three possible CSS selector paths for styling the sibling:
parent sibling { }
parent sibling:hover { }
parent:hover sibling { }
These different paths allow for some nice possibilities. For instance, unleashing this trick on the example in the question results in this fiddle:
div {position: relative}
div:hover {background: salmon}
div p:hover {background: white}
div p {padding-bottom: 26px}
div button {position: absolute; bottom: 0}
Obviously, in most cases this trick depends on the use of absolute positioning to give the sibling the same size as the parent, ánd still let the child appear within the parent.
Sometimes it is necessary to use a more qualified selector path in order to select a specific element, as shown in this fiddle which implements the trick multiple times in a tree menu. Quite nice really.
I encountered this problem because the dataset was filtered wrongly and the resultant data frame was empty. Even the following caused the error to show:
ggplot(df, aes(x="", y = y, fill=grp))
because df
was empty.
curl -u username:password http://
curl -u username http://
From the documentation page:
-u, --user <user:password>
Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.
If you simply specify the user name, curl will prompt for a password.
The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.
When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.
When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.
To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.
If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".
If this option is used several times, the last one will be used.
http://curl.haxx.se/docs/manpage.html#-u
Note that you do not need --basic
flag as it is the default.
"saving" is something wholly different from changing paragraph content with jquery.
If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").
Judging by your question, this is a topic on which you will have to do MUCH more research.
Input page (input.html):
<form action="/saveMyParagraph.php">
<input name="pContent" type="text"></input>
</form>
Saving page (saveMyParagraph.php) and Ouput page (output.php):
I wanted a way to do this without using an extra module. First turn list to string, then append to an array:
dataset_list = ''.join(input_list)
dataset_array = []
for item in dataset_list.split(';'): # comma, or other
dataset_array.append(item)
For the people like myself, who started recently: The loaders
keyword is replaced with rules
; even though it still represents the concept of loaders. So my webpack.config.js
, for a React app, is as follows:
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');
var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module : {
rules : [
{
test : /\.jsx?/,
include : APP_DIR,
loader : 'babel-loader'
}
]
}
};
module.exports = config;
Like Google documentation:
// Assume thisActivity is the current activity
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
Sure:
var newList = list.OrderByDescending(x => x.Product.Name).ToList();
Doc: OrderByDescending(IEnumerable, Func).
In response to your comment:
var newList = list.OrderByDescending(x => x.Product.Name)
.ThenBy(x => x.Product.Price)
.ToList();
Html code
<div id="coloredBy">
Colored By Santa
</div>
javascript code
document.getElementById("coloredBy").style.color = colorCode; // red or #ffffff
I think this is very easy to use
// @HostListener('scroll', ['$event']) // for scroll events of the current element
@HostListener('window:scroll', ['$event']) // for window scroll events
onScroll(event) {
...
}
or
<div (scroll)="onScroll($event)"></div>
Try it like,
<?php
$name='your name';
echo '<table>
<tr><th>Name</th></tr>
<tr><td>'.$name.'</td></tr>
</table>';
?>
Updated
<?php
echo '<table>
<tr><th>Rst</th><th>Marks</th></tr>
<tr><td>'.$rst4.'</td><td>'.$marks4.'</td></tr>
</table>';
?>
results.show(false)
will show you the full column content.
Show method by default limit to 20, and adding a number before false
will show more rows.
You can use the ParallelForEachAsync
extension method from AsyncEnumerator NuGet Package:
using Dasync.Collections;
var bag = new ConcurrentBag<object>();
await myCollection.ParallelForEachAsync(async item =>
{
// some pre stuff
var response = await GetData(item);
bag.Add(response);
// some post stuff
}, maxDegreeOfParallelism: 10);
var count = bag.Count;
There are probably many architectural differences between myRDD.foreach(println)
and myRDD.collect().foreach(println)
(not only 'collect', but also other actions). One the differences I saw is when doing myRDD.foreach(println)
, the output will be in a random order. For ex: if my rdd is coming from a text file where each line has a number, the output will have a different order. But when I did myRDD.collect().foreach(println)
, order remains just like the text file.
The solution to the problem for me was found in the XML document for my Main Activity. Originally my toolbar was <android.support.v7.widget.Toolbar
. To resolve this I changed it to <android.widget.Toolbar
.
I do not know why this worked though. Does anyone have any insight as to why?
Easy, \n
needs to be in the string.
Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.
Please Search Google given to the world by Larry Page and Sergey Brin.
BufferedWriter out = null;
try {
FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
out = new BufferedWriter(fstream);
out.write("\nsue");
}
catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
finally {
if(out != null) {
out.close();
}
}
A slight variation on andrew.fox answer, as the string to decode might not be a correct base64 encoded string:
using System;
namespace Service.Support
{
public static class Base64
{
public static string ToBase64(this System.Text.Encoding encoding, string text)
{
if (text == null)
{
return null;
}
byte[] textAsBytes = encoding.GetBytes(text);
return Convert.ToBase64String(textAsBytes);
}
public static bool TryParseBase64(this System.Text.Encoding encoding, string encodedText, out string decodedText)
{
if (encodedText == null)
{
decodedText = null;
return false;
}
try
{
byte[] textAsBytes = Convert.FromBase64String(encodedText);
decodedText = encoding.GetString(textAsBytes);
return true;
}
catch (Exception)
{
decodedText = null;
return false;
}
}
}
}
For all those still affected by this.
I've been getting the error...
OLEDB error "The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine."
...as described by the OP, Shailesh Sahu.
I have 64bit Windows 7.
My problem is within PowerShell scripts, but is using a connection string, similar to the OP's post, so hopefully my findings can be applied to C#, PowerShell and any other language relying on the "Microsoft.ACE.OLEDB" driver.
I followed instructions on this MS forum thread: http://goo.gl/h73RmI
I first tried installing the 64bit version, then installing the 32bit version of the AccessDatabaseEngine.exe from this page http://www.microsoft.com/en-us/download/details.aspx?id=13255
But still no joy.
I then ran the code below in PowerShell (from SQL Panda's site http://goo.gl/A3Hu96)
(New-Object system.data.oledb.oledbenumerator).GetElements() | select SOURCES_NAME, SOURCES_DESCRIPTION
...which gave me this result (I've removed other data sources for brevity)...
SOURCES_NAME SOURCES_DESCRIPTION
------------ -------------------
Microsoft.ACE.OLEDB.15.0 Microsoft Office 15.0 Access Database Engine OLE DB Provider
As you can see, I have Microsoft.ACE.OLEDB.15.0 (fifteen) not Microsoft.ACE.OLEDB.12.0 (twelve)
So, I amended my connection string to 15 and it worked.
So, a quick PowerShell snippet to demonstrate how to soft-code the version...
$AceVersion = ((New-Object System.Data.OleDb.OleDbEnumerator).GetElements() | Where-Object { $_.SOURCES_NAME -like "Microsoft.ACE.OLEDB*" } | Sort-Object SOURCES_NAME -Descending | Select-Object -First 1 SOURCES_NAME).SOURCES_NAME
$connString = "Provider=$AceVersion;Data Source=`"$filepath`";Extended Properties=`"Excel 12.0 Xml;HDR=NO`";"
amended to pick the latest ACE version, if more than one
Hopefully, anyone finding this can now check to see what OLEDB version is installed and use the appropriate version number.
You could probably use a set object instead. Just add
numbers to the set. They inherently do not replicate.
Here is a proper explanation of "still reachable":
"Still reachable" are leaks assigned to global and static-local variables. Because valgrind tracks global and static variables it can exclude memory allocations that are assigned "once-and-forget". A global variable assigned an allocation once and never reassigned that allocation is typically not a "leak" in the sense that it does not grow indefinitely. It is still a leak in the strict sense, but can usually be ignored unless you are pedantic.
Local variables that are assigned allocations and not free'd are almost always leaks.
Here is an example
int foo(void)
{
static char *working_buf = NULL;
char *temp_buf;
if (!working_buf) {
working_buf = (char *) malloc(16 * 1024);
}
temp_buf = (char *) malloc(5 * 1024);
....
....
....
}
Valgrind will report working_buf as "still reachable - 16k" and temp_buf as "definitely lost - 5k".
mootools example:
var ret = JSON.decode(jsonstr);
ret.each(function(item){
alert(item.id+'_'+item.classd);
});
A very simple hack is to use the json import instead of csv. For example instead of csv.writer just do the following:
fd = codecs.open(tempfilename, 'wb', 'utf-8')
for c in whatever :
fd.write( json.dumps(c) [1:-1] ) # json dumps writes ["a",..]
fd.write('\n')
fd.close()
Basically, given the list of fields in correct order, the json formatted string is identical to a csv line except for [ and ] at the start and end respectively. And json seems to be robust to utf-8 in python 2.*
var result = (35.8 / 100) * 10000;
(Thank you jball for this change of order of operations. I didn't consider it).
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watchv=cxLG2wtE7TM"));
startActivity(intent);
Figured out a workaround: I renamed my lgpl2.1_license.txt
to lgpl2.1_license.txt.py
, and put some triple quotes around the text. Now I don't need to use the data_files
option nor to specify any absolute paths. Making it a Python module is ugly, I know, but I consider it less ugly than specifying absolute paths.
Just need to float both elements left:
.post-container{
margin: 20px 20px 0 0;
border:5px solid #333;
}
.post-thumb img {
float: left;
}
.post-content {
float: left;
}
Edit: actually, you do not need the width, just float both left
I'm surprised no one mentioned the implicit style above. My preference is to use parens to wrap the string while lining the string lines up visually. Personally I think this looks cleaner and more compact than starting the beginning of the string on a tabbed new line.
Note that these parens are not part of a method call — they're only implicit string literal concatenation.
Python 2:
def fun():
print ('{0} Here is a really '
'long sentence with {1}').format(3, 5)
Python 3 (with parens for print function):
def fun():
print(('{0} Here is a really '
'long sentence with {1}').format(3, 5))
Personally I think it's cleanest to separate concatenating the long string literal from printing it:
def fun():
s = ('{0} Here is a really '
'long sentence with {1}').format(3, 5)
print(s)
public ResponseEntity<?> ApiCall(@PathVariable(name = "id") long id) {
JSONObject resp = new JSONObject();
resp.put("status", 0);
resp.put("id", id);
return new ResponseEntity<String>(resp.toString(), HttpStatus.CREATED);
}
Take a look at jfxmessagebox (http://en.sourceforge.jp/projects/jfxmessagebox/) if you are looking for very simple dialog popups.
git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
Adding the actual content from dbf's link in order to keep the solution within stackoverflow.
It turns out that when I first installed Glassfish on my Windows system I had JDK 6 installed, and recently I had to downgrade to JDK 5 to compile some code for another project.
Apparently when Glassfish is installed it hard-codes its reference to your JDK location, so to fix this problem I ended up having to edit a file named asenv.bat. In short, I edited this file:
C:\glassfish\config\asenv.bat:
and I commented out the reference to JDK 6 and added a new reference to JDK 5, like this:
REM set AS_JAVA=C:\Program Files\Java\jdk1.6.0_04\jre/..
set AS_JAVA=C:\Program Files\Java\jdk1.5.0_16
Although the path doesn't appear to be case sensitive, I've spent hours debugging an issue around JMS Destination object not found due to my replacement path's case being incorrect.
I like to use Action in place of MethodInvoker, it is shorter and looks cleaner.
Invoke((Action)(() => {
DoSomething();
}));
// OR
Invoke((Action)delegate {
DoSomething();
});
Eg.
// Thread-safe update on a form control
public void DisplayResult(string text){
if (txtResult.InvokeRequired){
txtResult.Invoke((Action)delegate {
DisplayResult(text);
});
return;
}
txtResult.Text += text + "\r\n";
}
New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
if(-not (Test-Path -Path "HKCR:\Directory\shell\$KeyName"))
{
Try
{
New-Item -itemType String "HKCR:\Directory\shell\$KeyName" -value "Open PowerShell in this Folder" -ErrorAction Stop
New-Item -itemType String "HKCR:\Directory\shell\$KeyName\command" -value "$env:SystemRoot\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command Set-Location '%V'" -ErrorAction Stop
Write-Host "Successfully!"
}
Catch
{
Write-Error $_.Exception.Message
}
}
else
{
Write-Warning "The specified key name already exists. Type another name and try again."
}
You can download detail script from how to start PowerShell from Windows Explorer
Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.
Try as follows:
Enter the following formula:
=ISERROR(MATCH(A1,$B$1:$B$10,0))
Now select the format you want to highlight the values in col A that do not appear in col B
This will highlight any value in Col A that does not appear in Col B.
I have found a simpler answer to this problem. I simply use reverse logic. The code is in VB but it is not much different than C#.
Private Sub DataGridView1_CellContentClick(sender As Object, e As
DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim _ColumnIndex As Integer = e.ColumnIndex
Dim _RowIndex As Integer = e.RowIndex
'Uses reverse logic for current cell because checkbox checked occures
'after click
'If you know current state is False then logic dictates that a click
'event will set it true
'With these 2 check boxes only one can be true while both can be off
If DataGridView1.Rows(_RowIndex).Cells("Column2").Value = False And
DataGridView1.Rows(_RowIndex).Cells("Column3").Value = True Then
DataGridView1.Rows(_RowIndex).Cells("Column3").Value = False
End If
If DataGridView1.Rows(_RowIndex).Cells("Column3").Value = False And
DataGridView1.Rows(_RowIndex).Cells("Column2").Value = True Then
DataGridView1.Rows(_RowIndex).Cells("Column2").Value = False
End If
End Sub
One of the best things about this is no need for multiple events.
DELETE FROM blob
WHERE NOT EXISTS (
SELECT *
FROM files
WHERE id=blob.id
)
You don't specify what kind of list, but the generic List can use either the RemoveAt(index)
method, or the Remove(obj)
method:
// Remove(obj)
var item = resultList.Single(x => x.Id == 2);
resultList.Remove(item);
// RemoveAt(index)
resultList.RemoveAt(1);
This is what operator.itemgetter
is for.
>>> a = [(1, u'abc'), (2, u'def')]
>>> import operator
>>> b = map(operator.itemgetter(0), a)
>>> b
[1, 2]
The itemgetter
statement returns a function that returns the index of the element you specify. It's exactly the same as writing
>>> b = map(lambda x: x[0], a)
But I find that itemgetter
is a clearer and more explicit.
This is handy for making compact sort statements. For example,
>>> c = sorted(a, key=operator.itemgetter(0), reverse=True)
>>> c
[(2, u'def'), (1, u'abc')]
CTRL+Q Block comment/uncomment.
If you just need to resync
windows time, open an elevated command prompt and type:
w32tm /resync
C:\WINDOWS\system32>w32tm /resync
Sending resync command to local computer
The command completed successfully.
Similarly, I experienced this: Port 443 in use by "Unable to open process" with PID 6012! When starting XAMPP Control Panel v3.2.1 for the first time.
In Task Manager I found that PID 6012 was Apache web server. A copy of it was running in the background without the GUI, and when I invoked the GUI it was trying to start another copy. Killed the phantom copy and then XAMPP started up fine.
I didn't have to change any port settings.
I usually do this:
#define COLOR_STR(color) \
(RED == color ? "red" : \
(BLUE == color ? "blue" : \
(GREEN == color ? "green" : \
(YELLOW == color ? "yellow" : "unknown"))))
I've tried this in Python 3.6.9
Convert Binary to Decimal
>>> 0b101111
47
>>> int('101111',2)
47
Convert Decimal to binary
>>> bin(47)
'0b101111'
Place a 0 as the second parameter python assumes it as decimal.
>>> int('101111',0)
101111
LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.
#FACTS.
Answer by @Calvin Froedge is the shortest answer but have an issue also mentioned by @kizu. Due to inconsistent width of the div the div will flick on hover. To solve this issue add minus margin to the right on hover
#div {
overflow:hidden;
height:whatever px;
}
#div:hover {
overflow-y:scroll;
margin-right: -15px; // adjust according to scrollbar width
}
This sub will populate a Collection with all files matching the filename or pattern you pass in.
Sub GetFiles(StartFolder As String, Pattern As String, _
DoSubfolders As Boolean, ByRef colFiles As Collection)
Dim f As String, sf As String, subF As New Collection, s
If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
f = Dir(StartFolder & Pattern)
Do While Len(f) > 0
colFiles.Add StartFolder & f
f = Dir()
Loop
If DoSubfolders then
sf = Dir(StartFolder, vbDirectory)
Do While Len(sf) > 0
If sf <> "." And sf <> ".." Then
If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
subF.Add StartFolder & sf
End If
End If
sf = Dir()
Loop
For Each s In subF
GetFiles CStr(s), Pattern, True, colFiles
Next s
End If
End Sub
Usage:
Dim colFiles As New Collection
GetFiles "C:\Users\Marek\Desktop\Makro\", FName & ".xls", True, colFiles
If colFiles.Count > 0 Then
'work with found files
End If
A carriage return \r
moves the cursor to the beginning of the current line. A newline \n
causes a drop to the next line and possibly the beginning of the next line; That's the platform dependent part that Alexei notes above (on a *nix system \n
gives you both a carriage return and a newline, in windows it doesn't)
What you use depends on what you're trying to do. If I wanted to make a little spinning thing on a console I would do str = "|\r/\r-\r\\\r";
for example.
the best of the best way is:
var floatNumber = 12.5523;
var x = floatNumber - Math.Truncate(floatNumber);
result you can convert however you like
In Code:
Url.Content("~/");
MVC3 Razor Syntax:
@Url.Content("~/")
Update
Based on Manipulating the browser history, passing the empty string as second parameter of pushState
method (aka title) should be safe against future changes to the method, so it's better to use pushState
like this:
history.pushState(null, '', '/en/step2');
You can read more about that in mentioned article
Original Answer
Use history.pushState
like this:
history.pushState(null, null, '/en/step2');
Update 2 to answer Idan Dagan's comment:
Why not using
history.replaceState()
?
From MDN
history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one
That means if you use replaceState
, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState
doesn't add new entry to history) and it's not recommended and provide bad UX.
Update 3 to add window.onpopstate
So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState
, you can detect the back/forward button navigation by using window.onpopstate
like this:
window.onpopstate = function(e) {
// ...
};
As the first argument of pushState
is an object, if you passed an object
instead of null
, you can access that object in onpopstate
which is very handy, here is how:
window.onpopstate = function(e) {
if(e.state) {
console.log(e.state);
}
};
Update 4 to add Reading the current state:
When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate
event using the history.state
property like this:
console.log(history.state);
Bonus: Use following to check history.pushState
support:
if (history.pushState) {
// \o/
}
Add PresentationCore.dll
to your references. This dll url in my pc - C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\PresentationCore.dll
You can't solve it. Simply answer1.sum()==0
, and you can't perform a division by zero.
This happens because answer1
is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.
nan
is returned in this case because of the division by zero.
Now to solve your problem you could:
scipy/numpy
function that does exactly what you want! Check out @Warren Weckesser answer.Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:
exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y)))
= exp(log(exp(-x)*[1+exp(-y+x)]))
= exp(log(exp(-x) + log(1+exp(-y+x)))
= exp(-x + log(1+exp(-y+x)))
where above x=3* 1089
and y=3* 1093
. Now, the argument of this exponential is
-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06
For the denominator you could proceed similarly but obtain that log(1+exp(-z+k))
is already rounded to 0
, so that the argument of the exponential function at the denominator is simply rounded to -z=-3000
. You then have that your result is
exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x))
= exp(-266.99999385580668)
which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number 1089
in the numerator and the first number 1000
at the denominator):
exp(3*(1089-1000))=exp(-267)
For the sake of it, let's see how close we are from the solution of Wolfram alpha (link):
Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -> -266.999993855806522267194565420933791813296828742310997510523
The difference between this number and the exponent above is +1.7053025658242404e-13
, so the approximation we made at the denominator was fine.
The final result is
'exp(-266.99999385580668) = 1.1050349147204485e-116
From wolfram alpha is (link)
1.105034914720621496.. × 10^-116 # Wolfram alpha.
and again, it is safe to use numpy here too.
There is no feature in scp to filter files. For "advanced" stuff like this, I recommend using rsync:
rsync -av --exclude '*.svn' user@server:/my/dir .
(this line copy rsync from distant folder to current one)
Recent versions of rsync tunnel over an ssh connection automatically by default.
For whom can help, nowadays in 2018, youtube have options for this:
(Example in Catalan, sorry :)
Translation of the 3 arrows : "Share" - "Embed" - "Show suggested videos when the video is finished"
This is basically the same solution as @andy-wilkinson provided, but as of Spring Boot 1.0 the customize(...) method has a ConfigurableEmbeddedServletContainer parameter.
Another thing that is worth mentioning is that Tomcat only compresses content types of text/html
, text/xml
and text/plain
by default. Below is an example that supports compression of application/json
as well:
@Bean
public EmbeddedServletContainerCustomizer servletContainerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer servletContainer) {
((TomcatEmbeddedServletContainerFactory) servletContainer).addConnectorCustomizers(
new TomcatConnectorCustomizer() {
@Override
public void customize(Connector connector) {
AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler();
httpProtocol.setCompression("on");
httpProtocol.setCompressionMinSize(256);
String mimeTypes = httpProtocol.getCompressableMimeTypes();
String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE;
httpProtocol.setCompressableMimeTypes(mimeTypesWithJson);
}
}
);
}
};
}
Color picker plugin for Interface Builder
There's a nice color picker from Panic which works well with IB: http://panic.com/~wade/picker/
Xcode plugin
This one gives you a GUI for choosing colors: http://www.youtube.com/watch?v=eblRfDQM0Go
Objective-C
UIColor *color = [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1.0];
Swift
let color = UIColor(red: 160/255, green: 97/255, blue: 5/255, alpha: 1.0)
Pods and libraries
There's a nice pod named MPColorTools
: https://github.com/marzapower/MPColorTools
You could used simple strtok() function (*)From here. Note that tokens are created on delimiters
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This is a string";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
With jQuery:
jQuery('#myDivID').css("background-color");
With prototype:
$('myDivID').getStyle('backgroundColor');
With pure JS:
document.getElementById("myDivID").style.backgroundColor
There are many algorithm to count the set bits; but i think the best one is the faster one! You can see the detailed on this page:
I suggest this one:
Counting bits set in 14, 24, or 32-bit words using 64-bit instructions
unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
// option 1, for at most 14-bit values in v:
c = (v * 0x200040008001ULL & 0x111111111111111ULL) % 0xf;
// option 2, for at most 24-bit values in v:
c = ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL)
% 0x1f;
// option 3, for at most 32-bit values in v:
c = ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) %
0x1f;
c += ((v >> 24) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
This method requires a 64-bit CPU with fast modulus division to be efficient. The first option takes only 3 operations; the second option takes 10; and the third option takes 15.
editText
is a part of alertDialog
layout so Just access editText
with reference of alertDialog
EditText editText = (EditText) alertDialog.findViewById(R.id.label_field);
Update:
Because in code line dialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null));
inflater
is Null.
update your code like below, and try to understand the each code line
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);
EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
editText.setText("test label");
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
Update 2:
As you are using View object created by Inflater to update UI components else you can directly use setView(int layourResId)
method of AlertDialog.Builder
class, which is available from API 21 and onwards.
Recursively delete all children of the file ...
public static void DeleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
DeleteRecursive(child);
}
}
fileOrDirectory.delete();
}
Notice the data-type and size
>describe all_tab_columns
VIEW all_tab_columns
Name Null? Type
----------------------------------------- -------- ----------------------------
OWNER NOT NULL VARCHAR2(30)
TABLE_NAME NOT NULL VARCHAR2(30)
COLUMN_NAME NOT NULL VARCHAR2(30)
DATA_TYPE VARCHAR2(106)
DATA_TYPE_MOD VARCHAR2(3)
DATA_TYPE_OWNER VARCHAR2(30)
DATA_LENGTH NOT NULL NUMBER
DATA_PRECISION NUMBER
DATA_SCALE NUMBER
NULLABLE VARCHAR2(1)
COLUMN_ID NUMBER
DEFAULT_LENGTH NUMBER
DATA_DEFAULT LONG
NUM_DISTINCT NUMBER
LOW_VALUE RAW(32)
HIGH_VALUE RAW(32)
DENSITY NUMBER
NUM_NULLS NUMBER
NUM_BUCKETS NUMBER
LAST_ANALYZED DATE
SAMPLE_SIZE NUMBER
CHARACTER_SET_NAME VARCHAR2(44)
CHAR_COL_DECL_LENGTH NUMBER
GLOBAL_STATS VARCHAR2(3)
USER_STATS VARCHAR2(3)
AVG_COL_LEN NUMBER
CHAR_LENGTH NUMBER
CHAR_USED VARCHAR2(1)
V80_FMT_IMAGE VARCHAR2(3)
DATA_UPGRADED VARCHAR2(3)
HISTOGRAM VARCHAR2(15)
The error is caused by the "smart-quotes" (or whatever they're called). The lesson here is, "don't write your code in an 'editor' that converts quotes to smart-quotes".
names(newprice)[1]<-paste(“premium”) # error
names(newprice)[1]<-paste("premium") # works
Also, you don't need paste("premium")
(the call to paste
is redundant) and it's a good idea to put spaces around <-
to avoid confusion (e.g. x <- -10; if(x<-3) "hi" else "bye"; x
).
Well, you can use Expression.AndAlso
/ OrElse
etc to combine logical expressions, but the problem is the parameters; are you working with the same ParameterExpression
in expr1 and expr2? If so, it is easier:
var body = Expression.AndAlso(expr1.Body, expr2.Body);
var lambda = Expression.Lambda<Func<T,bool>>(body, expr1.Parameters[0]);
This also works well to negate a single operation:
static Expression<Func<T, bool>> Not<T>(
this Expression<Func<T, bool>> expr)
{
return Expression.Lambda<Func<T, bool>>(
Expression.Not(expr.Body), expr.Parameters[0]);
}
Otherwise, depending on the LINQ provider, you might be able to combine them with Invoke
:
// OrElse is very similar...
static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> left,
Expression<Func<T, bool>> right)
{
var param = Expression.Parameter(typeof(T), "x");
var body = Expression.AndAlso(
Expression.Invoke(left, param),
Expression.Invoke(right, param)
);
var lambda = Expression.Lambda<Func<T, bool>>(body, param);
return lambda;
}
Somewhere, I have got some code that re-writes an expression-tree replacing nodes to remove the need for Invoke
, but it is quite lengthy (and I can't remember where I left it...)
Generalized version that picks the simplest route:
static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
// need to detect whether they use the same
// parameter instance; if not, they need fixing
ParameterExpression param = expr1.Parameters[0];
if (ReferenceEquals(param, expr2.Parameters[0]))
{
// simple version
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(expr1.Body, expr2.Body), param);
}
// otherwise, keep expr1 "as is" and invoke expr2
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(
expr1.Body,
Expression.Invoke(expr2, param)), param);
}
Starting from .NET 4.0, there is the ExpressionVisitor
class which allows you to build expressions that are EF safe.
public static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var parameter = Expression.Parameter(typeof (T));
var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
var left = leftVisitor.Visit(expr1.Body);
var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
var right = rightVisitor.Visit(expr2.Body);
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(left, right), parameter);
}
private class ReplaceExpressionVisitor
: ExpressionVisitor
{
private readonly Expression _oldValue;
private readonly Expression _newValue;
public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
{
_oldValue = oldValue;
_newValue = newValue;
}
public override Expression Visit(Expression node)
{
if (node == _oldValue)
return _newValue;
return base.Visit(node);
}
}
git commit -m "Merged master fixed conflict."
If you don't want to use dangerouslySetInnerHTML then you can use the below mentioned solution
var Iframe = React.createClass({
render: function() {
return(
<div>
<iframe src={this.props.src} height={this.props.height} width={this.props.width}/>
</div>
)
}
});
ReactDOM.render(
<Iframe src="http://plnkr.co/" height="500" width="500"/>,
document.getElementById('example')
);
here live demo is available Demo
PHP 7.4+; with the null coalescing assignment operator
$var ??= '';
PHP 7.0+; with the null coalescing operator
$var = $var ?? '';
PHP 5.3+; with the ternary operator shorthand
isset($var) ?: $var = '';
Or for all/older versions with isset:
$var = isset($var) ? $var : '';
or
!isset($var) && $var = '';
mbaird's answer works fine. Just be aware that there seems to be a bug in Android (2.1 at least), that if you set any individual corner's radius to 0, it forces all the corners to 0 (at least that's the case with "dp" units; I didn't try it with any other units).
I needed a shape where the top corners were rounded and the bottom corners were square. I got achieved this by setting the corners I wanted to be square to a value slightly larger than 0: 0.1dp. This still renders as square corners, but it doesn't force the other corners to be 0 radius.
Comment the following lines in the web.config file.
<modules>
<!--<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>-->
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-ISAPI-2.0"/>
<!--<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptResource" verb="GET" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>-->
</handlers>
This will work.
As can be seen by the many answers here, there are lots of problems that can result in this error message when you start the MySQL service. The thing is, MySQL will generally tell you exactly what's wrong, if you just look in the appropriate log file.
For example, on Ubuntu, you should check /var/log/syslog
. Since lots of other things might also be logging to this file, you probably want to use grep
to look at mysql messages, and tail
to look at only the most recent. All together, that might look like:
grep mysql /var/log/syslog | tail -50
Don't blindly make changes to your configuration because someone else said 'This worked for my system.' Figure out what is actually wrong with your system and you'll get a better result much faster.
You have a few options:
Examples:
PS C:\> explorer
PS C:\> explorer .
PS C:\> explorer /n
PS C:\> Invoke-Item c:\path\
PS C:\> ii c:\path\
PS C:\> Invoke-Item c:\windows\explorer.exe
PS C:\> ii c:\windows\explorer.exe
PS C:\> [diagnostics.process]::start("explorer.exe")
Something to be aware of, the $_SESSION
variables are still set in the same page after calling session_destroy()
where as this is not the case when using unset($_SESSION)
or $_SESSION = array()
. Also, unset($_SESSION)
blows away the $_SESSION
superglobal so only do this when you're destroying a session.
With all that said, it's best to do like the PHP docs has it in the first example for session_destroy()
.
If you can live without tools.jar and it's only included as a chained dependency, you can exclude it from the offending project:
<dependency>
<groupId>org.apache.ambari</groupId>
<artifactId>ambari-metrics-common</artifactId>
<version>2.1.0.0</version>
<exclusions>
<exclusion>
<artifactId>jdk.tools</artifactId>
<groupId>jdk.tools</groupId>
</exclusion>
</exclusions>
</dependency>
If you are like me and Photoshop is out of your price range or just overkill for what you need. Acorn 5 is a much cheaper version of Photoshop with a lot of the same features. One of those features being a color change option. You can import all of the basic image formats including SVG and PNG. The color editing software works great and allows for basic color selection, RBG selection, hex code, or even a color grabber if you do not know the color. These color features, plus a whole lot image editing features, is definitely worth the $30. The only downside is that is currently only available on Mac.
Try /E
To get a full list of options: xcopy /?
You could convert the dataframe to be a single column with stack
(this changes the shape from 5x3 to 15x1) and then take the standard deviation:
df.stack().std() # pandas default degrees of freedom is one
Alternatively, you can use values
to convert from a pandas dataframe to a numpy array before taking the standard deviation:
df.values.std(ddof=1) # numpy default degrees of freedom is zero
Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.
A couple of additional notes:
The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).
The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.
INSERT INTO `table` ( `data` , `date` ) VALUES('".$data."',NOW()+INTERVAL 1 DAY);
Here's a flow chart that illustrates a for loop:
The equivalent C code would be
for(i = 2; i <= 6; i = i + 2) {
printf("%d\t", i + 1);
}
I found this and several other examples on one of Tenouk's C Laboratory practice worksheets.
If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists):
>>> long_word_list = 'some one long two phrase three about above along after against'
>>> long_word_set = set(long_word_list.split())
>>> set('word along river'.split()) & long_word_set
set(['along'])
I modified Mike Eshva's code,And I made it work better.You can use it with either 1frame jpg png bmp or mutil-frame gif.If you want bind a uri to the control,bind the UriSource properties or you want bind any in-memory stream that you bind the Source propertie which is a BitmapImage.
/// <summary>
/// ??????? ?????????? "???????????", ?????????????? ????????????? GIF.
/// </summary>
public class AnimatedImage : Image
{
static AnimatedImage()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(AnimatedImage), new FrameworkPropertyMetadata(typeof(AnimatedImage)));
}
#region Public properties
/// <summary>
/// ????????/????????????? ????? ???????? ?????.
/// </summary>
public int FrameIndex
{
get { return (int)GetValue(FrameIndexProperty); }
set { SetValue(FrameIndexProperty, value); }
}
/// <summary>
/// Get the BitmapFrame List.
/// </summary>
public List<BitmapFrame> Frames { get; private set; }
/// <summary>
/// Get or set the repeatBehavior of the animation when source is gif formart.This is a dependency object.
/// </summary>
public RepeatBehavior AnimationRepeatBehavior
{
get { return (RepeatBehavior)GetValue(AnimationRepeatBehaviorProperty); }
set { SetValue(AnimationRepeatBehaviorProperty, value); }
}
public new BitmapImage Source
{
get { return (BitmapImage)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
public Uri UriSource
{
get { return (Uri)GetValue(UriSourceProperty); }
set { SetValue(UriSourceProperty, value); }
}
#endregion
#region Protected interface
/// <summary>
/// Provides derived classes an opportunity to handle changes to the Source property.
/// </summary>
protected virtual void OnSourceChanged(DependencyPropertyChangedEventArgs e)
{
ClearAnimation();
BitmapImage source;
if (e.NewValue is Uri)
{
source = new BitmapImage();
source.BeginInit();
source.UriSource = e.NewValue as Uri;
source.CacheOption = BitmapCacheOption.OnLoad;
source.EndInit();
}
else if (e.NewValue is BitmapImage)
{
source = e.NewValue as BitmapImage;
}
else
{
return;
}
BitmapDecoder decoder;
if (source.StreamSource != null)
{
decoder = BitmapDecoder.Create(source.StreamSource, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);
}
else if (source.UriSource != null)
{
decoder = BitmapDecoder.Create(source.UriSource, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);
}
else
{
return;
}
if (decoder.Frames.Count == 1)
{
base.Source = decoder.Frames[0];
return;
}
this.Frames = decoder.Frames.ToList();
PrepareAnimation();
}
#endregion
#region Private properties
private Int32Animation Animation { get; set; }
private bool IsAnimationWorking { get; set; }
#endregion
#region Private methods
private void ClearAnimation()
{
if (Animation != null)
{
BeginAnimation(FrameIndexProperty, null);
}
IsAnimationWorking = false;
Animation = null;
this.Frames = null;
}
private void PrepareAnimation()
{
Animation =
new Int32Animation(
0,
this.Frames.Count - 1,
new Duration(
new TimeSpan(
0,
0,
0,
this.Frames.Count / 10,
(int)((this.Frames.Count / 10.0 - this.Frames.Count / 10) * 1000))))
{
RepeatBehavior = RepeatBehavior.Forever
};
base.Source = this.Frames[0];
BeginAnimation(FrameIndexProperty, Animation);
IsAnimationWorking = true;
}
private static void ChangingFrameIndex
(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
AnimatedImage animatedImage = dp as AnimatedImage;
if (animatedImage == null || !animatedImage.IsAnimationWorking)
{
return;
}
int frameIndex = (int)e.NewValue;
((Image)animatedImage).Source = animatedImage.Frames[frameIndex];
animatedImage.InvalidateVisual();
}
/// <summary>
/// Handles changes to the Source property.
/// </summary>
private static void OnSourceChanged
(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
((AnimatedImage)dp).OnSourceChanged(e);
}
#endregion
#region Dependency Properties
/// <summary>
/// FrameIndex Dependency Property
/// </summary>
public static readonly DependencyProperty FrameIndexProperty =
DependencyProperty.Register(
"FrameIndex",
typeof(int),
typeof(AnimatedImage),
new UIPropertyMetadata(0, ChangingFrameIndex));
/// <summary>
/// Source Dependency Property
/// </summary>
public new static readonly DependencyProperty SourceProperty =
DependencyProperty.Register(
"Source",
typeof(BitmapImage),
typeof(AnimatedImage),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.AffectsMeasure,
OnSourceChanged));
/// <summary>
/// AnimationRepeatBehavior Dependency Property
/// </summary>
public static readonly DependencyProperty AnimationRepeatBehaviorProperty =
DependencyProperty.Register(
"AnimationRepeatBehavior",
typeof(RepeatBehavior),
typeof(AnimatedImage),
new PropertyMetadata(null));
public static readonly DependencyProperty UriSourceProperty =
DependencyProperty.Register(
"UriSource",
typeof(Uri),
typeof(AnimatedImage),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.AffectsMeasure,
OnSourceChanged));
#endregion
}
This is a custom control. You need to create it in WPF App Project,and delete the Template override in style.
You are always checking for a true condition, hence your message will always show.
You should replace your if (true)
statement with if ( n == JOptionPane.YES_OPTION)
When one of the showXxxDialog methods returns an integer, the possible values are:
YES_OPTION NO_OPTION CANCEL_OPTION OK_OPTION CLOSED_OPTION
From here
Don't forget to generate a second password for your Gmail account. You will use this new password in your code. Read this:
https://support.google.com/accounts/answer/185833
Under the section "How to generate an App password" click on "App passwords", then under "Select app" choose "Mail", select your device and click "Generate". Your second password will be printed on the screen.
Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.
You can also use $inject
to add a dependency:
var MyController = function($scope, $http) {
// ...
}
MyController.$inject = ['$scope', '$http'];
To change the default property for your entire MATLAB session, see the documentation on how default properties are handled.
As an example:
set(0,'DefaultAxesFontSize',22)
x=1:200; y=sin(x);
plot(x,y)
title('hello'); xlabel('x'); ylabel('sin(x)')
To change the button background we can follow 2 methods
In the button OnClick, just add this code:
public void onClick(View v) {
if(v == buttonName) {
buttonName.setBackgroundDrawable
(getResources().getDrawable(R.drawable.imageName_selected));
}
}
2.Create button_background.xml in the drawable folder.(using xml)
res -> drawable -> button_background.xml
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true"
android:drawable="@drawable/tabs_selected" /> <!-- selected-->
<item android:state_pressed="true"
android:drawable="@drawable/tabs_selected" /> <!-- pressed-->
<item android:drawable="@drawable/tabs_selected"/>
</selector>
Now set the above file in button's background file.
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/button_background"/>
(or)
Button tiny = (Button)findViewById(R.id.tiny);
tiny.setBackgroundResource(R.drawable.abc);
2nd method is better for setting the background fd button
I'd recommend to use an array for storing all values via __set()
.
class foo {
protected $values = array();
public function __get( $key )
{
return $this->values[ $key ];
}
public function __set( $key, $value )
{
$this->values[ $key ] = $value;
}
}
This way you make sure, that you can't access the variables in another way (note that $values
is protected), to avoid collisions.
For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
While this will not (note the leading space before the opening <?
tag)
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
Also, this will not work either (the echo
will break it):
<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.
add ob_start ();
at the top and at the end add ob_end_flush();
<?php
ob_start();
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
ob_end_flush();
?>
give me an error as below:
FPDF error: Some data has already been output, can't send PDF
to over come this error:
go to fpdf.php
in that,goto line number 996
function Output($name='', $dest='')
after that make changes like this:
function Output($name='', $dest='') {
ob_clean(); //Output PDF to so
Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.
<?
while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);
?>
cheers :-)
In my case i had set:
ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);
When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off
the display_errors
option, the report was generated successfully.
The only difference i've noted is that things set in a relative layout via drag and drop automatically have their dimensions relative to other elements inferred, so when you run the app what you see is what you get. However in the constraint layout even if you drag and drop an element in the design view, when you run the app things may be shifted around. This can easily be fixed by manually setting the constraints or, a more risky move being to right click the element in the component tree, selecting the constraint layout sub menu, then clicking 'infer constraints'. Hope this helps
The semicolon character is used to terminate the SQL statement.
You can either use #
signs around a date value or use Access's (ACE, Jet, whatever) cast to DATETIME
function CDATE()
. As its name suggests, DATETIME
always includes a time element so your literal values should reflect this fact. The ISO date format is understood perfectly by the SQL engine.
Best not to use BETWEEN
for DATETIME
in Access: it's modelled using a floating point type and anyhow time is a continuum ;)
DATE
and TABLE
are reserved words in the SQL Standards, ODBC and Jet 4.0 (and probably beyond) so are best avoided for a data element names:
Your predicates suggest open-open representation of periods (where neither its start date or the end date is included in the period), which is arguably the least popular choice. It makes me wonder if you meant to use closed-open representation (where neither its start date is included but the period ends immediately prior to the end date):
SELECT my_date
FROM MyTable
WHERE my_date >= #2008-09-01 00:00:00#
AND my_date < #2010-09-01 00:00:00#;
Alternatively:
SELECT my_date
FROM MyTable
WHERE my_date >= CDate('2008-09-01 00:00:00')
AND my_date < CDate('2010-09-01 00:00:00');
Matlab and Scilab languages offer a simpler and more elegant syntax than Python for the question you're asking, so I think the best you can do is to mimic Matlab/Scilab by using the Numpy package in Python. By doing this the solution to your problem is very concise and elegant:
from numpy import *
property_a = array([545., 656., 5.4, 33.])
property_b = array([ 1.2, 1.3, 2.3, 0.3])
good_objects = [True, False, False, True]
good_indices = [0, 3]
property_asel = property_a[good_objects]
property_bsel = property_b[good_indices]
Numpy tries to mimic Matlab/Scilab but it comes at a cost: you need to declare every list with the keyword "array", something which will overload your script (this problem doesn't exist with Matlab/Scilab). Note that this solution is restricted to arrays of number, which is the case in your example.
Globals in Python are global to a module, not across all modules. (Many people are confused by this, because in, say, C, a global is the same across all implementation files unless you explicitly make it static
.)
There are different ways to solve this, depending on your actual use case.
Before even going down this path, ask yourself whether this really needs to be global. Maybe you really want a class, with f
as an instance method, rather than just a free function? Then you could do something like this:
import module1
thingy1 = module1.Thingy(a=3)
thingy1.f()
If you really do want a global, but it's just there to be used by module1
, set it in that module.
import module1
module1.a=3
module1.f()
On the other hand, if a
is shared by a whole lot of modules, put it somewhere else, and have everyone import it:
import shared_stuff
import module1
shared_stuff.a = 3
module1.f()
… and, in module1.py:
import shared_stuff
def f():
print shared_stuff.a
Don't use a from
import unless the variable is intended to be a constant. from shared_stuff import a
would create a new a
variable initialized to whatever shared_stuff.a
referred to at the time of the import, and this new a
variable would not be affected by assignments to shared_stuff.a
.
Or, in the rare case that you really do need it to be truly global everywhere, like a builtin, add it to the builtin module. The exact details differ between Python 2.x and 3.x. In 3.x, it works like this:
import builtins
import module1
builtins.a = 3
module1.f()
It does not work in jQuery 1.9. Made this plugin based on user2444818's answer.
jQuery.fn.mouseIsOver = function () {
return $(this).parent().find($(this).selector + ":hover").length > 0;
};
You'll have to use the ChannelFactory class.
Here's an example:
var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
IMyService client = null;
try
{
client = myChannelFactory.CreateChannel();
client.MyServiceOperation();
((ICommunicationObject)client).Close();
myChannelFactory.Close();
}
catch
{
(client as ICommunicationObject)?.Abort();
}
}
Related resources:
I dont know if you solved this issue, but i had same issue, if the instance is local you must check the permission to access the file, but if you are accessing from your computer to a server (remote access) you have to specify the path in the server, so that means to include the file in a server directory, that solved my case
example:
BULK INSERT Table
FROM 'C:\bulk\usuarios_prueba.csv' -- This is server path not local
WITH
(
FIELDTERMINATOR =',',
ROWTERMINATOR ='\n'
);
I hope i am understanding your question correctly, as the above comment says you need to provide more information.
In order to bind it to your view you would use property binding which is using [property]="value". Hope this helps.
<div *ngFor="let student of students">
{{student.id}}
{{student.name}}
<img [src]="student.image">
</div>
There are different ways but simplest would be to use the space-between see the example at the end
#container {
border: solid 1px #000;
display: flex;
flex-direction: row;
justify-content: space-between;
padding: 10px;
height: 50px;
}
.item {
width: 20%;
border: solid 1px #000;
text-align: center;
}
Add to application.properties
### to enable
spring.jpa.show-sql=true
### to make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true
This the simplest way to print the SQL queries though it doesn't log the parameters of prepared statements. And its is not recommended since its not such as optimized logging framework.
Add to application.properties
### logs the SQL queries
logging.level.org.hibernate.SQL=DEBUG
### logs the prepared statement parameters
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
### to make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true
By specifying above properties, logs entries will be sent to the configured log appender such as log-back or log4j.
just tested doing this and it seems to work in firefox & IE
<html>
<head>
<script type="text/javascript">
function alertFilename()
{
var thefile = document.getElementById('thefile');
alert(thefile.value);
}
</script>
</head>
<body>
<form>
<input type="file" id="thefile" onchange="alertFilename()" />
<input type="button" onclick="alertFilename()" value="alert" />
</form>
</body>
</html>
For this simple scenario, i would also recommend to use the methods that comes build-in in javascript.
You could try this :
"okay.this.is.a.string".split(".").join("")
Greetings
You can also set a default value for the variable, so you don't need to use two "[", which amounts to two processes ("[" is actually a program) instead of one.
It goes by this syntax: ${VARIABLE:-default}.
The whole thing has to be thought in such a way that this "default" value is something distinct from a "valid" value/content.
If that's not possible for some reason you probably need to add a step like checking if there's a value at all, along the lines of "if [ -z $VARIABLE ] ; then echo "the variable needs to be filled"", or "if [ ! -z $VARIABLE ] ; then #everything is fine, proceed with the rest of the script".
You can also use the update-golang script:
update-golang is a script to easily fetch and install new Golang releases with minimum system intrusion
git clone https://github.com/udhos/update-golang
cd update-golang
sudo ./update-golang.sh
You could use a lookahead:
re.split(r'[ ](?=[A-Z]+\b)', input)
This will split at every space that is followed by a string of upper-case letters which end in a word-boundary.
Note that the square brackets are only for readability and could as well be omitted.
If it is enough that the first letter of a word is upper case (so if you would want to split in front of Hello
as well) it gets even easier:
re.split(r'[ ](?=[A-Z])', input)
Now this splits at every space followed by any upper-case letter.
Very good question. The Java Language specification confirms your suggestion.
For example, the following code is correct:
short x = 3; x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3; x = (short)(x + 4.6);
This is because images
and tmp_file_upload
are only writable by root
user. For upload to work we need to make the owner of those folders same as httpd process owner OR make them globally writable (bad practice).
$ps aux | grep httpd
. The first column will be the owner typically it will be nobody
Change the owner of images
and tmp_file_upload
to be become nobody
or whatever the owner you found in step 1.
$sudo chown nobody /var/www/html/mysite/images/
$sudo chown nobody /var/www/html/mysite/tmp_file_upload/
Chmod images
and tmp_file_upload
now to be writable by the owner, if needed [Seems you already have this in place]. Mentioned in @Dmitry Teplyakov answer.
$ sudo chmod -R 0755 /var/www/html/mysite/images/
$ sudo chmod -R 0755 /var/www/html/mysite/tmp_file_upload/
For more details why this behavior happend, check the manual http://php.net/manual/en/ini.core.php#ini.upload-tmp-dir , note that it also talking about open_basedir
directive.
Here's a method that REALLY works (tested on Windows Vista) :D
frame.setExtendedState(JFrame.ICONIFIED);
frame.setExtendedState(fullscreen ? JFrame.MAXIMIZED_BOTH : JFrame.NORMAL);
The fullscreen variable indicates if you want the app to run full screen or windowed.
This does not flash the task bar, but bring the window to front reliably.
Gimp can be used to convert SVGs with primitives (e.g. rects, circles, etc.) into a single path which can be used within HTML5.
.svg
file with any tool of choice e.g. Illustrator. Don't worry if the SVG output is messy for now, Gimp will clean it upCheck both the Import Paths and Merge imported paths options
<path d="copy this text here" />
In OS X
, Netbeans 8.0
Command + ,
to open the optionsFonts & Colors
tab
you can try this
pip install opencv==2.4.9
I found a good description at Markdown Cheatsheet:
Code blocks are part of the Markdown spec, but syntax highlighting isn't.
However, many renderers -- like GitHub's and Markdown Here -- support syntax highlighting. Which languages are supported and how those language names should be written will vary from renderer to renderer. Markdown Here supports highlighting for dozens of languages (and not-really-languages, like diffs and HTTP headers); to see the complete list, and how to write the language names, see the highlight.js demo page.
Although I could not find any official GitHub documentation about using highlight.js
, I've tested lots of languages and seemed to be working
To see list of languages I used https://github.com/highlightjs/highlight.js/blob/master/SUPPORTED_LANGUAGES.md
Some shell samples:
Shell: console, shell
Bash: bash, sh, zsh
PowerShell: powershell, ps
DOS: dos, bat, cmd
Example:
```bat
cd \
copy a b
ping 192.168.0.1
```
From the Javadocs for setDisplayOrientation(int)
(Requires API level 9):
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
See the documentation on MDN about expressions and operators and statements.
this
keyword:var x = function()
vs. function x()
— Function declaration syntax(function(){
…})()
— IIFE (Immediately Invoked Function Expression)(function(){…})();
work but function(){…}();
doesn't?(function(){…})();
vs (function(){…}());
!function(){…}();
- What does the exclamation mark do before the function?+function(){…}();
- JavaScript plus sign in front of function expression!
vs leading semicolon(function(window, undefined){…}(window));
someFunction()()
— Functions which return other functions=>
— Equal sign, greater than: arrow function expression syntax|>
— Pipe, greater than: Pipeline operatorfunction*
, yield
, yield*
— Star after function
or yield
: generator functions[]
, Array()
— Square brackets: array notationIf the square brackets appear on the left side of an assignment ([a] = ...
), or inside a function's parameters, it's a destructuring assignment.
{key: value}
— Curly brackets: object literal syntax (not to be confused with blocks)If the curly brackets appear on the left side of an assignment ({ a } = ...
) or inside a function's parameters, it's a destructuring assignment.
`
…${
…}
…`
— Backticks, dollar sign with curly brackets: template literals`…${…}…`
code from the node docs mean?/
…/
— Slashes: regular expression literals$
— Dollar sign in regex replace patterns: $$
, $&
, $`
, $'
, $n
()
— Parentheses: grouping operatorobj.prop
, obj[prop]
, obj["prop"]
— Square brackets or dot: property accessors?.
, ?.[]
, ?.()
— Question mark, dot: optional chaining operator::
— Double colon: bind operatornew
operator...iter
— Three dots: spread syntax; rest parameters(...args) => {}
— What is the meaning of “…args” (three dots) in a function definition?[...iter]
— javascript es6 array feature […data, 0] “spread operator”{...props}
— Javascript Property with three dots (…)++
, --
— Double plus or minus: pre- / post-increment / -decrement operatorsdelete
operatorvoid
operator+
, -
— Plus and minus: addition or concatenation, and subtraction operators; unary sign operators|
, &
, ^
, ~
— Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators~1
equal -2
?%
— Percent sign: remainder operator&&
, ||
, !
— Double ampersand, double pipe, exclamation point: logical operators??
— Double question mark: nullish-coalescing operator**
— Double star: power operator (exponentiation)x ** 2
is equivalent to Math.pow(x, 2)
==
, ===
— Equal signs: equality operators!=
, !==
— Exclamation point and equal signs: inequality operators<<
, >>
, >>>
— Two or three angle brackets: bit shift operators?
…:
… — Question mark and colon: conditional (ternary) operator=
— Equal sign: assignment operator%=
— Percent equals: remainder assignment+=
— Plus equals: addition assignment operator&&=
, ||=
, ??=
— Double ampersand, pipe, or question mark, followed by equal sign: logical assignments||=
(or equals) in JavaScript?,
— Comma operator{
…}
— Curly brackets: blocks (not to be confused with object literal syntax)var
, let
, const
— Declaring variableslabel:
— Colon: labels#
— Hash (number sign): Private methods or private fieldsIsn't it good enough?
Public Function Contains(col As Collection, key As Variant) As Boolean
Dim obj As Variant
On Error GoTo err
Contains = True
obj = col(key)
Exit Function
err:
Contains = False
End Function
For those looking a more modern approach, you can use the fetch API
. The following example shows how to download a PDF
file. It is easily done with the following code.
fetch(url, {
body: JSON.stringify(data),
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
})
.then(response => response.blob())
.then(response => {
const blob = new Blob([response], {type: 'application/pdf'});
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = downloadUrl;
a.download = "file.pdf";
document.body.appendChild(a);
a.click();
})
I believe this approach to be much easier to understand than other XMLHttpRequest
solutions. Also, it has a similar syntax to the jQuery
approach, without the need to add any additional libraries.
Of course, I would advise checking to which browser you are developing, since this new approach won't work on IE. You can find the full browser compatibility list on the following [link][1].
Important: In this example I am sending a JSON request to a server listening on the given url
. This url
must be set, on my example I am assuming you know this part. Also, consider the headers needed for your request to work. Since I am sending a JSON, I must add the Content-Type
header and set it to application/json; charset=utf-8
, as to let the server know the type of request it will receive.
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document
As documented here: http://api.jquery.com/height/
In an Object Oriented parking lot, there will be no need for attendants because the cars will "know how to park".
Finding a usable car on the lot will be difficult; the most common models will either have all their moving parts exposed as public member variables, or they will be "fully encapsulated" cars with no windows or doors.
The parking spaces in our OO parking lot will not match the size and shape of the cars (an "impediance mismatch" between the spaces and the cars)
License tags on our lot will have a dot between each letter and digit. Handicaped parking will only be available for licenses beginning with "_", and licenses beginning with "m_" will be towed.
Probably the file is not in the path specified. '../../../' will move 3 step up to the directory in which the page is located and look for the js file in a folder named JS.
Also the language attribute is Deprecated.
See Scripts:
18.2.1 The SCRIPT element
Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.
Edit
Try changing
<script src="../../../JS/Registration.js" language="javascript" type="text/javascript" />
to
<script src="../../../JS/Registration.js" language="javascript" type="text/javascript"></script>
MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html
This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY)
and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.
Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).
Combining both answers from
Flo & rptwsthi and roetzi,
Do remember to change your layout_width=0dp/px
, else the layout_weight
behaviour will act reversely with biggest number occupied the smallest space and lowest number occupied the biggest space.
Besides, some weights combination will caused some layout cannot be shown (since it over occupied the space).
Beware of this.
I go against convention here. I don't like typedef's to base types. I think it's a useless indirection that removes value.
In Expression Language you can just use the ==
or eq
operator to compare object values. Behind the scenes they will actually use the Object#equals()
. This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).
So the particular line
<c:when test="${lang}.equals(${pageLang})">
should be written as (note that the whole expression is inside the {
and }
)
<c:when test="${lang == pageLang}">
or, equivalently
<c:when test="${lang eq pageLang}">
Both are behind the scenes roughly interpreted as
jspContext.findAttribute("lang").equals(jspContext.findAttribute("pageLang"))
If you want to compare constant String
values, then you need to quote it
<c:when test="${lang == 'en'}">
or, equivalently
<c:when test="${lang eq 'en'}">
which is behind the scenes roughly interpreted as
jspContext.findAttribute("lang").equals("en")