With nginx you can send both tokens like this (even though it's against the standard):
Authorization: Basic basic-token,Bearer bearer-token
This works as long as the basic token is first - nginx successfully forwards it to the application server.
And then you need to make sure your application can properly extract the Bearer from the above string.
Trying to uninstall Python with
brew uninstall python
will not remove the natively installed Python but rather the version installed with brew
.
You can append a class to the className
member, with a leading space.
document.getElementById('hello').className += ' new-class';
Since both pip
nor python
commands are not installed along Python in Windows, you will need to use the Windows alternative py
, which is included by default when you installed Python. Then you have the option to specify a general or specific version number after the py
command.
C:\> py -m pip install pandas %= one of Python on the system =%
C:\> py -2 -m pip install pandas %= one of Python 2 on the system =%
C:\> py -2.7 -m pip install pandas %= only for Python 2.7 =%
C:\> py -3 -m pip install pandas %= one of Python 3 on the system =%
C:\> py -3.6 -m pip install pandas %= only for Python 3.6 =%
Alternatively, in order to get pip
to work without py -m
part, you will need to add pip to the PATH environment variable.
C:\> setx PATH "%PATH%;C:\<path\to\python\folder>\Scripts"
Now you can run the following command as expected.
C:\> pip install pandas
connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
This is caused by your SSL certificate is unable to verify the host server. You can add pypi.python.org to the trusted host or specify an alternative SSL certificate. For more information, please see this post. (Thanks to Anuj Varshney for suggesting this)
C:\> py -m pip install --trusted-host pypi.python.org pip pandas
PermissionError: [WinError 5] Access is denied
This is a caused by when you don't permission to modify the Python site-package folders. You can avoid this with one of the following methods:
Run Windows Command Prompt as administrator (thanks to DataGirl's suggestion) by:
cmd.exe
in the search boxRun pip in user mode by adding --user
option when installing with pip. Which typically install the package to the local %APPDATA% Python folder.
C:\> py -m pip install --user pandas
C:\> py -m venv c:\path\to\new\venv
C:\> <path\to\the\new\venv>\Scripts\activate.bat
The main thing is that if you don't store in onSaveInstanceState()
then onRestoreInstanceState()
will not be called. This is the main difference between restoreInstanceState()
and onCreate()
. Make sure you really store something. Most likely this is your problem.
You need to allocate a block of memory and use it as an array as:
int *arr = malloc (sizeof (int) * n); /* n is the length of the array */
int i;
for (i=0; i<n; i++)
{
arr[i] = 0;
}
If you need to initialize the array with zeros you can also use the memset
function from C standard library (declared in string.h
).
memset (arr, 0, sizeof (int) * n);
Here 0
is the constant with which every locatoin of the array will be set. Note that the last argument is the number of bytes to be set the the constant. Because each location of the array stores an integer therefore we need to pass the total number of bytes as this parameter.
Also if you want to clear the array to zeros, then you may want to use calloc
instead of malloc
. calloc
will return the memory block after setting the allocated byte locations to zero.
After you have finished, free the memory block free (arr)
.
EDIT1
Note that if you want to assign a particular integer in locations of an integer array using memset
then it will be a problem. This is because memset
will interpret the array as a byte array and assign the byte you have given, to every byte of the array. So if you want to store say 11243 in each location then it will not be possible.
EDIT2
Also note why every time setting an int array to 0 with memset
may not work: Why does "memset(arr, -1, sizeof(arr)/sizeof(int))" not clear an integer array to -1? as pointed out by @Shafik Yaghmour
Try the following:
POJO pojo = mapper.convertValue(singleObject, POJO.class);
or:
List<POJO> pojos = mapper.convertValue(
listOfObjects,
new TypeReference<List<POJO>>() { });
See conversion of LinkedHashMap for more information.
Try this. It works for me:
mkdir <repos>/tags/Release1.0
svn commit <repos>/tags/Release1.0
svn copy <repos>/trunk/* <repos>/tag/Release1.0
svn commit <repos/tags/Release1.0 -m "Tagging Release1.0"
I also faced the same issue with Eclipse when I ran the clean build with Maven, but there is a simple solution for this issue. We just need to run Maven update and then build or direct run the application. I hope it will solve the problem.
SetTimeout is used to make your set of code to execute after a specified time period so for your requirements its better to use setInterval because that will call your function every time at a specified time interval.
I tried most of the solutions to this problem but couldn't get any to work.
I ran lsof -P | grep ':5432' | awk '{print $2}'
which showed the PID of the process running. However I couldn't kill it with kill -9 <pid>
.
When I ran pkill postgresql
the process finally stopped. Hope this helps.
Another way to make the parser raise the same exception is the following incorrect clause.
SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id ,
system_user_id
FROM role_members m
WHERE r.id = m.role_id
AND m.system_user_id = intIdSystemUser
)
The nested SELECT
statement in the IN
clause returns two columns, which the parser sees as operands, which is technically correct, since the id column matches values from but one column (role_id) in the result returned by the nested select statement, which is expected to return a list.
For sake of completeness, the correct syntax is as follows.
SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id
FROM role_members m
WHERE r.id = m.role_id
AND m.system_user_id = intIdSystemUser
)
The stored procedure of which this query is a portion not only parsed, but returned the expected result.
If you have a xml like below
<e:Envelope
xmlns:d = "http://www.w3.org/2001/XMLSchema"
xmlns:e = "http://schemas.xmlsoap.org/soap/envelope/"
xmlns:wn0 = "http://systinet.com/xsd/SchemaTypes/"
xmlns:i = "http://www.w3.org/2001/XMLSchema-instance">
<e:Header>
<Friends>
<friend>
<Name>Testabc</Name>
<Age>12121</Age>
<Phone>Testpqr</Phone>
</friend>
</Friends>
</e:Header>
<e:Body>
<n0:ForAnsiHeaderOperResponse xmlns:n0 = "http://systinet.com/wsdl/com/magicsoftware/ibolt/localhost/ForAnsiHeader/ForAnsiHeaderImpl#ForAnsiHeaderOper?KExqYXZhL2xhbmcvU3RyaW5nOylMamF2YS9sYW5nL1N0cmluZzs=">
<response i:type = "d:string">12--abc--pqr</response>
</n0:ForAnsiHeaderOperResponse>
</e:Body>
</e:Envelope>
and wanted to extract the below xml
<e:Header>
<Friends>
<friend>
<Name>Testabc</Name>
<Age>12121</Age>
<Phone>Testpqr</Phone>
</friend>
</Friends>
</e:Header>
The below code helps to achieve the same
public static void main(String[] args) {
File fXmlFile = new File("C://Users//abhijitb//Desktop//Test.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document;
Node result = null;
try {
document = dbf.newDocumentBuilder().parse(fXmlFile);
XPath xPath = XPathFactory.newInstance().newXPath();
String xpathStr = "//Envelope//Header";
result = (Node) xPath.evaluate(xpathStr, document, XPathConstants.NODE);
System.out.println(nodeToString(result));
} catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException
| TransformerException e) {
e.printStackTrace();
}
}
private static String nodeToString(Node node) throws TransformerException {
StringWriter buf = new StringWriter();
Transformer xform = TransformerFactory.newInstance().newTransformer();
xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
xform.transform(new DOMSource(node), new StreamResult(buf));
return (buf.toString());
}
Now if you want only the xml like below
<Friends>
<friend>
<Name>Testabc</Name>
<Age>12121</Age>
<Phone>Testpqr</Phone>
</friend>
</Friends>
You need to change the
String xpathStr = "//Envelope//Header";
to String xpathStr = "//Envelope//Header/*";
I love this
$data = str_getcsv($CsvString, "\n"); //parse the rows
foreach ($data as &$row) {
$row = str_getcsv($row, "; or , or whatever you want"); //parse the items in rows
$this->debug($row);
}
in my case I am going to get a csv through web services, so in this way I don't need to create the file. But if you need to parser with a file, it's only necessary to pass as string
Another option is to use JQuery to store the element's in-line style property, append to it, and to then update the element's style property with the new values. As follows:
function appendCSSToElement(element, CssProperties)
{
var existingCSS = $(element).attr("style");
if(existingCSS == undefined) existingCSS = "";
$.each(CssProperties, function(key,value)
{
existingCSS += " " + key + ": " + value + ";";
});
$(element).attr("style", existingCSS);
return $(element);
}
And then execute it with the new CSS attributes as an object.
appendCSSToElement("#ElementID", { "color": "white", "background-color": "green", "font-weight": "bold" });
This may not necessarily be the most efficient method (I'm open to suggestions on how to improve this. :) ), but it definitely works.
In case somebody wants to do this, using Play Framework (and using LogBack http://logback.qos.ch/), then you can configure the application-logger.xml with this line:
<logger name="org.apache.cxf" level="DEBUG"/>
For me, it did the trick ;)
You do not need the latex2exp
package to do what you wanted to do. The following code would do the trick.
ggplot(smr, aes(Fuel.Rate, Eng.Speed.Ave., color=Eng.Speed.Max.)) +
geom_point() +
labs(title=expression("Fuel Efficiency"~(alpha*Omega)),
color=expression(alpha*Omega), x=expression(Delta~price))
Also, some comments (unanswered as of this point) asked about putting an asterisk (*) after a Greek letter. expression(alpha~"*")
works, so I suggest giving it a try.
More comments asked about getting ? Price
and I find the most straightforward way to achieve that is expression(Delta~price))
. If you need to add something before the Greek letter, you can also do this:
expression(Indicative~Delta~price)
which gets you:
Sample HTML
<table class="round-corner" aria-describedby="caption">
<caption id="caption">Table with rounded corners</caption>
<thead>
<tr>
<th scope="col">Head1</th>
<th scope="col">Head2</th>
<th scope="col">Head3</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="rowgroup">tbody1 row1</td>
<td scope="rowgroup">tbody1 row1</td>
<td scope="rowgroup">tbody1 row1</td>
</tr>
<tr>
<td scope="rowgroup">tbody1 row2</td>
<td scope="rowgroup">tbody1 row2</td>
<td scope="rowgroup">tbody1 row2</td>
</tr>
</tbody>
<tbody>
<tr>
<td scope="rowgroup">tbody2 row1</td>
<td scope="rowgroup">tbody2 row1</td>
<td scope="rowgroup">tbody2 row1</td>
</tr>
<tr>
<td scope="rowgroup">tbody2 row2</td>
<td scope="rowgroup">tbody2 row2</td>
<td scope="rowgroup">tbody2 row2</td>
</tr>
</tbody>
<tbody>
<tr>
<td scope="rowgroup">tbody3 row1</td>
<td scope="rowgroup">tbody3 row1</td>
<td scope="rowgroup">tbody3 row1</td>
</tr>
<tr>
<td scope="rowgroup">tbody3 row2</td>
<td scope="rowgroup">tbody3 row2</td>
<td scope="rowgroup">tbody3 row2</td>
</tr>
</tbody>
<tfoot>
<tr>
<td scope="col">Foot</td>
<td scope="col">Foot</td>
<td scope="col">Foot</td>
</tr>
</tfoot>
</table>
SCSS, easily converted to CSS, use sassmeister.com
// General CSS
table,
th,
td {
border: 1px solid #000;
padding: 8px 12px;
}
.round-corner {
border-collapse: collapse;
border-style: hidden;
box-shadow: 0 0 0 1px #000; // fake "border"
border-radius: 4px;
// Maybe there's no THEAD after the caption?
caption + tbody {
tr:first-child {
td:first-child,
th:first-child {
border-top-left-radius: 4px;
}
td:last-child,
th:last-child {
border-top-right-radius: 4px;
border-right: none;
}
}
}
tbody:first-child {
tr:first-child {
td:first-child,
th:first-child {
border-top-left-radius: 4px;
}
td:last-child,
th:last-child {
border-top-right-radius: 4px;
border-right: none;
}
}
}
tbody:last-child {
tr:last-child {
td:first-child,
th:first-child {
border-bottom-left-radius: 4px;
}
td:last-child,
th:last-child {
border-bottom-right-radius: 4px;
border-right: none;
}
}
}
thead {
tr:last-child {
td:first-child,
th:first-child {
border-top-left-radius: 4px;
}
td:last-child,
th:last-child {
border-top-right-radius: 4px;
border-right: none;
}
}
}
tfoot {
tr:last-child {
td:first-child,
th:first-child {
border-bottom-left-radius: 4px;
}
td:last-child,
th:last-child {
border-bottom-right-radius: 4px;
border-right: none;
}
}
}
// Reset tables inside table
table tr th,
table tr td {
border-radius: 0;
}
}
From my comparisons, I find that they have the exact same execution plan. There're three scenarios:
If and when they return the same results, they have the same speed. However, we must keep in mind that they are not the same queries, and that LEFT JOIN will possibly return more results (when some ON conditions aren't met) --- this is why it's usually slower.
When the main table (first non-const one in the execution plan) has a restrictive condition (WHERE id = ?) and the corresponding ON condition is on a NULL value, the "right" table is not joined --- this is when LEFT JOIN is faster.
As discussed in Point 1, usually INNER JOIN is more restrictive and returns fewer results and is therefore faster.
Both use (the same) indices.
If you load a 32 bit version of your dll with a 64 bit JRE you could have this issue. This was my case.
Don't forget if you already have a DateTime object and are not sure if it's UTC or Local, it's easy enough to use the methods on the object directly:
DateTime convertedDate = DateTime.Parse(date);
DateTime localDate = convertedDate.ToLocalTime();
How do we adjust for the extra hour?
Unless specified .net will use the local pc settings. I'd have a read of: http://msdn.microsoft.com/en-us/library/system.globalization.daylighttime.aspx
By the looks the code might look something like:
DaylightTime daylight = TimeZone.CurrentTimeZone.GetDaylightChanges( year );
And as mentioned above double check what timezone setting your server is on. There are articles on the net for how to safely affect the changes in IIS.
Tested on Ubuntu:
sudo apt install git-extras
git-show-tree
This produces an effect similar to the 2 most upvoted answers here.
Source: http://manpages.ubuntu.com/manpages/bionic/man1/git-show-tree.1.html
Also, if you have arcanist installed (correction: Uber's fork of arcanist installed--see the bottom of this answer here for installation instructions), arc flow
shows a beautiful dependency tree of upstream dependencies (ie: which were set previously via arc flow new_branch
or manually via git branch --set-upstream-to=upstream_branch
).
git branch
you are on too!"OpenId uses OAuth to deal with authentication.
By analogy, it's like .NET relies on Windows API. You could directly call Windows API but it's so wide, complex and method arguments so vast, you could easily make mistakes/bugs/security issue.
Same with OpenId/OAuth. OpenId relies on OAuth to manage Authentication but defining a specific Token (Id_token), digital signature and particular flows.
NOTE: This answer is for SQL Server 2005. For SQL Server 2008 and later, there are much better methods as seen in the other answers.
You can use INSERT with SELECT UNION ALL:
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
...
Only for small datasets though, which should be fine for your 4 records.
try this out :)
public static HashMap HashMapFrom(String s){
HashMap base = new HashMap(); //result
int dismiss = 0; //dismiss tracker
StringBuilder tmpVal = new StringBuilder(); //each val holder
StringBuilder tmpKey = new StringBuilder(); //each key holder
for (String next:s.split("")){ //each of vale
if(dismiss==0){ //if not writing value
if (next.equals("=")) //start writing value
dismiss=1; //update tracker
else
tmpKey.append(next); //writing key
} else {
if (next.equals("{")) //if it's value so need to dismiss
dismiss++;
else if (next.equals("}")) //value closed so need to focus
dismiss--;
else if (next.equals(",") //declaration ends
&& dismiss==1) {
//by the way you have to create something to correct the type
Object ObjVal = object.valueOf(tmpVal.toString()); //correct the type of object
base.put(tmpKey.toString(),ObjVal);//declaring
tmpKey = new StringBuilder();
tmpVal = new StringBuilder();
dismiss--;
continue; //next :)
}
tmpVal.append(next); //writing value
}
}
Object objVal = object.valueOf(tmpVal.toString()); //same as here
base.put(tmpKey.toString(), objVal); //leftovers
return base;
}
examples input : "a=0,b={a=1},c={ew={qw=2}},0=a" output : {0=a,a=0,b={a=1},c={ew={qw=2}}}
Tried to get the 1200x630 image working. Facebook kept complaining that it couldn't read the image, or that it was too small (it was a jpeg image ~150Kb).
Switched to a 200x200 size image, worked perfectly.
https://developers.facebook.com/tools/debug/og/object?q=drift.team
If function1 is some sync function that you want to turn into an async one because it takes some time to complete, and you have no control over it to add a callback :
function function1 (someVariable) {
var date = Date.now ();
while (Date.now () - date < 2000); // function1 takes some time to complete
console.log (someVariable);
}
function function2 (someVariable) {
console.log (someVariable);
}
function onClick () {
window.setTimeout (() => { function1 ("This is function1"); }, 0);
window.setTimeout (() => { function2 ("This is function2"); }, 0);
console.log ("Click handled"); // To show that the function will return before both functions are executed
}
onClick ();
The output will be :
Click handled
...and after 2 seconds :
This is function 1
This is function 2
This works because calling window.setTimeout () will add a task to the JS runtine task loop, which is what an async call makes, and because the basic principle of "run-to-completion" of the JS runtime ensures that onClick () is never interrupted before it ends.
Notice that this as funny as it may the code difficult to understand...
James Padolsey created a wonderful filter that allows regex to be used for selection.
Say you have the following div
:
<div class="asdf">
Padolsey's :regex
filter can select it like so:
$("div:regex(class, .*sd.*)")
Also, check the official documentation on selectors.
:
syntax Deprecation JQuery 3.0Since jQuery.expr[':']
used in Padolsey's implementation is already deprecated and will render a syntax error in the latest version of jQuery, here is his code adapted to jQuery 3+ syntax:
jQuery.expr.pseudos.regex = jQuery.expr.createPseudo(function (expression) {
return function (elem) {
var matchParams = expression.split(','),
validLabels = /^(data|css):/,
attr = {
method: matchParams[0].match(validLabels) ?
matchParams[0].split(':')[0] : 'attr',
property: matchParams.shift().replace(validLabels, '')
},
regexFlags = 'ig',
regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
return regex.test(jQuery(elem)[attr.method](attr.property));
}
});
find . -name \*.cc -print0 -or -name \*.h -print0 | xargs -0 grep "hello"
.
Check the manual pages for find
and xargs
for details.
You could use Gson library
Type type = new TypeToken<HashMap<String, String>>() {}.getType();
new Gson().fromJson(jsonString, type);
As the React Native Documentation says, all your images sources needs to be loaded before compiling your bundle
So another way you can use dynamic images it's using a switch statement. Let's say you want to display a different avatar for a different character, you can do something like this:
class App extends Component {
state = { avatar: "" }
get avatarImage() {
switch (this.state.avatar) {
case "spiderman":
return require('./spiderman.png');
case "batman":
return require('./batman.png');
case "hulk":
return require('./hulk.png');
default:
return require('./no-image.png');
}
}
render() {
return <Image source={this.avatarImage} />
}
}
Check the snack: https://snack.expo.io/@abranhe/dynamic-images
Also, remember if your image it's online you don't have any problems, you can do:
let superhero = "spiderman";
<Image source={{ uri: `https://some-website.online/${superhero}.png` }} />
For Windows users: Try deleting files: java.exe, javaw.exe and javaws.exe from Windows\System32
My issue was the java version 1.7 installed.
There is much simpler way:
using System;
using System.Collections.Generic;
....
var caseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
I know this is not the case but if you need to keep the original freq column, you can use another tidyverse
approach together with rep
:
library(purrr)
df <- data.frame(var1 = c('a', 'b', 'c'), var2 = c('d', 'e', 'f'), freq = 1:3)
df %>%
map_df(., rep, .$freq)
#> # A tibble: 6 x 3
#> var1 var2 freq
#> <fct> <fct> <int>
#> 1 a d 1
#> 2 b e 2
#> 3 b e 2
#> 4 c f 3
#> 5 c f 3
#> 6 c f 3
Created on 2019-12-21 by the reprex package (v0.3.0)
If you think the performance of the query will be better using the index, how could you force the query to use the index?
First you would of course verify that the index gave a better result for returning the complete data set, right?
The index hint is the key here, but the more up to date way of specifying it is with the column naming method rather than the index naming method. In your case you would use:
select /*+ index(table_name (column_having_index)) */ *
from table_name
where column_having_index="some value";
In more complex cases you might ...
select /*+ index(t (t.column_having_index)) */ *
from my_owner.table_name t,
...
where t.column_having_index="some value";
With regard to composite indexes, I'm not sure that you need to specify all columns, but it seems like a good idea. See the docs here http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#autoId18 on multiple index_specs and use of index_combine for multiple indexes, and here http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#BABGFHCH for the specification of multiple columns in the index_spec.
Here you go this should give you the correct answers every time!
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
d = b**2-4*a*c # discriminant
if d < 0:
print ("This equation has no real solution")
elif d == 0:
x = (-b+math.sqrt(b**2-4*a*c))/2*a
print ("This equation has one solutions: "), x
else:
x1 = (-b+math.sqrt((b**2)-(4*(a*c))))/(2*a)
x2 = (-b-math.sqrt((b**2)-(4*(a*c))))/(2*a)
print ("This equation has two solutions: ", x1, " or", x2)
use
sudo find / -name file.txt
It's stupid (because you elevate the search) and nonsecure, but far shorter to write.
Try this one, according to http://www.regextester.com it works for js normaly.
([^{]*?)(?=\})
You have writer.close();
in your code. So bash receives EOF on its stdin
and exits. Then you get Broken pipe
when trying to read from the stdout
of the defunct bash.
Technically, the way you have it worded, neither is correct, because the SOAP method's communication isn't secure, and the REST method didn't say anything about authenticating legitimate users.
HTTPS prevents attackers from eavesdropping on the communication between two systems. It also verifies that the host system (server) is actually the host system the user intends to access.
WS-Security prevents unauthorized applications (users) from accessing the system.
If a RESTful system has a way of authenticating users and a SOAP application with WS-Security is using HTTPS, then really both are secure. It's just a different way of presenting and accessing data.
For me, I usually use DataContext
together in order to bind two-depth property such as this question.
<TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />
Or, I prefer to use ElementName
because it achieves bindings only with view controls.
<TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />
Try changing
public class LinqHelper
to
public static class LinqHelper
It may has not helped OP, but it solved my problem. This answer is to help others who have not tried the command mentioned in OP's question.
Just use npm install -g @angular/cli@latest
. It did the trick for me.
OK, I'll take a stab at this. Python passes by object reference, which is different from what you'd normally think of as "by reference" or "by value". Take this example:
def foo(x):
print x
bar = 'some value'
foo(bar)
So you're creating a string object with value 'some value' and "binding" it to a variable named bar
. In C, that would be similar to bar
being a pointer to 'some value'.
When you call foo(bar)
, you're not passing in bar
itself. You're passing in bar
's value: a pointer to 'some value'. At that point, there are two "pointers" to the same string object.
Now compare that to:
def foo(x):
x = 'another value'
print x
bar = 'some value'
foo(bar)
Here's where the difference lies. In the line:
x = 'another value'
you're not actually altering the contents of x
. In fact, that's not even possible. Instead, you're creating a new string object with value 'another value'. That assignment operator? It isn't saying "overwrite the thing x
is pointing at with the new value". It's saying "update x
to point at the new object instead". After that line, there are two string objects: 'some value' (with bar
pointing at it) and 'another value' (with x
pointing at it).
This isn't clumsy. When you understand how it works, it's a beautifully elegant, efficient system.
Slightly off-topic, but I found this too useful not to be mentioned here.
What if we would like to read the the Html text from string.xml resource and thus make it easy to localize. CDATA make this possible:
<string name="my_text">
<![CDATA[
<b>Autor:</b> Mr Nice Guy<br/>
<b>Contact:</b> [email protected]<br/>
<i>Copyright © 2011-2012 Intergalactic Spacebar Confederation </i>
]]>
</string>
From our Java code we could now utilize it like this:
TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setText(Html.fromHtml(getString(R.string.my_text)));
I did not expect this to work. But it did.
Hope it's useful to some of you!
function clearForm(){
$('#frm input[type="text"]').each(function(){
$(this).val("");
});
$('#frm input[type="radio":checked]').each(function(){
$(this).attr('checked', false);
});
}
The correct selector is: #frm input[type="radio"]:checked
not #frm input[type="radio":checked]
Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
int selectedValue = (int)cmb.SelectedValue;
ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));
}
By Definition we can drag out the differences of two:
Factory: An interface is used for creating an object, but subclass decides which class to instantiate. The creation of object is done when it is required.
Abstract Factory: Abstract Factory pattern acts as a super-factory which creates other factories. In Abstract Factory pattern an interface is responsible for creating a set of related objects, or dependent objects without specifying their concrete classes.
So, in the definitions above we can emphasize on a particular difference. that is, Factory pattern is responsible for creating objects and Abstract Factory is responsible for creating a set of related objects; obviously both through an interface.
Factory pattern:
public interface IFactory{
void VehicleType(string n);
}
public class Scooter : IFactory{
public void VehicleType(string n){
Console.WriteLine("Vehicle type: " + n);
}
}
public class Bike : IFactory{
public void VehicleType(string n) {
Console.WriteLine("Vehicle type: " + n);
}
}
public interface IVehicleFactory{
IFactory GetVehicleType(string Vehicle);
}
public class ConcreteVehicleFactory : IVehicleFactory{
public IFactory GetVehicleType(string Vehicle){
switch (Vehicle){
case "Scooter":
return new Scooter();
case "Bike":
return new Bike();
default:
return new Scooter();
}
}
class Program{
static void Main(string[] args){
IVehicleFactory factory = new ConcreteVehicleFactory();
IFactory scooter = factory.GetVehicleType("Scooter");
scooter.VehicleType("Scooter");
IFactory bike = factory.GetVehicleType("Bike");
bike.VehicleType("Bike");
Console.ReadKey();
}
}
Abstract Factory Pattern:
interface IVehicleFactory{
IBike GetBike();
IScooter GetScooter();
}
class HondaFactory : IVehicleFactory{
public IBike GetBike(){
return new FZS();
}
public IScooter GetScooter(){
return new FZscooter();
}
}
class HeroFactory: IVehicleFactory{
public IBike GetBike(){
return new Pulsur();
}
public IScooter GetScooter(){
return new PulsurScooter();
}
}
interface IBike
{
string Name();
}
interface IScooter
{
string Name();
}
class FZS:IBike{
public string Name(){
return "FZS";
}
}
class Pulsur:IBike{
public string Name(){
return "Pulsur";
}
}
class FZscooter:IScooter {
public string Name(){
return "FZscooter";
}
}
class PulsurScooter:IScooter{
public string Name(){
return "PulsurScooter";
}
}
enum MANUFACTURERS
{
HONDA,
HERO
}
class VehicleTypeCheck{
IBike bike;
IScooter scooter;
IVehicleFactory factory;
MANUFACTURERS manu;
public VehicleTypeCheck(MANUFACTURERS m){
manu = m;
}
public void CheckProducts()
{
switch (manu){
case MANUFACTURERS.HONDA:
factory = new HondaFactory();
break;
case MANUFACTURERS.HERO:
factory = new HeroFactory();
break;
}
Console.WriteLine("Bike: " + factory.GetBike().Name() + "\nScooter: " + factory.GetScooter().Name());
}
}
class Program
{
static void Main(string[] args)
{
VehicleTypeCheck chk = new VehicleTypeCheck(MANUFACTURERS.HONDA);
chk.CheckProducts();
chk= new VehicleTypeCheck(MANUFACTURERS.HERO);
chk.CheckProducts();
Console.Read();
}
}
$('input[type=checkbox]').change(function () {
alert('changed');
});
This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.
So Soumyaansh's Revo Uninstaller Pro fix worked for me :) ( After 2 days of troubleshooting other options {screams internally 😀} ).
I did run into the an issue with his method though, "Could not find a suitable SDK to target" even though I selected to install Visual Studio with custom settings and selected the SDK I wanted to install. You may need to download the Windows 10 Standalone SDK to resolved this, in order to develop UWP apps if you see this same error after reinstalling Visual Studio.
To do this
Windows 10 SDK (WINDOWS_VERSION_NUMBER_HERE)
-> Windows 10 SDK (14393) etc . . .). If there are no SDKs on your system go to step 2!Apple already includes a DEBUG
flag in debug builds, so you don't need to define your own.
You might also want to consider just redefining NSLog
to a null operation when not in DEBUG
mode, that way your code will be more portable and you can just use regular NSLog
statements:
//put this in prefix.pch
#ifndef DEBUG
#undef NSLog
#define NSLog(args, ...)
#endif
With Kotlin it is even easier:
val file = File(uri.path)
Or if you are using Kotlin extensions for Android:
val file = uri.toFile()
The first argument of strcat() needs to be able to hold enough space for the concatenated string. So allocate a buffer with enough space to receive the result.
char bigEnough[64] = "";
strcat(bigEnough, "TEXT");
strcat(bigEnough, foo);
/* and so on */
strcat() will concatenate the second argument with the first argument, and store the result in the first argument, the returned char* is simply this first argument, and only for your convenience.
You do not get a newly allocated string with the first and second argument concatenated, which I'd guess you expected based on your code.
On linux distributions (@least on Debian with plasma) the default shortcut is
Ctrl + 0
Use a UIWebView on iOS 5-.
On iOS 6+ you can use UITextView.attributedString
, see https://stackoverflow.com/a/20996085 for how.
There's also an undocumented -[UITextView setContentToHTMLString:]
method. Do not use this if you want to submit to AppStore.
If DB is SQL Server then
select Convert(varchar(10),CONVERT(date,YourDateColumn,106),103)
From your question, I think what you are trying to do is to store something (an object, a string...) to foward it then to another servlet, using RequestDispatcher(). To do this you don't need to set a paramater but an attribute using
void setAttribute(String name, Object o);
and then
Object getAttribute(String name);
You can not use input for it, you need to use textarea instead.
Use textarea with the wrap="soft"
code and optional the rest of the attributes like this:
<textarea name="text" rows="14" cols="10" wrap="soft"> </textarea>
Atributes: To limit the amount of text in it for example to "40" characters you can add the attribute maxlength="40"
like this: <textarea name="text" rows="14" cols="10" wrap="soft" maxlength="40"></textarea>
To hide the scroll the style for it. if you only use overflow:scroll;
or overflow:hidden;
or overflow:auto;
it will only take affect for one scroll bar. If you want different attributes for each scroll bar then use the attributes like this overflow:scroll; overflow-x:auto; overflow-y:hidden;
in the style area:
To make the textarea not resizable you can use the style with resize:none;
like this:
<textarea name="text" rows="14" cols="10" wrap="soft" maxlength="40" style="overflow:hidden; resize:none;></textarea>
That way you can have or example a textarea with 14 rows and 10 cols with word wrap and max character length of "40" characters that works exactly like a input text box does but with rows instead and without using input text.
NOTE: textarea works with rows unlike like input <input type="text" name="tbox" size="10"></input>
that is made to not work with rows at all.
Very easy solution with jQuery:
$('#myFormId').attr('action', 'myNewActionTarget.html');
Your form:
<form action=get_action() id="myFormId">
...
</form>
For those who were as confused as I was when reading the answers, in your package.json file, add
"type": "module"
in the upper level as show below:
{
"name": "my-app",
"version": "0.0.0",
"type": "module",
"scripts": { ...
},
...
}
"echo off" is not ignored. "echo off" means that you do not want the commands echoed, it does not say anything about the errors produced by the commands.
The lines you showed us look okay, so the problem is probably not there. So, please show us more lines. Also, please show us the exact value of INSTALL_PATH.
With Swift 3, you can choose one of the following ways to solve your problem.
sorted(by:?)
with a Movie
class that does not conform to Comparable
protocolIf your Movie
class does not conform to Comparable
protocol, you must specify in your closure the property on which you wish to use Array's sorted(by:?)
method.
Movie
class declaration:
import Foundation
class Movie: CustomStringConvertible {
let name: String
var date: Date
var description: String { return name }
init(name: String, date: Date = Date()) {
self.name = name
self.date = date
}
}
Usage:
let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")
let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted(by: { $0.name < $1.name })
// let sortedMovies = movies.sorted { $0.name < $1.name } // also works
print(sortedMovies)
/*
prints: [Avatar, Piranha II: The Spawning, Titanic]
*/
sorted(by:?)
with a Movie
class that conforms to Comparable
protocolHowever, by making your Movie
class conform to Comparable
protocol, you can have a much concise code when you want to use Array's sorted(by:?)
method.
Movie
class declaration:
import Foundation
class Movie: CustomStringConvertible, Comparable {
let name: String
var date: Date
var description: String { return name }
init(name: String, date: Date = Date()) {
self.name = name
self.date = date
}
static func ==(lhs: Movie, rhs: Movie) -> Bool {
return lhs.name == rhs.name
}
static func <(lhs: Movie, rhs: Movie) -> Bool {
return lhs.name < rhs.name
}
}
Usage:
let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")
let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted(by: { $0 < $1 })
// let sortedMovies = movies.sorted { $0 < $1 } // also works
// let sortedMovies = movies.sorted(by: <) // also works
print(sortedMovies)
/*
prints: [Avatar, Piranha II: The Spawning, Titanic]
*/
sorted()
with a Movie
class that conforms to Comparable
protocolBy making your Movie
class conform to Comparable
protocol, you can use Array's sorted()
method as an alternative to sorted(by:?)
.
Movie
class declaration:
import Foundation
class Movie: CustomStringConvertible, Comparable {
let name: String
var date: Date
var description: String { return name }
init(name: String, date: Date = Date()) {
self.name = name
self.date = date
}
static func ==(lhs: Movie, rhs: Movie) -> Bool {
return lhs.name == rhs.name
}
static func <(lhs: Movie, rhs: Movie) -> Bool {
return lhs.name < rhs.name
}
}
Usage:
let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")
let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted()
print(sortedMovies)
/*
prints: [Avatar, Piranha II: The Spawning, Titanic]
*/
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 2012);
cal.add(Calendar.DAY_OF_MONTH, 5);
You can also substract days like Calendar.add(Calendar.DAY_OF_MONTH, -5);
git diff --stat 4b825dc642cb6eb9a060e54bf8d69288fbee4904
This shows the differences from the empty tree to your current working tree. Which happens to count all lines in your current working tree.
To get the numbers in your current working tree, do this:
git diff --shortstat `git hash-object -t tree /dev/null`
It will give you a string like 1770 files changed, 166776 insertions(+)
.
SSIS is a very good way to do this. This can be then scheduled using SQL Server Agent jobs.
Using the CSV idea, if it's just a list of Strings. Assuming l
is your list:
using System.IO;
using(StreamWriter sw = File.CreateText("list.csv"))
{
for(int i = 0; i < l.Count; i++)
{
sw.WriteLine(l[i]);
}
}
For reference, I am attaching my location
block for catching files with the .php
extension:
location ~ \.php$ {
include /path/to/fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}
Double-check the /path/to/fastcgi-params
, and make sure that it is present and readable by the nginx user.
I use SharePrefrences:
package myapps.serializedemo;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create the SharedPreferences
SharedPreferences sharedPreferences = this.getSharedPreferences("myapps.serilizerdemo", Context.MODE_PRIVATE);
ArrayList<String> friends = new ArrayList<>();
friends.add("Jack");
friends.add("Joe");
try {
//Write / Serialize
sharedPreferences.edit().putString("friends",
ObjectSerializer.serialize(friends)).apply();
} catch (IOException e) {
e.printStackTrace();
}
//READ BACK
ArrayList<String> newFriends = new ArrayList<>();
try {
newFriends = (ArrayList<String>) ObjectSerializer.deserialize(
sharedPreferences.getString("friends", ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
}
Log.i("***NewFriends", newFriends.toString());
}
}
You can use Type.GetType(string)
, but you'll need to know the full class name including namespace, and if it's not in the current assembly or mscorlib you'll need the assembly name instead. (Ideally, use Assembly.GetType(typeName)
instead - I find that easier in terms of getting the assembly reference right!)
For instance:
// "I know String is in the same assembly as Int32..."
Type stringType = typeof(int).Assembly.GetType("System.String");
// "It's in the current assembly"
Type myType = Type.GetType("MyNamespace.MyType");
// "It's in System.Windows.Forms.dll..."
Type formType = Type.GetType ("System.Windows.Forms.Form, " +
"System.Windows.Forms, Version=2.0.0.0, Culture=neutral, " +
"PublicKeyToken=b77a5c561934e089");
Are you hosting the site on iis? if so make sure the account your website runs under has access to local file system?
Straight from msdn .....
The Network Service account has Read and Execute permissions on the IIS server root folder by default. The IIS server root folder is named Wwwroot. This means that an ASP.NET application deployed inside the root folder already has Read and Execute permissions to its application folders. However, if your ASP.NET application needs to use files or folders in other locations, you must specifically enable access.
To provide access to an ASP.NET application running as Network Service, you must grant access to the Network Service account.
To grant read, write, and modify permissions to a specific file
Click here for more
The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).
For example:
struct foo_t {
int x;
char c;
};
Even though the c
field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8
(on a 32-bit system - rather a system with a 32-bit int
type) because there will need to be 3 bytes of padding after the c
field.
Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.
def my_add_fn():
print "SUM:%s"%sum(map(int,raw_input("Enter 2 numbers seperated by a space").split()))
def my_quit_fn():
raise SystemExit
def invalid():
print "INVALID CHOICE!"
menu = {"1":("Sum",my_add_fn),
"2":("Quit",my_quit_fn)
}
for key in sorted(menu.keys()):
print key+":" + menu[key][0]
ans = raw_input("Make A Choice")
menu.get(ans,[None,invalid])[1]()
When you are using JVM in 32-bit mode, the maximum heap size that can be allocated is 1280 MB. So, if you want to go beyond that, you need to invoke JVM in 64-mode.
You can use following:
$ java -d64 -Xms512m -Xmx4g HelloWorld
where,
You can tune in -Xms and -Xmx as per you requirements (YMMV)
A very good resource on JVM performance tuning, which might want to look into: http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html
Use the error
handler like this:
$('#image_id').error(function() {
alert('Image does not exist !!');
});
If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:
Update:
I think using:
$.ajax({url:'somefile.dat',type:'HEAD',error:do_something});
would be enough to check for a 404.
More Readings:
Update 2:
Your code should be like this:
$(this).error(function() {
alert('Image does not exist !!');
});
No need for these lines and that won't check if the remote file exists anyway:
var imgcheck = imgsrc.width;
if (imgcheck==0) {
alert("You have a zero size image");
} else {
//execute the rest of code here
}
Function Concat(myRange As Range, Optional myDelimiter As String) As String
Dim r As Range
Application.Volatile
For Each r In myRange
If Len(r.Text) Then
Concat = Concat & IIf(Concat <> "", myDelimiter, "") & r.Text
End If
Next
End Function
To check whether the frame have been loaded, use onload function. Or put your main function in load: I recommend to use load when creating the iframe by js
$('<iframe />', {
src: url,
id: 'receiver',
frameborder: 1,
load:function(){
//put your code here, so that those code can be make sure to be run after the frame loaded
}
}).appendTo('body');
In bash version 4 associative arrays were introduced.
declare -A arr
arr["key1"]=val1
arr+=( ["key2"]=val2 ["key3"]=val3 )
The arr array now contains the three key value pairs. Bash is fairly limited what you can do with them though, no sorting or popping etc.
for key in ${!arr[@]}; do
echo ${key} ${arr[${key}]}
done
Will loop over all key values and echo them out.
Note: Bash 4 does not come with Mac OS X because of its GPLv3 license; you have to download and install it. For more on that see here
You might get a more descriptive error message if you tried to start the service from command line using this command:
"C:\Program Files\PostgreSQL\9.5\bin\pg_ctl.exe" start -N "postgresql-x64-9.5"
-D "C:\Program Files\PostgreSQL\9.5\data" -w
The log file would be at C:\Program Files\PostgreSQL\9.5\data\pg_log
.
Note that paths and service name might be different depending on your installation.
This is a more accurate way to do it. It places decimals behind the seconds giving more precision.
$now = date('Y-m-d\TH:i:s.uP', time());
Notice the .uP
.
More info: https://stackoverflow.com/a/6153162/8662476
With reacts Hooks:
import ReactDOM from 'react-dom';
import React, {useRef} from 'react';
const divRef = useRef<HTMLDivElement>(null);
<div ref={divRef}/>
const scrollToDivRef = () => {
let node = ReactDOM.findDOMNode(divRef.current) as Element;
node.scrollIntoView({block: 'start', behavior: 'smooth'});
}
Open the project file and not the solution. The project will be converted by the Wizard, and after converted, when you build the project, a new Solution will be generated as a VS2010 one.
IMO code with a stand-alone SELECT used to check to see if a row exists in a table is not taking proper advantage of the database. In your example you've got a hard-coded ID value but that's not how apps work in "the real world" (at least not in my world - yours may be different :-). In a typical app you're going to use a cursor to find data - so let's say you've got an app that's looking at invoice data, and needs to know if the customer exists. The main body of the app might be something like
FOR aRow IN (SELECT * FROM INVOICES WHERE DUE_DATE < TRUNC(SYSDATE)-60)
LOOP
-- do something here
END LOOP;
and in the -- do something here
you want to find if the customer exists, and if not print an error message.
One way to do this would be to put in some kind of singleton SELECT, as in
-- Check to see if the customer exists in PERSON
BEGIN
SELECT 'TRUE'
INTO strCustomer_exists
FROM PERSON
WHERE PERSON_ID = aRow.CUSTOMER_ID;
EXCEPTION
WHEN NO_DATA_FOUND THEN
strCustomer_exists := 'FALSE';
END;
IF strCustomer_exists = 'FALSE' THEN
DBMS_OUTPUT.PUT_LINE('Customer does not exist!');
END IF;
but IMO this is relatively slow and error-prone. IMO a Better Way (tm) to do this is to incorporate it in the main cursor:
FOR aRow IN (SELECT i.*, p.ID AS PERSON_ID
FROM INVOICES i
LEFT OUTER JOIN PERSON p
ON (p.ID = i.CUSTOMER_PERSON_ID)
WHERE DUE_DATA < TRUNC(SYSDATE)-60)
LOOP
-- Check to see if the customer exists in PERSON
IF aRow.PERSON_ID IS NULL THEN
DBMS_OUTPUT.PUT_LINE('Customer does not exist!');
END IF;
END LOOP;
This code counts on PERSON.ID being declared as the PRIMARY KEY on PERSON (or at least as being NOT NULL); the logic is that if the PERSON table is outer-joined to the query, and the PERSON_ID comes up as NULL, it means no row was found in PERSON for the given CUSTOMER_ID because PERSON.ID must have a value (i.e. is at least NOT NULL).
Share and enjoy.
Just a piece of advice. Instead of writing
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
as suggested above, write a:
for (vector<double>::iterator it=Main.begin(); it!=Main.end(); it++) {
cout << *it << '\n';
}
to use iterators. If you have C++11
support, you can declare i
as auto i=Main.begin()
(just a handy shortcut though)
This avoids the nasty one-position-out-of-bound error caused by leaving out a -1
unintentionally.
X display location : localhost:0 Worked for me :)
I think using KeyDerivation.Pbkdf2 is better than Rfc2898DeriveBytes.
Example and explanation: Hash passwords in ASP.NET Core
using System;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
public class Program
{
public static void Main(string[] args)
{
Console.Write("Enter a password: ");
string password = Console.ReadLine();
// generate a 128-bit salt using a secure PRNG
byte[] salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
Console.WriteLine($"Salt: {Convert.ToBase64String(salt)}");
// derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 10000,
numBytesRequested: 256 / 8));
Console.WriteLine($"Hashed: {hashed}");
}
}
/*
* SAMPLE OUTPUT
*
* Enter a password: Xtw9NMgx
* Salt: NZsP6NnmfBuYeJrrAKNuVQ==
* Hashed: /OOoOer10+tGwTRDTrQSoeCxVTFr6dtYly7d0cPxIak=
*/
This is a sample code from the article. And it's a minimum security level. To increase it I would use instead of KeyDerivationPrf.HMACSHA1 parameter
KeyDerivationPrf.HMACSHA256 or KeyDerivationPrf.HMACSHA512.
Don't compromise on password hashing. There are many mathematically sound methods to optimize password hash hacking. Consequences could be disastrous. Once a malefactor can get his hands on password hash table of your users it would be relatively easy for him to crack passwords given algorithm is weak or implementation is incorrect. He has a lot of time (time x computer power) to crack passwords. Password hashing should be cryptographically strong to turn "a lot of time" to "unreasonable amount of time".
One more point to add
Hash verification takes time (and it's good). When user enters wrong user name it's takes no time to check that user name is incorrect. When user name is correct we start password verification - it's relatively long process.
For a hacker it would be very easy to understand if user exists or doesn't.
Make sure not to return immediate answer when user name is wrong.
Needless to say : never give an answer what is wrong. Just general "Credentials are wrong".
Some of the other answers given are great. But I am surprised that no one mentioned that it can be used to help enforce const
correctness in a compact way.
Something like this:
const int n = (x != 0) ? 10 : 20;
so basically n
is a const
whose initial value is dependent on a condition statement. The easiest alternative is to make n
not a const
, this would allow an ordinary if
to initialize it. But if you want it to be const
, it cannot be done with an ordinary if
. The best substitute you could make would be to use a helper function like this:
int f(int x) {
if(x != 0) { return 10; } else { return 20; }
}
const int n = f(x);
but the ternary if version is far more compact and arguably more readable.
Consider the alternative:
<properties>
<javac.src.version>1.8</javac.src.version>
<javac.target.version>1.8</javac.target.version>
</properties>
It should be the same thing of maven.compiler.source/maven.compiler.target
but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)
SELECT *, COUNT(*) FROM my_table
is not what you want, and it's not really valid SQL, you have to group by all the columns that's not an aggregate.
You'd want something like
SELECT somecolumn,someothercolumn, COUNT(*)
FROM my_table
GROUP BY somecolumn,someothercolumn
A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next
. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear
below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:
On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
WScript.Echo "Error: " & Err.Number
WScript.Echo "Error (Hex): " & Hex(Err.Number)
WScript.Echo "Source: " & Err.Source
WScript.Echo "Description: " & Err.Description
Err.Clear ' Clear the Error
End If
On Error Goto 0 ' Don't resume on Error
WScript.Echo "This text will always print."
Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear
with WScript.Quit(Err.Number)
.
Also note the On Error Goto 0
which turns off resuming execution at the next statement when an error occurs.
If you want to test behavior for when the Set
succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp
.
The On Error
directive only affects the current running scope (current Sub
or Function
) and does not affect calling or called scopes.
If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise
. Err.Raise
takes up to five arguments, Number
, Source
, Description
, HelpFile
, and HelpContext
. Using help files and contexts is beyond the scope of this text. Number
is an error number you choose, Source
is the name of your application/class/object/property that is raising the error, and Description
is a short description of the error that occurred.
If MyValue <> 42 Then
Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If
You could then handle the raised error as discussed above.
Change Log
Err.Clear
before the possibly error causing line to clear any previous errors that may have been ignored.
On Error Resume Next
and Err.Clear
. Fixed some grammar to be less awkward. Added info on Err.Raise
. Formatting.
Bootstrap 5 has changed the ml,mr,pl,pr
classes, which no longer work if you're upgrading from a lower version.
The l
and r
have now been replaced with s
(...which is confusing) and e
(east?) respectively.
From bootstrap website:
Where property is one of:
Where sides is one of:
0 - for classes that eliminate the margin or padding by setting it to 0 1 - (by default) for classes that set the margin or padding to $spacer * .25 2 - (by default) for classes that set the margin or padding to $spacer * .5 3 - (by default) for classes that set the margin or padding to $spacer 4 - (by default) for classes that set the margin or padding to $spacer * 1.5 5 - (by default) for classes that set the margin or padding to $spacer * 3 auto - for classes that set the margin to auto (You can add more sizes by adding entries to the $spacers Sass map variable.)
instead of writing listb.pop[0]
write
listb.pop()[0]
^
|
Quoting this link: http://steveswanson.wordpress.com/2009/04/21/exporting-and-importing-an-individual-mysql-table/
To export the table run the following command from the command line:
mysqldump -p --user=username dbname tableName > tableName.sql
This will export the tableName to the file tableName.sql.
To import the table run the following command from the command line:
mysql -u username -p -D dbname < tableName.sql
The path to the tableName.sql needs to be prepended with the absolute path to that file. At this point the table will be imported into the DB.
You can use date filter to convert in date and display in specific format.
In .ts file (typescript):
let dateString = '1968-11-16T00:00:00'
let newDate = new Date(dateString);
In HTML:
{{dateString | date:'MM/dd/yyyy'}}
Below are some formats which you can implement :
Backend:
public todayDate = new Date();
HTML :
<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option>
</select>
If you're getting source in Content Use the following method
try
{
var response = restClient.Execute<List<EmpModel>>(restRequest);
var jsonContent = response.Content;
var data = JsonConvert.DeserializeObject<List<EmpModel>>(jsonContent);
foreach (EmpModel item in data)
{
listPassingData?.Add(item);
}
}
catch (Exception ex)
{
Console.WriteLine($"Data get mathod problem {ex} ");
}
For Windows, first install the git base from here: https://git-scm.com/downloads
Next, set the environment variable:
C:\Program Files\Git\git-bash.exe
To test it, open the command window: press Windows+R, type cmd and then type ssh.
Since python 3.6 you can use fstring :
>>> length = 1
>>> print(f'length = {length:03}')
length = 001
Others have answered your question, but I'll go into a little bit more detail:
Python's is
compares identity - it asks the question "is this one thing actually the same object as this other thing" (similar to ==
in Java). So, there are some times when using is
makes sense - the most common one being checking for None
. Eg, foo is None
. But, in general, it isn't what you want.
==
, on the other hand, asks the question "is this one thing logically equivalent to this other thing". For example:
>>> [1, 2, 3] == [1, 2, 3]
True
>>> [1, 2, 3] is [1, 2, 3]
False
And this is true because classes can define the method they use to test for equality:
>>> class AlwaysEqual(object):
... def __eq__(self, other):
... return True
...
>>> always_equal = AlwaysEqual()
>>> always_equal == 42
True
>>> always_equal == None
True
But they cannot define the method used for testing identity (ie, they can't override is
).
You can do it, but not at the point you've specified. Within the context of B
, you may invoke A.X()
by calling base.X()
.
Try this
<style>
@font-face {
font-family: Roboto Bold Condensed;
src: url(fonts/Roboto_Condensed/RobotoCondensed-Bold.ttf);
}
@font-face {
font-family:Roboto Condensed;
src: url(fonts/Roboto_Condensed/RobotoCondensed-Regular.tff);
}
div1{
font-family:Roboto Bold Condensed;
}
div2{
font-family:Roboto Condensed;
}
</style>
<div id='div1' >This is Sample text</div>
<div id='div2' >This is Sample text</div>
You can handle it like this:
for API level 5 and greater
@Override
public void onBackPressed() {
// your code.
}
older than API 5
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// your code
return true;
}
return super.onKeyDown(keyCode, event);
}
It depends on your need.
Using DECIMAL(10,2)
usually is enough but if you need a little bit more precise values you can set DECIMAL(10,4)
.
If you work with big values replace 10
with 19
.
I had similar issue, my code was:
function RadioInput(props) {
return (
<div className="form-check form-check-inline">
<input className="form-check-input" type="radio" name="inlineRadioOptions" id={props.id} onClick={props.onClick} value={props.label}></input>
<label className="form-check-label" htmlFor={props.id}>{props.label}</label>
</div>
);
}
class ScheduleType extends React.Component
{
renderRadioInput(id,label)
{
id = "inlineRadio"+id;
return(
<RadioInput
id = {id}
label = {label}
onClick = {this.props.onClick}
/>
);
}
Where it should be
onClick = {() => this.props.onClick()}
in RenderRadioInput
It fixed the issue for me.
To get current language of device
NSLocale.preferredLanguages()[0] as String
To get application language
NSBundle.mainBundle().preferredLocalizations[0] as NSString
Note:
It fetches the language that you have given in CFBundleDevelopmentRegion of info.plist
if CFBundleAllowMixedLocalizations is true in info.plist then first item of CFBundleLocalizations in info.plist is returned
Use convert
from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)
That simply means that your server does not have access to the SMTP Server.
You can test this by doing:
telnet <smtpServer> <smtpPort>
You should get the Access denied error.
The solution is to just use another SMTP server that can be accessed by your server.
There is also difference is in plan handling.
Oracle is able form an optimized plan with concatenation of branch filters when search contains comparison of nvl
result with an indexed column.
create table tt(a, b) as
select level, mod(level,10)
from dual
connect by level<=1e4;
alter table tt add constraint ix_tt_a primary key(a);
create index ix_tt_b on tt(b);
explain plan for
select * from tt
where a=nvl(:1,a)
and b=:2;
explain plan for
select * from tt
where a=coalesce(:1,a)
and b=:2;
nvl:
-----------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
-----------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 2 | 52 | 2 (0)| 00:00:01 |
| 1 | CONCATENATION | | | | | |
|* 2 | FILTER | | | | | |
|* 3 | TABLE ACCESS BY INDEX ROWID| TT | 1 | 26 | 1 (0)| 00:00:01 |
|* 4 | INDEX RANGE SCAN | IX_TT_B | 7 | | 1 (0)| 00:00:01 |
|* 5 | FILTER | | | | | |
|* 6 | TABLE ACCESS BY INDEX ROWID| TT | 1 | 26 | 1 (0)| 00:00:01 |
|* 7 | INDEX UNIQUE SCAN | IX_TT_A | 1 | | 1 (0)| 00:00:01 |
-----------------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
2 - filter(:1 IS NULL)
3 - filter("A" IS NOT NULL)
4 - access("B"=TO_NUMBER(:2))
5 - filter(:1 IS NOT NULL)
6 - filter("B"=TO_NUMBER(:2))
7 - access("A"=:1)
coalesce:
---------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
---------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 26 | 1 (0)| 00:00:01 |
|* 1 | TABLE ACCESS BY INDEX ROWID| TT | 1 | 26 | 1 (0)| 00:00:01 |
|* 2 | INDEX RANGE SCAN | IX_TT_B | 40 | | 1 (0)| 00:00:01 |
---------------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
1 - filter("A"=COALESCE(:1,"A"))
2 - access("B"=TO_NUMBER(:2))
Credits go to http://www.xt-r.com/2012/03/nvl-coalesce-concatenation.html.
@bardev provides a good solution, but unfortunately it's not ideal in all cases. Mine was one of them.
I'm using WebForms in a Website (I swear I'll never use a Website again--what a PITA) in VS 2013.
I tried the Razor suggestion, but mine being a Website I didn't get the all-important IntelliSense that the IDE delivers in an MVC project. I also like to use the designer for my templates--a perfect spot for a UserControl.
Nix on Razor again.
So I came up with this little framework instead (hat tips to @mun for UserControl and @imatoria for Strong Typing). Just about the only potential trouble spot I can see is that you have to be careful to keep your .ASCX filename in sync with its class name. If you stray, you'll get a runtime error.
FWIW: In my testing at least the RenderControl() call doesn't like a Page control, so I went with UserControl.
I'm pretty sure I've included everything here; let me know if I left something out.
HTH
Usage:
Partial Class Purchase
Inherits UserControl
Private Sub SendReceipt()
Dim oTemplate As MailTemplates.PurchaseReceipt
oTemplate = MailTemplates.Templates.PurchaseReceipt(Me)
oTemplate.Name = "James Bond"
oTemplate.OrderTotal = 3500000
oTemplate.OrderDescription = "Q-Stuff"
oTemplate.InjectCss("PurchaseReceipt")
Utils.SendMail("{0} <[email protected]>".ToFormat(oTemplate.Name), "Purchase Receipt", oTemplate.ToHtml)
End Sub
End Class
Base Class:
Namespace MailTemplates
Public MustInherit Class BaseTemplate
Inherits UserControl
Public Shared Function GetTemplate(Caller As TemplateControl, Template As Type) As BaseTemplate
Return Caller.LoadControl("~/MailTemplates/{0}.ascx".ToFormat(Template.Name))
End Function
Public Sub InjectCss(FileName As String)
If Me.Styler IsNot Nothing Then
Me.Styler.Controls.Add(New Controls.Styler(FileName))
End If
End Sub
Private ReadOnly Property Styler As PlaceHolder
Get
If _Styler Is Nothing Then
_Styler = Me.FindNestedControl(GetType(PlaceHolder))
End If
Return _Styler
End Get
End Property
Private _Styler As PlaceHolder
End Class
End Namespace
"Factory" Class:
Namespace MailTemplates
Public Class Templates
Public Shared ReadOnly Property PurchaseReceipt(Caller As TemplateControl) As PurchaseReceipt
Get
Return BaseTemplate.GetTemplate(Caller, GetType(PurchaseReceipt))
End Get
End Property
End Class
End Namespace
Template Class:
Namespace MailTemplates
Public MustInherit Class PurchaseReceipt
Inherits BaseTemplate
Public MustOverride WriteOnly Property Name As String
Public MustOverride WriteOnly Property OrderTotal As Decimal
Public MustOverride WriteOnly Property OrderDescription As String
End Class
End Namespace
ASCX Header:
<%@ Control Language="VB" ClassName="_Header" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
See https://www.campaignmonitor.com/blog/post/3317/ for discussion of DocType in HTML Email
-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<asp:PlaceHolder ID="plcStyler" runat="server"></asp:PlaceHolder>
</head>
<body>
ASCX Footer:
<%@ Control Language="VB" ClassName="_Footer" %>
</body>
</html>
ASCX Template:
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="PurchaseReceipt.ascx.vb" Inherits="PurchaseReceipt" %>
<%@ Register Src="_Header.ascx" TagName="Header" TagPrefix="uc" %>
<%@ Register Src="_Footer.ascx" TagName="Footer" TagPrefix="uc" %>
<uc:Header ID="ctlHeader" runat="server" />
<p>Name: <asp:Label ID="lblName" runat="server"></asp:Label></p>
<p>Order Total: <asp:Label ID="lblOrderTotal" runat="server"></asp:Label></p>
<p>Order Description: <asp:Label ID="lblOrderDescription" runat="server"></asp:Label></p>
<uc:Footer ID="ctlFooter" runat="server" />
ASCX Template CodeFile:
Partial Class PurchaseReceipt
Inherits MailTemplates.PurchaseReceipt
Public Overrides WriteOnly Property Name As String
Set(Value As String)
lblName.Text = Value
End Set
End Property
Public Overrides WriteOnly Property OrderTotal As Decimal
Set(Value As Boolean)
lblOrderTotal.Text = Value
End Set
End Property
Public Overrides WriteOnly Property OrderDescription As Decimal
Set(Value As Boolean)
lblOrderDescription.Text = Value
End Set
End Property
End Class
Helpers:
'
' FindNestedControl helpers based on tip by @andleer
' at http://stackoverflow.com/questions/619449/
'
Public Module Helpers
<Extension>
Public Function AllControls(Control As Control) As List(Of Control)
Return Control.Controls.Flatten
End Function
<Extension>
Public Function FindNestedControl(Control As Control, Id As String) As Control
Return Control.Controls.Flatten(Function(C) C.ID = Id).SingleOrDefault
End Function
<Extension>
Public Function FindNestedControl(Control As Control, Type As Type) As Control
Return Control.Controls.Flatten(Function(C) C.GetType = Type).SingleOrDefault
End Function
<Extension>
Public Function Flatten(Controls As ControlCollection) As List(Of Control)
Flatten = New List(Of Control)
Controls.Traverse(Sub(Control) Flatten.Add(Control))
End Function
<Extension>
Public Function Flatten(Controls As ControlCollection, Predicate As Func(Of Control, Boolean)) As List(Of Control)
Flatten = New List(Of Control)
Controls.Traverse(Sub(Control)
If Predicate(Control) Then
Flatten.Add(Control)
End If
End Sub)
End Function
<Extension>
Public Sub Traverse(Controls As ControlCollection, Action As Action(Of Control))
Controls.Cast(Of Control).ToList.ForEach(Sub(Control As Control)
Action(Control)
If Control.HasControls Then
Control.Controls.Traverse(Action)
End If
End Sub)
End Sub
<Extension()>
Public Function ToFormat(Template As String, ParamArray Values As Object()) As String
Return String.Format(Template, Values)
End Function
<Extension()>
Public Function ToHtml(Control As Control) As String
Dim oSb As StringBuilder
oSb = New StringBuilder
Using oSw As New StringWriter(oSb)
Using oTw As New HtmlTextWriter(oSw)
Control.RenderControl(oTw)
Return oSb.ToString
End Using
End Using
End Function
End Module
Namespace Controls
Public Class Styler
Inherits LiteralControl
Public Sub New(FileName As String)
Dim _
sFileName,
sFilePath As String
sFileName = Path.GetFileNameWithoutExtension(FileName)
sFilePath = HttpContext.Current.Server.MapPath("~/Styles/{0}.css".ToFormat(sFileName))
If File.Exists(sFilePath) Then
Me.Text = "{0}<style type=""text/css"">{0}{1}</style>{0}".ToFormat(vbCrLf, File.ReadAllText(sFilePath))
Else
Me.Text = String.Empty
End If
End Sub
End Class
End Namespace
Public Class Utils
Public Shared Sub SendMail(Recipient As MailAddress, Subject As String, HtmlBody As String)
Using oMessage As New MailMessage
oMessage.To.Add(Recipient)
oMessage.IsBodyHtml = True
oMessage.Subject = Subject.Trim
oMessage.Body = HtmlBody.Trim
Using oClient As New SmtpClient
oClient.Send(oMessage)
End Using
End Using
End Sub
End Class
I would try:
self.wordList = list(wordList)
to force it to make a copy instead of referencing the same object.
use this
public static Set<Class> getExtendedClasses(Class superClass)
{
try
{
ResolverUtil resolver = new ResolverUtil();
resolver.findImplementations(superClass, superClass.getPackage().getName());
return resolver.getClasses();
}
catch(Exception e)
{Log.d("Log:", " Err: getExtendedClasses() ");}
return null;
}
getExtendedClasses(Animals.class);
Edit:
--Find and drop the constraints
DECLARE @dynamicSQL VARCHAR(MAX)
DECLARE MY_CURSOR CURSOR
LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT dynamicSQL = 'ALTER TABLE [' + OBJECT_SCHEMA_NAME(parent_object_id) + '].[' + OBJECT_NAME(parent_object_id) + '] DROP CONSTRAINT [' + name + ']'
FROM sys.foreign_keys
WHERE object_name(referenced_object_id) in ('table1', 'table2', 'table3')
OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @dynamicSQL
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @dynamicSQL
EXEC (@dynamicSQL)
FETCH NEXT FROM MY_CURSOR INTO @dynamicSQL
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR
-- Drop tables
DROP 'table1'
DROP 'table2'
DROP 'table3'
I've pasted what I use in my excel file below. This picks up unique values from range L11:L300
and populate them from in column V, V11 onwards. In this case I have this formula in v11 and drag it down to get all the unique values.
=INDEX(L$11:L$300,MATCH(0,COUNTIF(V$10:V10,L$11:L$300),0))
or
=INDEX(L$11:L$300,MATCH(,COUNTIF(V$10:V10,L$11:L$300),))
this is an array formula
My fix for this issue was to separate the primary key with the foreign key. If you are using eclipse and made the above changes please remember to refresh the database explorer. Then recreate the entities from the tables.
I found that adding "-i" to the commit command fixes this problem for me. The -i basically tells it to stage additional files before committing. That is:
git commit -i myfile.php
You can coalesce your NULLs in the ORDER BY
statement:
select * from tablename
where <conditions>
order by
coalesce(position, 0) ASC,
id DESC
If you want the NULLs to sort on the bottom, try coalesce(position, 100000)
. (Make the second number bigger than all of the other position
's in the db.)
Try to use edithidden: true and also do
editoptions: { dataInit: function(element) { $(element).attr("readonly", "readonly"); } }
Or see jqGrid wiki for custom editing, you can setup any input type, even label I think.
Variables can be assigned but not declared inside the conditional statement:
int v;
if((v = someMethod()) != 0) return true;
import re
mystr = "I want to Remove all white \t spaces, new lines \n and tabs \t"
print re.sub(r"\W", "", mystr)
Output : IwanttoRemoveallwhitespacesnewlinesandtabs
If you want know, the how may nodejs processes running then you can use this command
ps -aef | grep node
So it will give list of nodejs process with it's project name. It will be helpful when you are running multipe nodejs application & you want kill specific process for the specific project.
Above command will give output like
XXX 12886 1741 1 12:36 ? 00:00:05 /home/username/.nvm/versions/node/v9.2.0/bin/node --inspect-brk=43443 /node application running path.
So to kill you can use following command
kill -9 12886
So it will kill the spcefic node process
I just ran into this issue with Safari 5 and it has been an issue with Opera 10 for some time, but I never spent time to fix it. Now I need to fix it and saw your post but no solution yet on how to cancel the form. After much searching I finally found something:
http://www.w3.org/TR/html5/forms.html#attr-fs-formnovalidate
<input type=submit formnovalidate name=cancel value="Cancel">
Works on Safari 5 and Opera 10.
I'd like to comment on Wikipedia's definition of virtual, as repeated by several here. [At the time this answer was written,] Wikipedia defined a virtual method as one that can be overridden in subclasses. [Fortunately, Wikipedia has been edited since, and it now explains this correctly.] That is incorrect: any method, not just virtual ones, can be overridden in subclasses. What virtual does is to give you polymorphism, that is, the ability to select at run-time the most-derived override of a method.
Consider the following code:
#include <iostream>
using namespace std;
class Base {
public:
void NonVirtual() {
cout << "Base NonVirtual called.\n";
}
virtual void Virtual() {
cout << "Base Virtual called.\n";
}
};
class Derived : public Base {
public:
void NonVirtual() {
cout << "Derived NonVirtual called.\n";
}
void Virtual() {
cout << "Derived Virtual called.\n";
}
};
int main() {
Base* bBase = new Base();
Base* bDerived = new Derived();
bBase->NonVirtual();
bBase->Virtual();
bDerived->NonVirtual();
bDerived->Virtual();
}
What is the output of this program?
Base NonVirtual called.
Base Virtual called.
Base NonVirtual called.
Derived Virtual called.
Derived overrides every method of Base: not just the virtual one, but also the non-virtual.
We see that when you have a Base-pointer-to-Derived (bDerived), calling NonVirtual calls the Base class implementation. This is resolved at compile-time: the compiler sees that bDerived is a Base*, that NonVirtual is not virtual, so it does the resolution on class Base.
However, calling Virtual calls the Derived class implementation. Because of the keyword virtual, the selection of the method happens at run-time, not compile-time. What happens here at compile-time is that the compiler sees that this is a Base*, and that it's calling a virtual method, so it insert a call to the vtable instead of class Base. This vtable is instantiated at run-time, hence the run-time resolution to the most-derived override.
I hope this wasn't too confusing. In short, any method can be overridden, but only virtual methods give you polymorphism, that is, run-time selection of the most derived override. In practice, however, overriding a non-virtual method is considered bad practice and rarely used, so many people (including whoever wrote that Wikipedia article) think that only virtual methods can be overridden.
You can do it by giving margin or by positioning those elements absolutely.
For example
.button{
margin:0px auto; //it will center them
}
0px will be from top and bottom and auto will be from left and right.
var inputs = events.Select(async ev => await ProcessEventAsync(ev))
.Select(t => t.Result)
.Where(i => i != null)
.ToList();
But this seems very weird to me, first of all the use of async and await in the select. According to this answer by Stephen Cleary I should be able to drop those.
The call to Select
is valid. These two lines are essentially identical:
events.Select(async ev => await ProcessEventAsync(ev))
events.Select(ev => ProcessEventAsync(ev))
(There's a minor difference regarding how a synchronous exception would be thrown from ProcessEventAsync
, but in the context of this code it doesn't matter at all.)
Then the second Select which selects the result. Doesn't this mean the task isn't async at all and is performed synchronously (so much effort for nothing), or will the task be performed asynchronously and when it's done the rest of the query is executed?
It means that the query is blocking. So it is not really asynchronous.
Breaking it down:
var inputs = events.Select(async ev => await ProcessEventAsync(ev))
will first start an asynchronous operation for each event. Then this line:
.Select(t => t.Result)
will wait for those operations to complete one at a time (first it waits for the first event's operation, then the next, then the next, etc).
This is the part I don't care for, because it blocks and also would wrap any exceptions in AggregateException
.
and is it completely the same like this?
var tasks = await Task.WhenAll(events.Select(ev => ProcessEventAsync(ev)));
var inputs = tasks.Where(result => result != null).ToList();
var inputs = (await Task.WhenAll(events.Select(ev => ProcessEventAsync(ev))))
.Where(result => result != null).ToList();
Yes, those two examples are equivalent. They both start all asynchronous operations (events.Select(...)
), then asynchronously wait for all the operations to complete in any order (await Task.WhenAll(...)
), then proceed with the rest of the work (Where...
).
Both of these examples are different from the original code. The original code is blocking and will wrap exceptions in AggregateException
.
Try the following:
SELECT *
FROM
(SELECT FIELDA,
FIELDB,
FIELDC,
ROW_NUMBER() OVER (ORDER BY FIELDC) R
FROM TABLE_NAME
WHERE FIELDA = 10
)
WHERE R >= 10
AND R <= 15;
via [tecnicume]
Just use Kotlin!
val list = listOf(user1, user2, user3)
val maxDate = list.maxBy { it.date }?.date
Does c# have its own version of the java "synchronized" keyword?
No. In C#, you explicitly lock
resources that you want to work on synchronously across asynchronous threads. lock
opens a block; it doesn't work on method level.
However, the underlying mechanism is similar since lock
works by invoking Monitor.Enter
(and subsequently Monitor.Exit
) on the runtime. Java works the same way, according to the Sun documentation.
You could place the link within a div, then use JavaScript on the anchor tag to hide the div when clicked. Example (not tested, may need to be tweaked but you get the idea):
<div id="printOption">
<a href="javascript:void();"
onclick="document.getElementById('printOption').style.visibility = 'hidden';
document.print();
return true;">
Print
</a>
</div>
The downside is that once clicked, the button disappears and they lose that option on the page (there's always Ctrl+P though).
The better solution would be to create a print stylesheet and within that stylesheet specify the hidden status of the printOption
ID (or whatever you call it). You can do this in the head section of the HTML and specify a second stylesheet with a media attribute.
Hint: The STRINGIZE
macro above is cool, but if you make a mistake and its argument isn't a macro - you had a typo in the name, or forgot to #include
the header file - then the compiler will happily put the purported macro name into the string with no error.
If you intend that the argument to STRINGIZE
is always a macro with a normal C value, then
#define STRINGIZE(A) ((A),STRINGIZE_NX(A))
will expand it once and check it for validity, discard that, and then expand it again into a string.
It took me a while to figure out why STRINGIZE(ENOENT)
was ending up as "ENOENT"
instead of "2"
... I hadn't included errno.h
.
Using ElementTree
:
import xml.etree.ElementTree
# Open original file
et = xml.etree.ElementTree.parse('file.xml')
# Append new tag: <a x='1' y='abc'>body text</a>
new_tag = xml.etree.ElementTree.SubElement(et.getroot(), 'a')
new_tag.text = 'body text'
new_tag.attrib['x'] = '1' # must be str; cannot be an int
new_tag.attrib['y'] = 'abc'
# Write back to file
#et.write('file.xml')
et.write('file_new.xml')
note: output written to file_new.xml
for you to experiment, writing back to file.xml
will replace the old content.
IMPORTANT: the ElementTree library stores attributes in a dict, as such, the order in which these attributes are listed in the xml text will NOT be preserved. Instead, they will be output in alphabetical order. (also, comments are removed. I'm finding this rather annoying)
ie: the xml input text <b y='xxx' x='2'>some body</b>
will be output as <b x='2' y='xxx'>some body</b>
(after alphabetising the order parameters are defined)
This means when committing the original, and changed files to a revision control system (such as SVN, CSV, ClearCase, etc), a diff between the 2 files may not look pretty.
int weight=10;
int height=10;
double bmi;
bmi = weight / Math.pow(height / 100.0, 2.0);
System.out.println("bmi"+(bmi));
double result = bmi * 100;
result = Math.round(result);
result = result / 100;
System.out.println("result"+result);
Can use this:
Select id,name,age
From Student
Where age < 15
Union ALL
SELECT * FROM (Select id,name,age
From Student
Where Name like "%a%")
How to share content: https://developers.facebook.com/docs/share/
You have to choose use the deprecated function without JS, and check every day, or follow the way use JS and have fun.
If you're running Linux I would suggest two tools:
align_image_stack from package hugin-tools - is a commandline program that can automatically correct rotation, scaling, and other distortions (it's mostly intended for compositing HDR photography, but works for video frames and other documents too). More information: http://hugin.sourceforge.net/docs/manual/Align_image_stack.html
compare from package imagemagick - a program that can find and count the amount of different pixels in two images. Here's a neat tutorial: http://www.imagemagick.org/Usage/compare/ uising the -fuzz N% you can increase the error tolerance. The higher the N the higher the error tolerance to still count two pixels as the same.
align_image_stack should correct any offset so the compare command will actually have a chance of detecting same pixels.
Kudos to @Fredrik above. His answer didn't work for me, but lead me to the resolution of my issue:
In 'Window'|'Preferences'|'Install/Update'|'Available Software Sites'. The location that I was attempting to install from the 'Marketplace' was getting inserted with an https://
URL. Editing this to http://
allowed me to then use 'Help'|Install New Software ...' to select the repository from the drop down 'Work with:' combobox instead of having the https://
one automatically inserted and used.
UPDATE: In iPhone OS 3.0 and later UITableViewCell
now has a backgroundColor
property that makes this really easy (especially in combination with the [UIColor colorWithPatternImage:]
initializer). But I'll leave the 2.0 version of the answer here for anyone that needs it…
It's harder than it really should be. Here's how I did this when I had to do it:
You need to set the UITableViewCell's backgroundView property to a custom UIView that draws the border and background itself in the appropriate colors. This view needs to be able to draw the borders in 4 different modes, rounded on the top for the first cell in a section, rounded on the bottom for the last cell in a section, no rounded corners for cells in the middle of a section, and rounded on all 4 corners for sections that contain one cell.
Unfortunately I couldn't figure out how to have this mode set automatically, so I had to set it in the UITableViewDataSource's -cellForRowAtIndexPath method.
It's a real PITA but I've confirmed with Apple engineers that this is currently the only way.
Update Here's the code for that custom bg view. There's a drawing bug that makes the rounded corners look a little funny, but we moved to a different design and scrapped the custom backgrounds before I had a chance to fix it. Still this will probably be very helpful for you:
//
// CustomCellBackgroundView.h
//
// Created by Mike Akers on 11/21/08.
// Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef enum {
CustomCellBackgroundViewPositionTop,
CustomCellBackgroundViewPositionMiddle,
CustomCellBackgroundViewPositionBottom,
CustomCellBackgroundViewPositionSingle
} CustomCellBackgroundViewPosition;
@interface CustomCellBackgroundView : UIView {
UIColor *borderColor;
UIColor *fillColor;
CustomCellBackgroundViewPosition position;
}
@property(nonatomic, retain) UIColor *borderColor, *fillColor;
@property(nonatomic) CustomCellBackgroundViewPosition position;
@end
//
// CustomCellBackgroundView.m
//
// Created by Mike Akers on 11/21/08.
// Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import "CustomCellBackgroundView.h"
static void addRoundedRectToPath(CGContextRef context, CGRect rect,
float ovalWidth,float ovalHeight);
@implementation CustomCellBackgroundView
@synthesize borderColor, fillColor, position;
- (BOOL) isOpaque {
return NO;
}
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(c, [fillColor CGColor]);
CGContextSetStrokeColorWithColor(c, [borderColor CGColor]);
if (position == CustomCellBackgroundViewPositionTop) {
CGContextFillRect(c, CGRectMake(0.0f, rect.size.height - 10.0f, rect.size.width, 10.0f));
CGContextBeginPath(c);
CGContextMoveToPoint(c, 0.0f, rect.size.height - 10.0f);
CGContextAddLineToPoint(c, 0.0f, rect.size.height);
CGContextAddLineToPoint(c, rect.size.width, rect.size.height);
CGContextAddLineToPoint(c, rect.size.width, rect.size.height - 10.0f);
CGContextStrokePath(c);
CGContextClipToRect(c, CGRectMake(0.0f, 0.0f, rect.size.width, rect.size.height - 10.0f));
} else if (position == CustomCellBackgroundViewPositionBottom) {
CGContextFillRect(c, CGRectMake(0.0f, 0.0f, rect.size.width, 10.0f));
CGContextBeginPath(c);
CGContextMoveToPoint(c, 0.0f, 10.0f);
CGContextAddLineToPoint(c, 0.0f, 0.0f);
CGContextStrokePath(c);
CGContextBeginPath(c);
CGContextMoveToPoint(c, rect.size.width, 0.0f);
CGContextAddLineToPoint(c, rect.size.width, 10.0f);
CGContextStrokePath(c);
CGContextClipToRect(c, CGRectMake(0.0f, 10.0f, rect.size.width, rect.size.height));
} else if (position == CustomCellBackgroundViewPositionMiddle) {
CGContextFillRect(c, rect);
CGContextBeginPath(c);
CGContextMoveToPoint(c, 0.0f, 0.0f);
CGContextAddLineToPoint(c, 0.0f, rect.size.height);
CGContextAddLineToPoint(c, rect.size.width, rect.size.height);
CGContextAddLineToPoint(c, rect.size.width, 0.0f);
CGContextStrokePath(c);
return; // no need to bother drawing rounded corners, so we return
}
// At this point the clip rect is set to only draw the appropriate
// corners, so we fill and stroke a rounded rect taking the entire rect
CGContextBeginPath(c);
addRoundedRectToPath(c, rect, 10.0f, 10.0f);
CGContextFillPath(c);
CGContextSetLineWidth(c, 1);
CGContextBeginPath(c);
addRoundedRectToPath(c, rect, 10.0f, 10.0f);
CGContextStrokePath(c);
}
- (void)dealloc {
[borderColor release];
[fillColor release];
[super dealloc];
}
@end
static void addRoundedRectToPath(CGContextRef context, CGRect rect,
float ovalWidth,float ovalHeight)
{
float fw, fh;
if (ovalWidth == 0 || ovalHeight == 0) {// 1
CGContextAddRect(context, rect);
return;
}
CGContextSaveGState(context);// 2
CGContextTranslateCTM (context, CGRectGetMinX(rect),// 3
CGRectGetMinY(rect));
CGContextScaleCTM (context, ovalWidth, ovalHeight);// 4
fw = CGRectGetWidth (rect) / ovalWidth;// 5
fh = CGRectGetHeight (rect) / ovalHeight;// 6
CGContextMoveToPoint(context, fw, fh/2); // 7
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);// 8
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);// 9
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);// 10
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // 11
CGContextClosePath(context);// 12
CGContextRestoreGState(context);// 13
}
Clear answers are already provided. But it's worth mentioning how devDependencies
affects installing packages:
By default, npm install will install all modules listed as dependencies in package.json . With the --production flag (or when the NODE_ENV environment variable is set to production ), npm will not install modules listed in devDependencies .
There is no such method as slideLeft() and slideRight() which looks like slideUp() and slideDown(), but you can simulate these effects using jQuery’s animate() function.
HTML Code:
<div class="text">Lorem ipsum.</div>
JQuery Code:
$(document).ready(function(){
var DivWidth = $(".text").width();
$(".left").click(function(){
$(".text").animate({
width: 0
});
});
$(".right").click(function(){
$(".text").animate({
width: DivWidth
});
});
});
You can see an example here: How to slide toggle a DIV from Left to Right?
There's a .val()
method:
If you've got an input with an id of txtEmail
you can use the following code to access the value of the text box:
$("#txtEmail").val()
You can also use the val(string)
method to set that value:
$("#txtEmail").val("something")
You have to use or read about associative arrays, or maps,..etc. Storing the the number of occurrences of the repeated elements in array, and holding another array for the repeated elements themselves, don't make much sense.
Your problem in your code is in the inner loop
for (int j = i + 1; j < x.length; j++) {
if (x[i] == x[j]) {
y[i] = x[i];
times[i]++;
}
}
I simply got this error because my .cpp file was not in the makefile.
In general, if you forget to compile or link to the specific object file containing the definition, you will run into this error.
you can move to another fragment by using the FragmentManager transactions. Fragment can not be called like activities,. Fragments exists on the existance of activities.
You can call another fragment by writing the code below:
FragmentTransaction t = this.getFragmentManager().beginTransaction();
Fragment mFrag = new MyFragment();
t.replace(R.id.content_frame, mFrag);
t.commit();
here "R.id.content_frame" is the id of the layout on which you want to replace the fragment.
you can also add the other fragment incase of replace.
The OP says, for unknown reasons, "I prefer it without an arraylist or list."
If the type you are referring to is a primitive (you mention integers, but you don't say if you mean int
or Integer
), then you can use one of the NIO Buffer classes like java.nio.IntBuffer
. These act a lot like StringBuffer
does - they act as buffers for a list of the primitive type (buffers exist for all the primitives but not for Objects), and you can wrap a buffer around an array and/or extract an array from a buffer.
Note that the javadocs say, "The capacity of a buffer is never negative and never changes." It's still just a wrapper around an array, but one that's nicer to work with. The only way to effectively expand a buffer is to allocate()
a larger one and use put()
to dump the old buffer into the new one.
If it's not a primitive, you should probably just use List
, or come up with a compelling reason why you can't or won't, and maybe somebody will help you work around it.
To read a particular date from range EJ_PAYDATES_2021 (index is next to the last "1")
=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,1,1) // Jan
=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,2,1) // Feb
=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,3,1) // Mar
This allows reading a particular element of a range [0] etc from another spreadsheet file. Target file need not be open. Range in the above example is named EJ_PAYDATES_2021, with one element for each month contained within that range.
Took me a while to parse this out, but it works, and is the answer to the question asked above.
I would do something like:
filename = "mynumbers.txt"
mynumbers = []
with open(filename) as f:
for line in f:
mynumbers.append([int(n) for n in line.strip().split(',')])
for pair in mynumbers:
try:
x,y = pair[0],pair[1]
# Do Something with x and y
except IndexError:
print "A line in the file doesn't have enough entries."
The with open is recommended in http://docs.python.org/tutorial/inputoutput.html since it makes sure files are closed correctly even if an exception is raised during the processing.
If you want to use the call operator, the arguments can be an array stored in a variable:
$prog = 'c:\windows\system32\cmd.exe'
$myargs = '/c','dir','/x'
& $prog $myargs
The call operator works with ApplicationInfo objects too.
$prog = get-command cmd
$myargs = -split '/c dir /x'
& $prog $myargs
Just access the element and append it to the value.
<input
type="button"
onclick="document.getElementById('myTextArea').value += '•'"
value="Add •">
See a live demo.
For the sake of keeping things simple, I haven't written unobtrusive JS. For a production system you should.
Also it needs to be a UTF8 character.
Browsers generally submit forms using the encoding they received the page in. Serve your page as UTF-8 if you want UTF-8 data submitted back.
I collected some information on the internet and prepared the script that requires no external tool: See my response here. Hope it's helpful.
When you have a list of dfs, and a column contains the "ID", but in some lists, some IDs are missing, then you may use this version of Reduce / Merge in order to join multiple Dfs of missing Row Ids or labels:
Reduce(function(x, y) merge(x=x, y=y, by="V1", all.x=T, all.y=T), list_of_dfs)
And if nothing works by whatever reason, build it from the command line:
ant -Dj2ee.server.home=D:\apache-tomcat-8.0.23 clean
ant -Dj2ee.server.home=D:\apache-tomcat-8.0.23 compile
ant -Dj2ee.server.home=D:\apache-tomcat-8.0.23 dist
This approach is ok but will not work for when you get params dynamically , sometimes 1, 2, 3 or more, just like a SOLR search query (for example)
Here is a more flexible solution. Crude but can be refined.
public static void main(String[] args) {
String host = "localhost";
String port = "9093";
String param = "/10-2014.01?description=cars&verbose=true&hl=true&hl.simple.pre=<b>&hl.simple.post=</b>";
String[] wholeString = param.split("\\?");
String theQueryString = wholeString.length > 1 ? wholeString[1] : "";
String SolrUrl = "http://" + host + ":" + port + "/mypublish-services/carclassifications/" + "loc";
GetMethod method = new GetMethod(SolrUrl );
if (theQueryString.equalsIgnoreCase("")) {
method.setQueryString(new NameValuePair[]{
});
} else {
String[] paramKeyValuesArray = theQueryString.split("&");
List<String> list = Arrays.asList(paramKeyValuesArray);
List<NameValuePair> nvPairList = new ArrayList<NameValuePair>();
for (String s : list) {
String[] nvPair = s.split("=");
String theKey = nvPair[0];
String theValue = nvPair[1];
NameValuePair nameValuePair = new NameValuePair(theKey, theValue);
nvPairList.add(nameValuePair);
}
NameValuePair[] nvPairArray = new NameValuePair[nvPairList.size()];
nvPairList.toArray(nvPairArray);
method.setQueryString(nvPairArray); // Encoding is taken care of here by setQueryString
}
}
a.mean()
takes an axis
argument:
In [1]: import numpy as np
In [2]: a = np.array([[40, 10], [50, 11]])
In [3]: a.mean(axis=1) # to take the mean of each row
Out[3]: array([ 25. , 30.5])
In [4]: a.mean(axis=0) # to take the mean of each col
Out[4]: array([ 45. , 10.5])
Or, as a standalone function:
In [5]: np.mean(a, axis=1)
Out[5]: array([ 25. , 30.5])
The reason your slicing wasn't working is because this is the syntax for slicing:
In [6]: a[:,0].mean() # first column
Out[6]: 45.0
In [7]: a[:,1].mean() # second column
Out[7]: 10.5
[edited]
using your comment about productCode (and assuming product code is a String) as reference...
for(Product p : productList){
s.put(p.getProductCode() , p);
}
To set to default Excel type Date (defaulted to OS level locale /-> i.e. xlsx will look different when opened by a German or British person/ and flagged with an asterisk if you choose it in Excel's cell format chooser) you should:
CellStyle cellStyle = xssfWorkbook.createCellStyle();
cellStyle.setDataFormat((short)14);
cell.setCellStyle(cellStyle);
I did it with xlsx and it worked fine.
SELECT {FN LENGTH('123-345-566')} - {FN LENGTH({FN REPLACE('123-345-566', '#', '')})} FROM DUAL
You've to do that in your application layer. If you're using an ORM, it could use annotations (or something similar) to pull references that exist in other collections. I only have worked with Morphia, and the @Reference
annotation fetches the referenced entity when queried, so I am able to avoid doing it myself in the code.
Yeah think of signing data as giving it your own wax stamp that nobody else has. It is done to achieve integrity and non-repudiation. Encryption is so no-one else can see the data. This is done to achieve confidentiality. See wikipedia http://en.wikipedia.org/wiki/Information_security#Key_concepts
A signature is a hash of your message signed using your private key.
Your code is
urlpatterns = [
url(r'^$', 'myapp.views.home'),
url(r'^contact/$', 'myapp.views.contact'),
url(r'^login/$', 'django.contrib.auth.views.login'),
]
change it to following as you're importing include()
function :
urlpatterns = [
url(r'^$', views.home),
url(r'^contact/$', views.contact),
url(r'^login/$', views.login),
]
Maybe you should just write the ImageView first and the TextView second. That can help sometimes. That's simple but I hope it helps somebody. :)
For example two class A,B having same method m1(). And class C extends both A, B.
class C extends A, B // for explaining purpose.
Now, class C will search the definition of m1. First, it will search in class if it didn't find then it will check to parents class. Both A, B having the definition So here ambiguity occur which definition should choose. So JAVA DOESN'T SUPPORT MULTIPLE INHERITANCE.
JSON.stringify
JSON.stringify(`{
a:"a"
}`)
would convert the above string to
"{ \n a:\"a\"\n }"
as mentioned here
This function adds double quotes at the beginning and end of the input string and escapes special JSON characters. In particular, a newline is replaced by the \n character, a tab is replaced by the \t character, a backslash is replaced by two backslashes \, and a backslash is placed before each quotation mark.
I use this command.
kubectl -n <namespace> logs -f deployment/<app-name> --all-containers=true --since=10m
I realize this is an old question, but the Bootstrap framework has a built in class (sr-only) to handle hiding text on everything but screen readers:
<a href="/" class="navbar-brand"><span class="sr-only">Home</span></a>
<?php
$j=1;
array_reverse($skills_nav);
foreach ( $skills_nav as $skill ) {
$a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
$a .= $skill->name;
$a .= '</a></li>';
echo $a;
echo "\n";
$j++;
}
?>
You can also count on multiple groups and their intersection:
self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()
The query above will return counts for all possible combinations of values from both columns.
I think this is what the original poster meant to accomplish:
var array_of_functions = [
function() { first_function('a string') },
function() { second_function('a string') },
function() { third_function('a string') },
function() { fourth_function('a string') }
]
for (i = 0; i < array_of_functions.length; i++) {
array_of_functions[i]();
}
Hopefully this will help others (like me 20 minutes ago :-) looking for any hint about how to call JS functions in an array.
Do you mean something like 'border: 1px dotted black'?
You maybe having an older version of the ADB, Update the tools package and that should bring down the latest ADB.
If you're trying to create a web service to serve data over JSON to a web page, consider using the ASP.NET Ajax toolkit:
http://www.asp.net/learn/ajax/tutorial-05-cs.aspx
It will automatically convert your objects served over a webservice to json, and create the proxy class that you can use to connect to it.
Generic function to post any JavaScript object to the given URL.
function postAndRedirect(url, postData)
{
var postFormStr = "<form method='POST' action='" + url + "'>\n";
for (var key in postData)
{
if (postData.hasOwnProperty(key))
{
postFormStr += "<input type='hidden' name='" + key + "' value='" + postData[key] + "'></input>";
}
}
postFormStr += "</form>";
var formElement = $(postFormStr);
$('body').append(formElement);
$(formElement).submit();
}
If you're attempting to do this in a .NET Standard library, here's a simple solution, with all of the risks of just returning true
in your handler. I leave safety up to you.
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
var client = new HttpClient(handler);
If you only need to support Python 2.6 and 2.7 you can use io.open
instead of open
. io
is the new io subsystem for Python 3, and it exists in Python 2,6 ans 2.7 as well. Please be aware that in Python 2.6 (as well as 3.0) it's implemented purely in python and very slow, so if you need speed in reading files, it's not a good option.
If you need speed, and you need to support Python 2.6 or earlier, you can use codecs.open
instead. It also has an encoding parameter, and is quite similar to io.open
except it handles line-endings differently.
open()
style file handler which streams bytestrings:open(filename, 'rb')
Note the 'b', meaning 'binary'.
Firstly, you should use randrange(0,1000)
or randint(0,999)
, not randint(0,1000)
. The upper limit of randint
is inclusive.
For efficiently, randint
is simply a wrapper of randrange
which calls random
, so you should just use random
. Also, use xrange
as the argument to sample
, not range
.
You could use
[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]
to generate 10,000 numbers in the range using sample
10 times.
(Of course this won't beat NumPy.)
$ python2.7 -m timeit -s 'from random import randrange' '[randrange(1000) for _ in xrange(10000)]'
10 loops, best of 3: 26.1 msec per loop
$ python2.7 -m timeit -s 'from random import sample' '[a%1000 for a in sample(xrange(10000),10000)]'
100 loops, best of 3: 18.4 msec per loop
$ python2.7 -m timeit -s 'from random import random' '[int(1000*random()) for _ in xrange(10000)]'
100 loops, best of 3: 9.24 msec per loop
$ python2.7 -m timeit -s 'from random import sample' '[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]'
100 loops, best of 3: 3.79 msec per loop
$ python2.7 -m timeit -s 'from random import shuffle
> def samplefull(x):
> a = range(x)
> shuffle(a)
> return a' '[a for a in samplefull(1000) for _ in xrange(10000/1000)]'
100 loops, best of 3: 3.16 msec per loop
$ python2.7 -m timeit -s 'from numpy.random import randint' 'randint(1000, size=10000)'
1000 loops, best of 3: 363 usec per loop
But since you don't care about the distribution of numbers, why not just use:
range(1000)*(10000/1000)
?
That would be an HTML Encoded Line Feed character (using the hexadecimal value).
The decimal value would be
There is actually a pretty good tree structure implemented in the JDK.
Have a look at javax.swing.tree, TreeModel, and TreeNode. They are designed to be used with the JTreePanel
but they are, in fact, a pretty good tree implementation and there is nothing stopping you from using it with out a swing interface.
Note that as of Java 9 you may wish not to use these classes as they will not be present in the 'Compact profiles'.
Why would you want to put a submit button inside an anchor? You are either trying to submit a form or go to a different page. Which one is it?
Either submit the form:
<input type="submit" class="button_active" value="1" />
Or go to another page:
<input type="button" class="button_active" onclick="location.href='1.html';" />
Let say button 1 has an event called
Button1_Click(Sender, eventarg)
If you want to call it in Button2 then call this function directly.
Button1_Click(Nothing, Nothing)
I tried what Samuel Slade has suggested. Didn't work for me. The PropertyInfo
list was coming as empty. So, I tried the following and it worked for me.
Type type = typeof(Record);
FieldInfo[] properties = type.GetFields();
foreach (FieldInfo property in properties) {
Debug.LogError(property.Name);
}
<a href="<?php echo site_url('controller/function'); ?>Compose</a>
<a href="<?php echo site_url('controller/function'); ?>Inbox</a>
<a href="<?php echo site_url('controller/function'); ?>Outbox</a>
<a href="<?php echo site_url('controller/function'); ?>logout</a>
<a href="<?php echo site_url('controller/function'); ?>logout</a>
I came across this, and thought I'd throw in my 2 cents. Click on the column headers to sort ascending, and again to sort descending.
$('th').click(function(){_x000D_
var table = $(this).parents('table').eq(0)_x000D_
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))_x000D_
this.asc = !this.asc_x000D_
if (!this.asc){rows = rows.reverse()}_x000D_
for (var i = 0; i < rows.length; i++){table.append(rows[i])}_x000D_
})_x000D_
function comparer(index) {_x000D_
return function(a, b) {_x000D_
var valA = getCellValue(a, index), valB = getCellValue(b, index)_x000D_
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)_x000D_
}_x000D_
}_x000D_
function getCellValue(row, index){ return $(row).children('td').eq(index).text() }
_x000D_
table, th, td {_x000D_
border: 1px solid black;_x000D_
}_x000D_
th {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
<tr><th>Country</th><th>Date</th><th>Size</th></tr>_x000D_
<tr><td>France</td><td>2001-01-01</td><td>25</td></tr>_x000D_
<tr><td><a href=#>spain</a></td><td>2005-05-05</td><td></td></tr>_x000D_
<tr><td>Lebanon</td><td>2002-02-02</td><td>-17</td></tr>_x000D_
<tr><td>Argentina</td><td>2005-04-04</td><td>100</td></tr>_x000D_
<tr><td>USA</td><td></td><td>-6</td></tr>_x000D_
</table>
_x000D_
I've gotten this error too.
for (int i=0;i<10;i++) { ..
is not valid in the C89/C90 standard. As OysterD says, you need to do:
int i;
for (i=0;i<10;i++) { ..
Your original code is allowed in C99 and later standards of the C language.
This might help..!!!
SQLCMD -S SERVERNAME -E
There is the same problem in Linux OS. The issue is related on Windows OS, but Homestead is a Ubuntu VM, and the solution posted works strongly good in others SO. I applied the commands sugested by flik, and the problems was solved. I only used the following commands
I only used the following commands
rm -rf node_modules
npm cache clear --force
After
npm install cross-env
npm install
npm run watch
It's working fine on linux Fedora 25.
forever might be of interest to you. It will run your .js-File 24/7 with logging options. Here are two snippets from the help text:
[Long Running Process] The forever process will continue to run outputting log messages to the console. ex. forever -o out.log -e err.log my-script.js
and
[Daemon] The forever process will run as a daemon which will make the target process start in the background. This is extremely useful for remote starting simple node.js scripts without using nohup. It is recommended to run start with -o -l, & -e. ex. forever start -l forever.log -o out.log -e err.log my-daemon.js forever stop my-daemon.js
Note that numeric objects in R are stored with double precision, which gives you (roughly) 16 decimal digits of precision - the rest will be noise. I grant that the number shown above is probably just for an example, but it is 22 digits long.
You can also use the ignore syntax instead of using (or better the 'as any') notation:
// @ts-ignore
$("div.printArea").printArea();
This may be late, but sharing it for the new users visiting this question. To drop multiple columns actual syntax is
alter table tablename drop column col1, drop column col2 , drop column col3 ....
So for every column you need to specify "drop column" in Mysql 5.0.45.
You could have a div for the top with one background and another for the main page, and seperate the page content between them or put the content in a floating div on another z-level. The way you are doing it may work but I doubt it will work across every browser you encounter.
You can use an anonymous function to pass the matches to your function:
$result = preg_replace_callback(
"/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
$result
);
Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e
would convert a double quote "
into \"
.
This answer may be too late. but it will be useful for future readers.
I have some criteria. I have coded for pick the file from intent. and selected file to be passed to particular fragment for further process. i have many fragments having the functionality of File picking. at the time , every time checking the condition and get the fragment and pass the value is quite disgusting. so , i have decided to pass the value using interface.
Step 1: Create the interface on Main Activity.
public interface SelectedBundle {
void onBundleSelect(Bundle bundle);
}
Step 2: Create the SelectedBundle reference on the Same Activity
SelectedBundle selectedBundle;
Step 3: create the Method in the Same Activity
public void setOnBundleSelected(SelectedBundle selectedBundle) {
this.selectedBundle = selectedBundle;
}
Step 4: Need to initialise the SelectedBundle reference which are all fragment need filepicker functionality.You place this code on your fragment onCreateView(..)
method
((MainActivity)getActivity()).setOnBundleSelected(new MainActivity.SelectedBundle() {
@Override
public void onBundleSelect(Bundle bundle) {
updateList(bundle);
}
});
Step 5: My case, i need to pass the image Uri from HomeActivity to fragment. So, i used this functionality on onActivityResult method.
onActivityResult from the MainActivity, pass the values to the fragments using interface.
Note: Your case may be different. you can call it from any where from your HomeActivity.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
selectedBundle.onBundleSelect(bundle);
}
Thats all. Implement every fragment you needed on the FragmentClass. You are great. you have done. WOW...
Using the sibling selector is the general solution for styling other elements when hovering over a given one, but it works only if the other elements follow the given one in the DOM. What can we do when the other elements should actually be before the hovered one? Say we want to implement a signal bar rating widget like the one below:
This can actually be done easily using the CSS flexbox model, by setting flex-direction
to reverse
, so that the elements are displayed in the opposite order from the one they're in the DOM. The screenshot above is from such a widget, implemented with pure CSS.
Flexbox is very well supported by 95% of modern browsers.
.rating {_x000D_
display: flex;_x000D_
flex-direction: row-reverse;_x000D_
width: 9rem;_x000D_
}_x000D_
.rating div {_x000D_
flex: 1;_x000D_
align-self: flex-end;_x000D_
background-color: black;_x000D_
border: 0.1rem solid white;_x000D_
}_x000D_
.rating div:hover {_x000D_
background-color: lightblue;_x000D_
}_x000D_
.rating div[data-rating="1"] {_x000D_
height: 5rem;_x000D_
}_x000D_
.rating div[data-rating="2"] {_x000D_
height: 4rem;_x000D_
}_x000D_
.rating div[data-rating="3"] {_x000D_
height: 3rem;_x000D_
}_x000D_
.rating div[data-rating="4"] {_x000D_
height: 2rem;_x000D_
}_x000D_
.rating div[data-rating="5"] {_x000D_
height: 1rem;_x000D_
}_x000D_
.rating div:hover ~ div {_x000D_
background-color: lightblue;_x000D_
}
_x000D_
<div class="rating">_x000D_
<div data-rating="1"></div>_x000D_
<div data-rating="2"></div>_x000D_
<div data-rating="3"></div>_x000D_
<div data-rating="4"></div>_x000D_
<div data-rating="5"></div>_x000D_
</div>
_x000D_
Invalidate cache and restart your IntelliJ, it worked for me.
Use the wc utility with the print the byte counts (-c
) option:
$ SO="stackoverflow"
$ echo -n "$SO" | wc -c
13
You'll have to use the do not output the trailing newline (-n
) option for echo
. Otherwise, the newline character will also be counted.
Carriage return means to return to the beginning of the current line without advancing downward. The name comes from a printer's carriage, as monitors were rare when the name was coined. This is commonly escaped as \r
, abbreviated CR, and has ASCII value 13
or 0x0D
.
Linefeed means to advance downward to the next line; however, it has been repurposed and renamed. Used as "newline", it terminates lines (commonly confused with separating lines). This is commonly escaped as \n
, abbreviated LF or NL, and has ASCII value 10
or 0x0A
. CRLF (but not CRNL) is used for the pair \r\n
.
Form feed means advance downward to the next "page". It was commonly used as page separators, but now is also used as section separators. (It's uncommonly used in source code to divide logically independent functions or groups of functions.) Text editors can use this character when you "insert a page break". This is commonly escaped as \f
, abbreviated FF, and has ASCII value 12
or 0x0C
.
As control characters, they may be interpreted in various ways.
The most common difference (and probably the only one worth worrying about) is lines end with CRLF on Windows, NL on Unix-likes, and CR on older Macs (the situation has changed with OS X to be like Unix). Note the shift in meaning from LF to NL, for the exact same character, gives the differences between Windows and Unix. (Windows is, of course, newer than Unix, so it didn't adopt this semantic shift. I don't know the history of Macs using CR.) Many text editors can read files in any of these three formats and convert between them, but not all utilities can.
Form feed is a bit more interesting (even though less commonly used directly), and with the usual definition of page separator, it can only come between lines (e.g. after the newline sequence of NL, CRLF, or CR) or at the start or end of the file.
Should this not work?
echo "LOAD_SETTLED LOAD_INIT 2011-01-13 03:50:01" | awk '{print $1}'
The simple answer is you should write code for rvalue references like you would regular references code, and you should treat them the same mentally 99% of the time. This includes all the old rules about returning references (i.e. never return a reference to a local variable).
Unless you are writing a template container class that needs to take advantage of std::forward and be able to write a generic function that takes either lvalue or rvalue references, this is more or less true.
One of the big advantages to the move constructor and move assignment is that if you define them, the compiler can use them in cases were the RVO (return value optimization) and NRVO (named return value optimization) fail to be invoked. This is pretty huge for returning expensive objects like containers & strings by value efficiently from methods.
Now where things get interesting with rvalue references, is that you can also use them as arguments to normal functions. This allows you to write containers that have overloads for both const reference (const foo& other) and rvalue reference (foo&& other). Even if the argument is too unwieldy to pass with a mere constructor call it can still be done:
std::vector vec;
for(int x=0; x<10; ++x)
{
// automatically uses rvalue reference constructor if available
// because MyCheapType is an unamed temporary variable
vec.push_back(MyCheapType(0.f));
}
std::vector vec;
for(int x=0; x<10; ++x)
{
MyExpensiveType temp(1.0, 3.0);
temp.initSomeOtherFields(malloc(5000));
// old way, passed via const reference, expensive copy
vec.push_back(temp);
// new way, passed via rvalue reference, cheap move
// just don't use temp again, not difficult in a loop like this though . . .
vec.push_back(std::move(temp));
}
The STL containers have been updated to have move overloads for nearly anything (hash key and values, vector insertion, etc), and is where you will see them the most.
You can also use them to normal functions, and if you only provide an rvalue reference argument you can force the caller to create the object and let the function do the move. This is more of an example than a really good use, but in my rendering library, I have assigned a string to all the loaded resources, so that it is easier to see what each object represents in the debugger. The interface is something like this:
TextureHandle CreateTexture(int width, int height, ETextureFormat fmt, string&& friendlyName)
{
std::unique_ptr<TextureObject> tex = D3DCreateTexture(width, height, fmt);
tex->friendlyName = std::move(friendlyName);
return tex;
}
It is a form of a 'leaky abstraction' but allows me to take advantage of the fact I had to create the string already most of the time, and avoid making yet another copying of it. This isn't exactly high-performance code but is a good example of the possibilities as people get the hang of this feature. This code actually requires that the variable either be a temporary to the call, or std::move invoked:
// move from temporary
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, string("Checkerboard"));
or
// explicit move (not going to use the variable 'str' after the create call)
string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, std::move(str));
or
// explicitly make a copy and pass the temporary of the copy down
// since we need to use str again for some reason
string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, string(str));
but this won't compile!
string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, str);
I believe you want to use DATEPART('hour', datetime)
.
Reference is here:
I had same issue after installing mariadb via HomeBrew, brew doctor
suggested to run brew link mariadb
- which fixed the issue.