just replace 'myselect' with your id
to disable->
document.getElementById("mySelect").disabled = true;
to enable->
document.getElementById("mySelect").disabled = false;
Place zero-width spaces at the points where you want to allow breaks. The zero-width space is ​
in HTML. For example:
ACTGATCG​AGCTGAAG​CGCAGTGC​GATGCTTC​GATGATGC
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
@lenooh satisfied my query. I discovered this article while searching for 'python suppress newline'. I'm using IDLE3 on Raspberry Pi to develop Python 3.2 for PuTTY. I wanted to create a progress bar on the PuTTY command line. I didn't want the page scrolling away. I wanted a horizontal line to re-assure the user from freaking out that the program hasn't cruncxed to a halt nor been sent to lunch on a merry infinite loop - as a plea to 'leave me be, I'm doing fine, but this may take some time.' interactive message - like a progress bar in text.
The print('Skimming for', search_string, '\b! .001', end='')
initializes the message by preparing for the next screen-write, which will print three backspaces as ??? rubout and then a period, wiping off '001' and extending the line of periods. After search_string
parrots user input, the \b!
trims the exclamation point of my search_string
text to back over the space which print()
otherwise forces, properly placing the punctuation. That's followed by a space and the first 'dot' of the 'progress bar' which I'm simulating. Unnecessarily, the message is also then primed with the page number (formatted to a length of three with leading zeros) to take notice from the user that progress is being processed and which will also reflect the count of periods we will later build out to the right.
import sys
page=1
search_string=input('Search for?',)
print('Skimming for', search_string, '\b! .001', end='')
sys.stdout.flush() # the print function with an end='' won't print unless forced
while page:
# some stuff…
# search, scrub, and build bulk output list[], count items,
# set done flag True
page=page+1 #done flag set in 'some_stuff'
sys.stdout.write('\b\b\b.'+format(page, '03')) #<-- here's the progress bar meat
sys.stdout.flush()
if done: #( flag alternative to break, exit or quit)
print('\nSorting', item_count, 'items')
page=0 # exits the 'while page' loop
list.sort()
for item_count in range(0, items)
print(list[item_count])
#print footers here
if not (len(list)==items):
print('#error_handler')
The progress bar meat is in the sys.stdout.write('\b\b\b.'+format(page, '03'))
line. First, to erase to the left, it backs up the cursor over the three numeric characters with the '\b\b\b' as ??? rubout and drops a new period to add to the progress bar length. Then it writes three digits of the page it has progressed to so far. Because sys.stdout.write()
waits for a full buffer or the output channel to close, the sys.stdout.flush()
forces the immediate write. sys.stdout.flush()
is built into the end of print()
which is bypassed with print(txt, end='' )
. Then the code loops through its mundane time intensive operations while it prints nothing more until it returns here to wipe three digits back, add a period and write three digits again, incremented.
The three digits wiped and rewritten is by no means necessary - it's just a flourish which exemplifies sys.stdout.write()
versus print()
. You could just as easily prime with a period and forget the three fancy backslash-b ? backspaces (of course not writing formatted page counts as well) by just printing the period bar longer by one each time through - without spaces or newlines using just the sys.stdout.write('.'); sys.stdout.flush()
pair.
Please note that the Raspberry Pi IDLE3 Python shell does not honor the backspace as ? rubout but instead prints a space, creating an apparent list of fractions instead.
—(o=8> wiz
If you only want to remove the boundary quotes:
function stripquotes(a) {
if (a.charAt(0) === '"' && a.charAt(a.length-1) === '"') {
return a.substr(1, a.length-2);
}
return a;
}
This approach won't touch the string if it doesn't look like "text in quotes"
.
None of the solutions above worked for me straight away. So I followed these steps:
pom.xml:
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
Go to Project Properties
> Java Build Path
, then remove the JRE
System Library pointing to JRE1.5
.
Force updated the project.
implements
means a behaviour will be defined for abstract
methods (except for abstract classes obviously), you define the implementation.
extends
means that a behaviour is inherited.
With interfaces it is possible to say that one interface should have that the same behaviour as another, there is not even an actual implementation. That's why it makes more sense for an interface to extends
another interface instead of implementing it.
On a side note, remember that even if an abstract
class can define abstract
methods (the sane way an interface does), it is still a class and still has to be inherited (extended) and not implemented.
You can use String#replaceAll()
with a pattern of ^\"|\"$
for this.
E.g.
string = string.replaceAll("^\"|\"$", "");
To learn more about regular expressions, have al ook at http://regular-expression.info.
That said, this smells a bit like that you're trying to invent a CSV parser. If so, I'd suggest to look around for existing libraries, such as OpenCSV.
Two lines of code is too many.
If a method has a second line of code, it is a code smell. Refactor.
Employer employer = context.Employers.First(x => x.EmployerId == 1);
context.Customers.DeleteObject(employer);
context.SaveChanges();
I have just finished updating and sending an iOS 6.0 version of one of my Apps to the store. This version is backwards compatible with iOS 5.0, thus I kept the shouldAutorotateToInterfaceOrientation:
method and added the new ones as listed below.
I had to do the following:
Autorotation is changing in iOS 6. In iOS 6, the shouldAutorotateToInterfaceOrientation:
method of UIViewController is deprecated. In its place, you should use the supportedInterfaceOrientationsForWindow:
and shouldAutorotate
methods.
Thus, I added these new methods (and kept the old for iOS 5 compatibility):
- (BOOL)shouldAutorotate {
return YES;
}
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskAllButUpsideDown;
}
viewWillLayoutSubviews
method and adjust the layout using the view’s bounds rectangle. willRotateToInterfaceOrientation:duration:
,willAnimateRotationToInterfaceOrientation:duration:
, anddidRotateFromInterfaceOrientation:
methods are no longer called on
any view controller that makes a full-screen presentation overpresentViewController:animated:completion:
.[email protected]
and the size is 640×1136. It´s also allowed to supply 640×1096 for the same portrait mode (Statusbar removed). Similar sizes may also be supplied in landscape mode if your app only allows landscape orientation on the iPhone.armv6
code has been dropped. Thus, all devices that I am able to support now (running armv7
) can be upgraded to iOS 5.That was all but just remember to test the autorotation in iOS 5 and iOS 6 because of the changes in rotation.
import numpy as np
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
array = np.random.random(10)
print(array)
# [ 0.21069679 0.61290182 0.63425412 0.84635244 0.91599191 0.00213826
# 0.17104965 0.56874386 0.57319379 0.28719469]
value = 0.5
print(find_nearest(array, value))
# 0.568743859261
I tried pretty much everything suggested in the answers above. Unfortunately, nothing worked. Then I signout out of my Github account on VS Code and signed in again. Added the remote origin with the following command.
git remote add origin https://github.com/pete/first_app.git
And it was working.
You can switch the data type to an integer:
>>> n = 5.59
>>> int(n * 10) / 10.0
5.5
>>> int(n * 10 + 0.5)
56
And then display the number by inserting the locale's decimal separator.
However, Jimmy's answer is better.
Following answer can help in this and other similar situations like synchronous AJAX call -
Working example
waitForMe().then(function(intentsArr){
console.log('Finally, I can execute!!!');
},
function(err){
console.log('This is error message.');
})
function waitForMe(){
// Returns promise
console.log('Inside waitForMe');
return new Promise(function(resolve, reject){
if(true){ // Try changing to 'false'
setTimeout(function(){
console.log('waitForMe\'s function succeeded');
resolve();
}, 2500);
}
else{
setTimeout(function(){
console.log('waitForMe\'s else block failed');
resolve();
}, 2500);
}
});
}
Another way to do is to use the str.rpartition(sep)
method.
For example:
filename = '/home/user/somefile.txt'
(prefix, sep, suffix) = filename.rpartition('.')
new_filename = prefix + '.jpg'
print new_filename
We can use setProperty or cssText to add !important
to a DOM element using JavaScript.
Example 1:
elem.style.setProperty ("color", "green", "important");
Example 2:
elem.style.cssText='color: red !important;'
You're probably setting a value for a key in the alertView, which is not allowed. The key is in this case LoginScreen
. I don't see any call to setValue()
, so I assume it's somewhere else in the code.
With your ANDs you shouldn't have a FALSE value -2, until right at the end, e.g. with just 2 ANDs
=IF(AND(E2="In Play",F2="Closed"),3,IF(AND(E2="In Play",F2=" Suspended"),3,-2))
although it might be better with a combination of nested IFs and ANDs - try like this for the full formula:[Edited - thanks David]
=IF(E2="In Play",IF(F2="Closed",3,IF(F2="Suspended",2,IF(F2="Null",1))),IF(AND(E2="Pre-play",F2="Null"),-1,IF(AND(E2="Completed",F2="Closed"),2,IF(AND(E2="Pre-play",F2="Null"),3,-2))))
To avoid a long formula like the above you could create a table with all E2 possibilities in a column like K2:K5 and all F2 possibilities in a row like L1:N1 then fill in the required results in L2:N5 and use this formula
=INDEX($L$2:$N$5,MATCH(E2,$K$2:$K$5,0),MATCH(F2,$L$1:$N$1,0))
In the new 2013 book named "Functional Programming Patterns- in Scala and Clojure" the author Michael.B. Linn does a decent job comparing and providing replacements in many cases for the GoF patterns and also discusses the newer functional patterns like 'tail recursion', 'memoization', 'lazy sequence', etc.
This book is available on Amazon. I found it very informative and encouraging when coming from an OO background of a couple of decades.
<?php
$conn = mysql_connect ("localhost:3306","root","");
$db = mysql_select_db ("database_name", $conn);
if(!$db) {
echo mysql_error();
}
$q = "SELECT image FROM table_name where id=4";
$r = mysql_query ("$q",$conn);
if($r) {
while($row = mysql_fetch_array($r)) {
header ("Content-type: image/jpeg");
echo $row ["image"];
}
}else{
echo mysql_error();
}
?>
sometimes problem may occures because of port number of mysql server is incoreect to avoid it just write port number with host name like this "localhost:3306"
in case if you have installed two mysql servers on same system then write port according to that
in order to display any data from database please make sure following steps
1.proper connection with sql
2.select database
3.write query
4.write correct table name inside the query
5.and last is traverse through data
TLDR:
CREATE TABLE MyTable(
a int NOT NULL
,b smallint NOT NULL index IX_indexName nonclustered
,c smallint NOT NULL
,d smallint NOT NULL
,e smallint NOT NULL
)
Details
As per T-SQL CREATE TABLE documentation, in 2014 the column definition supports defining an index:
<column_definition> ::=
column_name <data_type>
...
[ <column_index> ]
and <column_index> grammar is defined as:
<column_index> ::=
INDEX index_name [ CLUSTERED | NONCLUSTERED ]
[ WITH ( <index_option> [ ,... n ] ) ]
[ ON { partition_scheme_name (column_name )
| filegroup_name
| default
}
]
[ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]
So a lot of what you can do as a separate statement can be done inline. I noticed include
is not an option in this grammar so some things are not possible.
CREATE TABLE MyTable(
a int NOT NULL
,b smallint NOT NULL index IX_indexName nonclustered
,c smallint NOT NULL
,d smallint NOT NULL
,e smallint NOT NULL
)
You can also have inline indexes defined as another line after columns, but within the create table statement, and this allows multiple columns in the index, but still no include
clause:
< table_index > ::=
{
{
INDEX index_name [ CLUSTERED | NONCLUSTERED ]
(column_name [ ASC | DESC ] [ ,... n ] )
| INDEX index_name CLUSTERED COLUMNSTORE
| INDEX index_name [ NONCLUSTERED ] COLUMNSTORE (column_name [ ,... n ] )
}
[ WITH ( <index_option> [ ,... n ] ) ]
[ ON { partition_scheme_name (column_name )
| filegroup_name
| default
}
]
[ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]
}
For example here we add an index on both columns c and d:
CREATE TABLE MyTable(
a int NOT NULL
,b smallint NOT NULL index IX_MyTable_b nonclustered
,c smallint NOT NULL
,d smallint NOT NULL
,e smallint NOT NULL
,index IX_MyTable_c_d nonclustered (c,d)
)
One obvious solution would be to use javascript (which is not JSF). To implement this by JSF you should use AJAX. In this example, I use a radio button group to show and hide two set of components. In the back bean, I define a boolean switch.
private boolean switchComponents;
public boolean isSwitchComponents() {
return switchComponents;
}
public void setSwitchComponents(boolean switchComponents) {
this.switchComponents = switchComponents;
}
When the switch is true, one set of components will be shown and when it is false the other set will be shown.
<h:selectOneRadio value="#{backbean.switchValue}">
<f:selectItem itemLabel="showComponentSetOne" itemValue='true'/>
<f:selectItem itemLabel="showComponentSetTwo" itemValue='false'/>
<f:ajax event="change" execute="@this" render="componentsRoot"/>
</h:selectOneRadio>
<H:panelGroup id="componentsRoot">
<h:panelGroup rendered="#{backbean.switchValue}">
<!--switchValue to be shown on switch value == true-->
</h:panelGroup>
<h:panelGroup rendered="#{!backbean.switchValue}">
<!--switchValue to be shown on switch value == false-->
</h:panelGroup>
</H:panelGroup>
Note: on the ajax event we render components root. because components which are not rendered in the first place can't be re-rendered on the ajax event.
Also, note that if the "componentsRoot" and radio buttons are under different component hierarchy. you should reference it from the root (form root).
Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")
Or, in a more structured way...
Sub openwb()
Dim sPath As String, sFile As String
Dim wb As Workbook
sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"
Set wb = Workbooks.Open(sFile)
End Sub
Although this is an old document, but it helped me resolve the problem of 'HintPath' being ignored on another machine. It was because the referenced DLL needed to be in source control as well:
Excerpt:
To include and then reference an outer-system assembly 1. In Solution Explorer, right-click the project that needs to reference the assembly,,and then click Add Existing Item. 2. Browse to the assembly, and then click OK. The assembly is then copied into the project folder and automatically added to VSS (assuming the project is already under source control). 3. Use the Browse button in the Add Reference dialog box to set a file reference to assembly in the project folder.
Using CSS, you set the logo div to position absolute, and set the z-order to be above the second div.
#logo
{
position: absolute:
z-index: 2000;
left: 100px;
width: 100px;
height: 50px;
}
<?php
$edit_post = add_query_arg('c', '123', 'news' );
?>
<a href="<?php echo $edit_post; ?>">Go to New page</a>
You can add any page inplace of "news".
It's as simple as:
>>> lists = [[1, 2], [3, 4]]
>>> np.array(lists)
array([[1, 2],
[3, 4]])
protected void btnExportExcel_Click(object sender, EventArgs e)
{
DataTable _datatable = new DataTable();
for (int i = 0; i < grdReport.Columns.Count; i++)
{
_datatable.Columns.Add(grdReport.Columns[i].ToString());
}
foreach (GridViewRow row in grdReport.Rows)
{
DataRow dr = _datatable.NewRow();
for (int j = 0; j < grdReport.Columns.Count; j++)
{
if (!row.Cells[j].Text.Equals(" "))
dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
}
_datatable.Rows.Add(dr);
}
ExportDataTableToExcel(_datatable);
}
I wrote a little script based on Florian's answer that uses nano (my favorite editor):
#!/bin/sh
if [ "$#" -ne 3 ]; then
echo "Usage: $0 hugeFilePath startLine endLine" >&2
exit 1
fi
sed -n -e $2','$3'p' -e $3'q' $1 > hfnano_temporary_file
nano hfnano_temporary_file
(head -n `expr $2 - 1` $1; cat hfnano_temporary_file; sed -e '1,'$3'd' $1) > hfnano_temporary_file2
cat hfnano_temporary_file2 > $1
rm hfnano_temporary_file hfnano_temporary_file2
Use it like this:
sh hfnano yourHugeFile 3 8
In that example, nano will open up lines 3 through 8, you can edit them, and when you save and quit, those lines in the hugefile will automatically be overwritten with your saved lines.
It's actually pretty easy. Let's say we have this in our JavaVirtualMachines folder:
Imagine that 1.8 is our default, then we just add a new folder (for example 'old') and move the default jdk folder to that new folder.
Do java -version
again et voila, 1.7!
The missing reference is the System.Net.Http.Formatting.dll
. But the better solution is to add the NuGet package Microsoft.AspNet.WebApi.Client
to ensure the version of the formatting dll worked with the .NET framework version of System.Net.Http
in my project.
So Amandu's answer mostly works. Using it in the wild, however, I ran into some issues, where things that I would have expected to get found were not getting found. This was because sometimes there is random white space surrounding the element's text. It is my belief that if you're searching for "Hello World", you would still want it to match " Hello World ", or even "Hello World \n". Thus, I just added the "trim()" method to the function, which removes surrounding whitespace, and it started to work better.
Specifically...
$.expr[':'].textEquals = function(el, i, m) {
var searchText = m[3];
var match = $(el).text().trim().match("^" + searchText + "$")
return match && match.length > 0;
}
Also, note, this answer is extremely similar to Select link by text (exact match)
And secondary note... trim
only removes whitespace before and after the searched text. It does not remove whitespace in the middle of the words. I believe this is desirable behavior, but you could change that if you wanted.
Judging by the declaration and description of the startsWith
Java function, the "most straight forward way" to implement it in VBA would either be with Left
:
Public Function startsWith(str As String, prefix As String) As Boolean
startsWith = Left(str, Len(prefix)) = prefix
End Function
Or, if you want to have the offset parameter available, with Mid
:
Public Function startsWith(str As String, prefix As String, Optional toffset As Integer = 0) As Boolean
startsWith = Mid(str, toffset + 1, Len(prefix)) = prefix
End Function
Visual Basic, C#, and C++ all have syntax for accessing the Item property without using its name. Instead, the variable containing the List is used as if it were an array.
List[index]
See for instance: https://msdn.microsoft.com/en-us/library/0ebtbkkc(v=vs.110).aspx
The basic idea of using ICollection
is a provide an interface to readonly-access to some finite amount of data. In fact you have a ICollection.Count property. IEnumerable
is more suitable for some chain of the data where you read till some logical point, some condition esplicitly specified by consumer or till the end of the enumeration.
Use Array list http://developer.android.com/reference/java/util/ArrayList.html
Kind of a hack because it's not really python doing anything special here, but if you run the export command in the same sub-shell, you will probably get the result you want.
import os
cmd = "export MY_DATA='1234'; echo $MY_DATA" # or whatever command
os.system(cmd)
Just simply write BETWEEN '{$startDate}' AND '{$endDate}' in where condition as
->where("date BETWEEN '{$startDate}' AND '{$endDate}'")
This is the way I got the solution. Simple and Sweet. Independent of Screen density:
export default class AwesomeProject extends Component {
constructor(props){
super(props);
this.state = {text: ""}
}
render() {
return (
<View
style={{
flex: 1,
backgroundColor: "#ececec",
flexDirection: "column",
justifyContent: "center",
alignItems: "center"
}}
>
<View style={{ padding: 10, flexDirection: "row" }}>
<TextInput
style={{ flex: 0.8, height: 40, borderWidth: 1 }}
onChangeText={text => this.setState({ text })}
placeholder="Text 1"
value={this.state.text}
/>
</View>
<View style={{ padding: 10, flexDirection: "row" }}>
<TextInput
style={{ flex: 0.8, height: 40, borderWidth: 1 }}
onChangeText={text => this.setState({ text })}
placeholder="Text 2"
value={this.state.text}
/>
</View>
<View style={{ padding: 10, flexDirection: "row" }}>
<Button
onPress={onButtonPress}
title="Press Me"
accessibilityLabel="See an Information"
/>
</View>
</View>
);
}
}
TL;DR
Error #1064 means that MySQL can't understand your command. To fix it:
Read the error message. It tells you exactly where in your command MySQL got confused.
Examine your command. If you use a programming language to create your command, use
echo
,console.log()
, or its equivalent to show the entire command so you can see it.Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.
Check for reserved words. If the error occurred on an object identifier, check that it isn't a reserved word (and, if it is, ensure that it's properly quoted).
Error messages may look like gobbledygook, but they're (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.
As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.
Whilst "syntax" is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.
For example, the following English sentence contains a syntax error (because the indefinite article "a" must always precede a noun):
This sentence contains syntax error a.
Whenever one issues a command to a computer, one of the very first things that it must do is "parse" that command in order to make sense of it. A "syntax error" means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.
It's important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.
Obviously, one needs to determine how it is that the command violates MySQL's grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…
MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:
UPDATE my_table WHERE id=101 SET name='foo'
That command yields the following error message:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id=101 SET name='foo'' at line 1
MySQL is telling us that everything seemed fine up to the word WHERE
, but then a problem was encountered. In other words, it wasn't expecting to encounter WHERE
at that point.
Messages that say ...near '' at line...
simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.
Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:
$result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
If you write this this in two lines
$query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
$result = $mysqli->query($query);
then you can add echo $query;
or var_dump($query)
to see that the query actually says
UPDATE userSET name='foo' WHERE id=101
Often you'll see your error immediately and be able to fix it.
MySQL is also recommending that we "check the manual that corresponds to our MySQL version for the right syntax to use". Let's do that.
I'm using MySQL v5.6, so I'll turn to that version's manual entry for an UPDATE
command. The very first thing on the page is the command's grammar (this is true for every command):
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it's enough to recognise that: clauses contained within square brackets [
and ]
are optional; vertical bars |
indicate alternatives; and ellipses ...
denote either an omission for brevity, or that the preceding clause may be repeated.
We already know that the parser believed everything in our command was okay prior to the WHERE
keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference
must be followed by the SET
keyword: whereas in our command it was actually followed by the WHERE
keyword. This explains why the parser reports that a problem was encountered at that point.
Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual's description of what was expected at that point), virtually every syntax error can be readily identified.
I say "virtually all", because there's a small class of problems that aren't quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:
UPDATE my_table SET where='foo'
Again, the parser does not expect to encounter WHERE
at this point and so will raise a similar syntax error—but you hadn't intended for that where
to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.
[ deletia ]The identifier quote character is the backtick (“
`
”):mysql> SELECT * FROM `select` WHERE `select`.id > 100;
If the
ANSI_QUOTES
SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:mysql> CREATE TABLE "test" (col INT); ERROR 1064: You have an error in your SQL syntax... mysql> SET sql_mode='ANSI_QUOTES'; mysql> CREATE TABLE "test" (col INT); Query OK, 0 rows affected (0.00 sec)
Leave off the quotes
$cmd &
$othercmd &
eg:
nicholas@nick-win7 /tmp
$ cat test
#!/bin/bash
cmd="ls -la"
$cmd &
nicholas@nick-win7 /tmp
$ ./test
nicholas@nick-win7 /tmp
$ total 6
drwxrwxrwt+ 1 nicholas root 0 2010-09-10 20:44 .
drwxr-xr-x+ 1 nicholas root 4096 2010-09-10 14:40 ..
-rwxrwxrwx 1 nicholas None 35 2010-09-10 20:44 test
-rwxr-xr-x 1 nicholas None 41 2010-09-10 20:43 test~
1.If it shows error (shutting down with code 100) that means it is not finding the desired location of file.
1.a If its before macOS Catalina then create directory with
sudo mkdir -p /data/db and give permissions to use it
sudo chown -R id -un
/data/db.
1.b if it macOS Catalina onwards then make
sudo mkdir -p /System/Volumes/data/db and give it
permissions
sudo chown -R id -un
/System/Volumes/data/db.
2.Starting mongo db brew services run mongodb-community
3.Type mongod or mongod --dbpath /System/Volumes/Data/data/db
4.And if the mongod show error (shutting down with code 48) that
means the port is being already use so you can do two things
4.a Either you change the port of mongod by specifying port
number
mongod --dbpath /System/Volumes/Data/data/db —port 27018.
4.b Or You can kill the process at that port by finding
the process by
sudo lsof -i :27017
and then kill by command
kill -9
5.Repeat the step 2 and 3.
I have been waiting to see if Google would open a Keep API. When I discovered Google Tasks, and saw that it had an Android app, web app, and API, I converted over to Tasks. This may not directly answer your question, but it is my solution to the Keep API problem.
Tasks doesn't have a reminder alarm exactly like Keep. I can live without that if I also connect with the Calendar API.
.section {
display: flex;
}
.element-left {
width: 94%;
}
.element-right {
flex-grow: 1;
}
_x000D_
<div class="section">
<div id="dB" class="element-left" }>
<a href="http://notareallink.com" title="Download" id="buyButton">Download</a>
</div>
<div id="gB" class="element-right">
<a href="#" title="Gallery" onclick="$j('#galleryDiv').toggle('slow');return false;" id="galleryButton">Gallery</a>
</div>
</div>
_x000D_
or
.section {
display: flex;
flex-wrap: wrap;
}
.element-left {
flex: 2;
}
.element-right {
width: 100px;
}
_x000D_
<div class="section">
<div id="dB" class="element-left" }>
<a href="http://notareallink.com" title="Download" id="buyButton">Download</a>
</div>
<div id="gB" class="element-right">
<a href="#" title="Gallery" onclick="$j('#galleryDiv').toggle('slow');return false;" id="galleryButton">Gallery</a>
</div>
</div>
_x000D_
You can do this a couple of ways.
Via the "Solution Explorer"
Via the "Package Manager Console"
Install-Package Newtonsoft.Json
For more info on how to use the "Package Manager Console" check out the nuget docs.
As jzd says, you can use System.currentTimeMillis
. If you need it in a Date
object but don't want to create a new Date
object, you can use Date.setTime
to reuse an existing Date
object. Personally I hate the fact that Date
is mutable, but maybe it's useful to you in this particular case. Similarly, Calendar
has a setTimeInMillis
method.
If possible though, it would probably be better just to keep it as a long
. If you only need a timestamp, effectively, then that would be the best approach.
`$Color = array('A' => 'Blue', 'B' => 'Green', 'c' => 'Red');
$strtolower = array_map('strtolower', $Color);
$strtoupper = array_map('strtoupper', $Color);
print_r($strtolower); print_r($strtoupper);`
This Code in MapsActivity
Class works for me :
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
public void centreMapOnLocation(Location location, String title){
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,12));
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
centreMapOnLocation(lastKnownLocation,"Your Location");
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Intent intent = getIntent();
if (intent.getIntExtra("Place Number",0) == 0 ){
// Zoom into users location
locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
centreMapOnLocation(location,"Your Location");
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
centreMapOnLocation(lastKnownLocation,"Your Location");
} else {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
}
}
}
Before using the $result
variable, you should use $row = mysqli_fetch_array($result)
or mysqli_fetch_assoc()
functions.
Like this:
$row = mysqli_fetch_array($result);
and use the $row
array as you need.
The ALL_DIRECTORIES
data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
I'm surprised why no one suggested to use the WinForms Textbox.
XAML:
<WindowsFormsHost Margin="10" Width="70">
<wf:TextBox x:Name="textbox1"/>
</WindowsFormsHost>
Also don't forget the Winforms Namespace:
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
C#:
AutoCompleteStringCollection stringCollection = new AutoCompleteStringCollection(){"String 1", "String 2", "etc..."};
textbox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textbox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
textbox1.AutoCompleteCustomSource = stringCollection;
With Autocomplete, you need to do it in the Code behind, because for some reasons, others might can explain, it throws an exception.
step 1: run this script
SET FOREIGN_KEY_CHECKS=0;
step 2: add column
ALTER TABLE mileage_unit ADD COLUMN COMPANY_ID BIGINT(20) NOT NULL
step 3: add foreign key to the added column
ALTER TABLE mileage_unit
ADD FOREIGN KEY (COMPANY_ID) REFERENCES company_mst(COMPANY_ID);
step 4: run this script
SET FOREIGN_KEY_CHECKS=1;
update ubuntu:
sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev
Install rvm, which manages the ruby versions:
to install rvm use the following command.
\curl -sSL https://get.rvm.io | bash -s stable
source ~/.bash_profile
rvm install ruby-2.1.4
Check ruby versions installed and in use:
rvm list
rvm use --default ruby-2.1.4
This is what I usually do ,please refer my function below :
This function can extract first number occurance from any string you can modify and use this function according to your usage
public static int GetFirstNumber(this string strInsput)
{
int number = 0;
string strNumber = "";
bool bIsContNo = true;
bool bNoOccued = false;
try
{
var arry = strInsput.ToCharArray(0, strInsput.Length - 1);
foreach (char item in arry)
{
if (char.IsNumber(item))
{
strNumber = strNumber + item.ToString();
bIsContNo = true;
bNoOccued = true;
}
else
{
bIsContNo = false;
}
if (bNoOccued && !bIsContNo)
{
break;
}
}
number = Convert.ToInt32(strNumber);
}
catch (Exception ex)
{
return 0;
}
return number;
}
import React from 'react';
import {sendFormData} from '../services/';
class Signup extends React.Component{
constructor(props){
super(props);
this.state = {
isDisabled:true
}
this.submitForm = this.submitForm.bind(this);
}
validateEmail(email){
const pattern = /[a-zA-Z0-9]+[\.]?([a-zA-Z0-9]+)?[\@][a-z]{3,9}[\.][a-z]{2,5}/g;
const result = pattern.test(email);
if(result===true){
this.setState({
emailError:false,
email:email
})
} else{
this.setState({
emailError:true
})
}
}
handleChange(e){
const target = e.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
if(e.target.name==='firstname'){
if(e.target.value==='' || e.target.value===null ){
this.setState({
firstnameError:true
})
} else {
this.setState({
firstnameError:false,
firstName:e.target.value
})
}
}
if(e.target.name==='lastname'){
if(e.target.value==='' || e.target.value===null){
this.setState({
lastnameError:true
})
} else {
this.setState({
lastnameError:false,
lastName:e.target.value
})
}
}
if(e.target.name==='email'){
this.validateEmail(e.target.value);
}
if(e.target.name==='password'){
if(e.target.value==='' || e.target.value===null){
this.setState({
passwordError:true
})
} else {
this.setState({
passwordError:false,
password:e.target.value
})
}
}
if(this.state.firstnameError===false && this.state.lastnameError===false &&
this.state.emailError===false && this.state.passwordError===false){
this.setState({
isDisabled:false
})
}
}
submitForm(e){
e.preventDefault();
const data = {
firstName: this.state.firstName,
lastName: this.state.lastName,
email: this.state.email,
password: this.state.password
}
sendFormData(data).then(res=>{
if(res.status===200){
alert(res.data);
this.props.history.push('/');
}else{
}
});
}
render(){
return(
<div className="container">
<div className="card card-login mx-auto mt-5">
<div className="card-header">Register here</div>
<div className="card-body">
<form id="signup-form">
<div className="form-group">
<div className="form-label-group">
<input type="text" id="firstname" name="firstname" className="form-control" placeholder="Enter firstname" onChange={(e)=>{this.handleChange(e)}} />
<label htmlFor="firstname">firstname</label>
{this.state.firstnameError ? <span style={{color: "red"}}>Please Enter some value</span> : ''}
</div>
</div>
<div className="form-group">
<div className="form-label-group">
<input type="text" id="lastname" name="lastname" className="form-control" placeholder="Enter lastname" onChange={(e)=>{this.handleChange(e)}} />
<label htmlFor="lastname">lastname</label>
{this.state.lastnameError ? <span style={{color: "red"}}>Please Enter some value</span> : ''}
</div>
</div>
<div className="form-group">
<div className="form-label-group">
<input type="email" id="email" name="email" className="form-control" placeholder="Enter your email" onChange={(e)=>{this.handleChange(e)}} />
<label htmlFor="email">email</label>
{this.state.emailError ? <span style={{color: "red"}}>Please Enter valid email address</span> : ''}
</div>
</div>
<div className="form-group">
<div className="form-label-group">
<input type="password" id="password" name="password" className="form-control" placeholder="Password" onChange={(e)=>{this.handleChange(e)}} />
<label htmlFor="password">Password</label>
{this.state.passwordError ? <span style={{color: "red"}}>Please enter some value</span> : ''}
</div>
</div>
<button className="btn btn-primary btn-block" disabled={this.state.isDisabled} onClick={this.submitForm}>Signup</button>
</form>
</div>
</div>
</div>
);
}
}
export default Signup;
<select>
<option disabled selected>select your beverage</option>
<option >Tea</option>
<option>coffee</option>
<option>soda</option>
</select>
Wouldn't establishing a connection to the database do this for you? If the database isn't up you won't be able to establish a connection.
I prefer to use the following command:
:set fileformat=unix
You can also use mac
or dos
to respectively convert your file to Mac or MS-DOS/Windows file convention. And it does nothing if the file is already in the correct format.
For more information, see the Vim help:
:help fileformat
if you want filename only :
for file in /home/user/*; do
f=$(echo "${file##*/}");
filename=$(echo $f| cut -d'.' -f 1); #file has extension, it return only filename
echo $filename
done
for more information about cut
command see here.
Android Studio 2.2.3 Linux Mint 18.1
Inside your 'project view' open Gradle Scripts -> build.gradle(Module:app) and put your mouse pointer inside the word dependencies.
Click on the light bulb and click "add library dependency" and for me all the libraries I wanted were listed there.
example libraries that came up for me: compile 'com.android.support:gridlayout-v7:25.1.0' compile 'com.android.support:support-v13:25.1.0'
I am now looking to add android support by default in Gradles default configuration.
Rabin-Miller is a standard probabilistic primality test. (you run it K times and the input number is either definitely composite, or it is probably prime with probability of error 4-K. (a few hundred iterations and it's almost certainly telling you the truth)
There is a non-probabilistic (deterministic) variant of Rabin Miller.
The Great Internet Mersenne Prime Search (GIMPS) which has found the world's record for largest proven prime (274,207,281 - 1 as of June 2017), uses several algorithms, but these are primes in special forms. However the GIMPS page above does include some general deterministic primality tests. They appear to indicate that which algorithm is "fastest" depends upon the size of the number to be tested. If your number fits in 64 bits then you probably shouldn't use a method intended to work on primes of several million digits.
It can be a mathematical convention in the definition of an interval where square brackets mean "extremal inclusive" and round brackets "extremal exclusive".
private readonly UserManager<AppUser> _userManager;
public AccountsController(UserManager<AppUser> userManager)
{
_userManager = userManager;
}
[Authorize(Policy = "ApiUser")]
[HttpGet("api/accounts/GetProfile", Name = "GetProfile")]
public async Task<IActionResult> GetProfile()
{
var userId = ((ClaimsIdentity)User.Identity).FindFirst("Id").Value;
var user = await _userManager.FindByIdAsync(userId);
ProfileUpdateModel model = new ProfileUpdateModel();
model.Email = user.Email;
model.FirstName = user.FirstName;
model.LastName = user.LastName;
model.PhoneNumber = user.PhoneNumber;
return new OkObjectResult(model);
}
I had trouble with ll of the above, including the approved answer. I converted Hardy's category back into a method since all i wanted was to rotate an image. Here's the code and usage:
- (UIImage *)imageRotatedByDegrees:(UIImage*)oldImage deg:(CGFloat)degrees{
// calculate the size of the rotated view's containing box for our drawing space
UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,oldImage.size.width, oldImage.size.height)];
CGAffineTransform t = CGAffineTransformMakeRotation(degrees * M_PI / 180);
rotatedViewBox.transform = t;
CGSize rotatedSize = rotatedViewBox.frame.size;
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize);
CGContextRef bitmap = UIGraphicsGetCurrentContext();
// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
// // Rotate the image context
CGContextRotateCTM(bitmap, (degrees * M_PI / 180));
// Now, draw the rotated/scaled image into the context
CGContextScaleCTM(bitmap, 1.0, -1.0);
CGContextDrawImage(bitmap, CGRectMake(-oldImage.size.width / 2, -oldImage.size.height / 2, oldImage.size.width, oldImage.size.height), [oldImage CGImage]);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
And the usage:
UIImage *image2 = [self imageRotatedByDegrees:image deg:90];
Thanks Hardy!
git commit -m "first commit"
git remote add origin <linkyourrepository>
git push -u origin master
will works!
Not sure why nobody has mentioned this...but I was doing exactly what you were doing in my viewDidLoad
...and it wasn't working. Then I placed my code into viewWillAppear
and it all worked.
The above solution is to change a single barbuttonItem. If you want to change the color for every navigationBar in your code then follow this answer.
Basically changing onto the class itself using appearance()
is like making a global change on all instances of that view in your app. For more see here
Just crop the string:
var date = new Date("2013-03-10T02:00:00Z");
date.toISOString().substring(0, 10);
Or if you need only date out of string.
var strDate = "2013-03-10T02:00:00Z";
strDate.substring(0, 10);
HashMap supports both null
keys and values
http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
... and permits null values and the null key
So your problem is probably not the map itself.
Sometimes you still need to know if Cookie exists in Response. Then you can check if cookie key exists:
HttpContext.Current.Response.Cookies.AllKeys.Contains("myCookie")
More info can be found here.
In my case I had to modify Response Cookie in Application_EndRequest method in Global.asax. If Cookie doesn't exist I don't touch it:
string name = "myCookie";
HttpContext context = ((HttpApplication)sender).Context;
HttpCookie cookie = null;
if (context.Response.Cookies.AllKeys.Contains(name))
{
cookie = context.Response.Cookies[name];
}
if (cookie != null)
{
// update response cookie
}
I don't see any problem with that. Pre-ARC, I've always made my IBOutlets assign
, as they're already retained by their superviews. If you make them weak
, you shouldn't have to nil them out in viewDidUnload, as you point out.
One caveat: You can support iOS 4.x in an ARC project, but if you do, you can't use weak
, so you'd have to make them assign
, in which case you'd still want to nil the reference in viewDidUnload
to avoid a dangling pointer. Here's an example of a dangling pointer bug I've experienced:
A UIViewController has a UITextField for zip code. It uses CLLocationManager to reverse geocode the user's location and set the zip code. Here's the delegate callback:
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
Class geocoderClass = NSClassFromString(@"CLGeocoder");
if (geocoderClass && IsEmpty(self.zip.text)) {
id geocoder = [[geocoderClass alloc] init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if (self.zip && IsEmpty(self.zip.text)) {
self.zip.text = [[placemarks objectAtIndex:0] postalCode];
}
}];
}
[self.locationManager stopUpdatingLocation];
}
I found that if I dismissed this view at the right time and didn't nil self.zip in viewDidUnload
, the delegate callback could throw a bad access exception on self.zip.text.
Be sure to checkout the branch you want to merge first and then pull it (so your local version matches the remote version).
Then checkout back to your branch you want to do the merge on and your git merge should work.
Find the stable version of the hibernate plugin (Zip or URL for auto update) in the below URL. http://www.jboss.org/tools/download
Do not install everything though. You just need:
That's all!
In 2013, you will be probably using the latest versions of Eclipse and Hibernate. For Eclipse-4.2.2. and JBoss Tools 4.0 you need:
Then you are ready to go!
This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.
There's no need for a parent POM.
You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.
To do it on the build server, just pass to the mvn
command:
-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases
See https://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html for details which options can be set.
It's also possible to set this in your settings.xml
.
Just create a profile there which is enabled and contains the property.
Example settings.xml:
<settings>
[...]
<profiles>
<profile>
<id>nexus</id>
<properties>
<altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
<altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
</properties>
</profile>
</profiles>
<activeProfiles>
<activeProfile>nexus</activeProfile>
</activeProfiles>
</settings>
Make sure that credentials for "snapshots" and "releases" are in the <servers>
section of your settings.xml
The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message
Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter
To fix this, you can enforce a newer version of the plug-in:
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8</version>
</plugin>
</plugins>
</pluginManagement>
</build>
In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.
The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.
DECLARE
PROD_ROW_ID VARCHAR (10) := NULL;
VIS_ROW_ID NUMBER;
DSC VARCHAR (512);
BEGIN
SELECT ROW_ID
INTO VIS_ROW_ID
FROM SIEBEL.S_PROD_INT
WHERE PART_NUM = 'S0146404';
BEGIN
SELECT RTRIM (VIS.SERIAL_NUM)
|| ','
|| RTRIM (PLANID.DESC_TEXT)
|| ','
|| CASE
WHEN PLANID.HIGH = 'TEST123'
THEN
CASE
WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
THEN
'Y'
ELSE
'N'
END
ELSE
'N'
END
|| ','
|| 'GB'
|| ','
|| RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
INTO DSC
FROM SIEBEL.S_LST_OF_VAL PLANID
INNER JOIN SIEBEL.S_PROD_INT PROD
ON PROD.PART_NUM = PLANID.VAL
INNER JOIN SIEBEL.S_ASSET NETFLIX
ON PROD.PROD_ID = PROD.ROW_ID
INNER JOIN SIEBEL.S_ASSET VIS
ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
INNER JOIN SIEBEL.S_PROD_INT VISPROD
ON VIS.PROD_ID = VISPROD.ROW_ID
WHERE PLANID.TYPE = 'Test Plan'
AND PLANID.ACTIVE_FLG = 'Y'
AND VISPROD.PART_NUM = VIS_ROW_ID
AND PROD.STATUS_CD = 'Active'
AND VIS.SERIAL_NUM IS NOT NULL;
END;
END;
/
References
http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/
Just check in you projects properties >build ->packaging WAR file compress.
but layer 02, will cover all drawings in layer 01. I used this to show drawing in both layers. use (background-color: transparent;) in style.
<div style="position: relative;"> _x000D_
<canvas id="lay01" width="500" height="500" style="position: absolute; left: 0; top: 0; z-index: 0; background-color: transparent;">_x000D_
</canvas> _x000D_
<canvas id="lay02" width="500" height="500" style="position: absolute; left: 0; top: 0; z-index: 1; background-color: transparent;">_x000D_
</canvas>_x000D_
</div>
_x000D_
In Eclipse, you don't need to change JAVA_HOME, you just need to change the run configuration for Maven to something above 1.6 (even if your project is on Java 6, Maven shouldn't be). Right-click the project, choose Maven Build or Run As > Run Configurations and set the correct JDK version.
This is a weird approach but it worked for me(MacOs HighSierra 10.13.3). Install CLion. It comes with gdb. Once run the gdb using Terminal. Copy the gdb program to your usr/local/bin/. No problem of signin, sudo etc.
I had faced same issues, I refined apache2 virtual host entery and got success.
Note: on server I had succesful installed and working on 9001 port without any issue. This guide line for apache2 only no relavence with nginx, this answer for apache2+etherpad lovers.
<VirtualHost *:80>
ServerName pad.tejastank.com
ServerAlias pad.tejastank.com
ServerAdmin [email protected]
LoadModule proxy_module /usr/lib/apache2/modules/mod_proxy.so
LoadModule proxy_http_module /usr/lib/apache2/modules/mod_proxy_http.so
LoadModule headers_module /usr/lib/apache2/modules/mod_headers.so
LoadModule deflate_module /usr/lib/apache2/modules/mod_deflate.so
ProxyVia On
ProxyRequests Off
ProxyPreserveHost on
<Location />
ProxyPass http://localhost:9001/ retry=0 timeout=30
ProxyPassReverse http://localhost:9001/
</Location>
<Location /socket.io>
# This is needed to handle the websocket transport through the proxy, since
# etherpad does not use a specific sub-folder, such as /ws/ to handle this kind of traffic.
# Taken from https://github.com/ether/etherpad-lite/issues/2318#issuecomment-63548542
# Thanks to beaugunderson for the semantics
RewriteEngine On
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule /(.*) ws://localhost:9001/socket.io/$1 [P,L]
ProxyPass http://localhost:9001/socket.io retry=0 timeout=30
ProxyPassReverse http://localhost:9001/socket.io
</Location>
<Proxy *>
Options FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Proxy>
</VirtualHost>
Advance tips: Please with help of a2enmod enable all mod of apache2
Restart apache2 than will get effect. But obvious a2ensite to enable site required.
On client:
axios.get('/api', {
params: {
foo: 'bar'
}
});
On server:
function get(req, res, next) {
let param = req.query.foo
.....
}
I used this code to show the dialog at the bottom of the screen:
Dialog dlg = <code to create custom dialog>;
Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);
This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about
private void showPictureialog() {
final Dialog dialog = new Dialog(this,
android.R.style.Theme_Translucent_NoTitleBar);
// Setting dialogview
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
dialog.setTitle(null);
dialog.setContentView(R.layout.selectpic_dialog);
dialog.setCancelable(true);
dialog.show();
}
you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment
I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).
If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::
.
Something along these lines:
create view view1
as
select table1.col1,table2.col1,table3.col3
from table1
inner join
table2
inner join
table3
on
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;
Notice the varchar
typecasting on the table1.col4.
Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.
Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).
If you can make an approximation of the number of items that will be there at the end, use the overload of the List constuctor that takes count as a parameter. You will save some expensive List duplications. Otherwise you have to pay for it.
In my case i never put return inside a arrow function so my code is follow
`<ProductConsumer>
{(myvariable)=>{
return <h1>{myvariable}</h1>
}}
</ProductConsumer> `
MySQLi stands for MySQL improved. It's an object-oriented interface to the MySQL bindings which makes things easier to use. It also offers support for prepared statements (which are very useful). If you're on PHP 5 use MySQLi.
If you like doing things the hard way:
my (undef,undef,undef,$mday,$mon,$year) = localtime;
$year = $year+1900;
$mon += 1;
if (length($mon) == 1) {$mon = "0$mon";}
if (length($mday) == 1) {$mday = "0$mday";}
my $today = "$mon/$mday/$year";
here is a part I use it to start a VNC server
#!/bin/bash
start() {
echo "Starting vnc server with $resolution on Display $display"
#your execute command here mine is below
#vncserver :$display -geometry $resolution
}
stop() {
echo "Killing vncserver on display $display"
#vncserver -kill :$display
}
#########################
# The command line help #
#########################
display_help() {
echo "Usage: $0 [option...] {start|stop|restart}" >&2
echo
echo " -r, --resolution run with the given resolution WxH"
echo " -d, --display Set on which display to host on "
echo
# echo some stuff here for the -a or --add-options
exit 1
}
################################
# Check if parameters options #
# are given on the commandline #
################################
while :
do
case "$1" in
-r | --resolution)
if [ $# -ne 0 ]; then
resolution="$2" # You may want to check validity of $2
fi
shift 2
;;
-h | --help)
display_help # Call your function
exit 0
;;
-d | --display)
display="$2"
shift 2
;;
-a | --add-options)
# do something here call function
# and write it in your help function display_help()
shift 2
;;
--) # End of all options
shift
break
;;
-*)
echo "Error: Unknown option: $1" >&2
## or call function display_help
exit 1
;;
*) # No more options
break
;;
esac
done
######################
# Check if parameter #
# is set too execute #
######################
case "$1" in
start)
start # calling function start()
;;
stop)
stop # calling function stop()
;;
restart)
stop # calling function stop()
start # calling function start()
;;
*)
# echo "Usage: $0 {start|stop|restart}" >&2
display_help
exit 1
;;
esac
It's a bit weird that I placed the start stop restart in a separate case but it should work
For your first question, find the position of some value in a list x using index(), like so:
x.index(value)
For your second question, to check for multiple same values you should split your list into chunks and use the same logic from above. They say divide and conquer. It works. Try this:
value = 1
x = [1,2,3,4,5,6,2,1,4,5,6]
chunk_a = x[:int(len(x)/2)] # get the first half of x
chunk_b = x[int(len(x)/2):] # get the rest half of x
print(chunk_a.index(value))
print(chunk_b.index(value))
Hope that helps!
Nothing was working for me but then I checked here. I ran that command qc sc mysql57
and copied the value of BINARY_PATH_NAME
from it. After that I checked this and changed the value of lower_case_table_names
from 0 to 2 in my.ini
file. Then in the command prompt, I ran this command - << BINARY_PATH_NAME >> --install-manual
. After that, I started the MySQL57 service and it worked.
DIV
does not fire a resize
event, so you won't be able to do exactly what you've coded, but you could look into monitoring DOM properties.
If you are actually working with something like resizables, and that is the only way for a div to change in size, then your resize plugin will probably be implementing a callback of its own.
The abort
function does this. For example:
abort("Message goes here")
Note: the abort
message will be written to STDERR
as opposed to puts
which will write to STDOUT
.
And this is to get all local IPs in csv format in VB.NET
Imports System.Net
Imports System.Net.Sockets
Function GetIPAddress() As String
Dim ipList As List(Of String) = New List(Of String)
Dim host As IPHostEntry
Dim localIP As String = "?"
host = Dns.GetHostEntry(Dns.GetHostName())
For Each ip As IPAddress In host.AddressList
If ip.AddressFamily = AddressFamily.InterNetwork Then
localIP = ip.ToString()
ipList.Add(localIP)
End If
Next
Dim ret As String = String.Join(",", ipList.ToArray)
Return ret
End Function
Use:
#include<iostream>
using namespace std;
struct Node
{
int num;
Node *next;
};
Node *head = NULL;
Node *tail = NULL;
void AddnodeAtbeggining(){
Node *temp = new Node;
cout << "Enter the item";
cin >> temp->num;
temp->next = NULL;
if (head == NULL)
{
head = temp;
tail = temp;
}
else
{
temp->next = head;
head = temp;
}
}
void addnodeAtend()
{
Node *temp = new Node;
cout << "Enter the item";
cin >> temp->num;
temp->next = NULL;
if (head == NULL){
head = temp;
tail = temp;
}
else{
tail->next = temp;
tail = temp;
}
}
void displayNode()
{
cout << "\nDisplay Function\n";
Node *temp = head;
for(Node *temp = head; temp != NULL; temp = temp->next)
cout << temp->num << ",";
}
void deleteNode ()
{
for (Node *temp = head; temp != NULL; temp = temp->next)
delete head;
}
int main ()
{
AddnodeAtbeggining();
addnodeAtend();
displayNode();
deleteNode();
displayNode();
}
use base_url()
echo $baseurl=base_url();
if you need to pass url to a function then use site_url()
echo site_url('controller/function');
if you need the root path then FCPATH
..
echo FCPATH;
Allowing for duplicates in the IEnumerable<T>
(if sets are not desirable\possible) and "ignoring order" you should be able to use a .GroupBy()
.
I'm not an expert on the complexity measurements, but my rudimentary understanding is that this should be O(n). I understand O(n^2) as coming from performing an O(n) operation inside another O(n) operation like ListA.Where(a => ListB.Contains(a)).ToList()
. Every item in ListB is evaluated for equality against each item in ListA.
Like I said, my understanding on complexity is limited, so correct me on this if I'm wrong.
public static bool IsSameAs<T, TKey>(this IEnumerable<T> source, IEnumerable<T> target, Expression<Func<T, TKey>> keySelectorExpression)
{
// check the object
if (source == null && target == null) return true;
if (source == null || target == null) return false;
var sourceList = source.ToList();
var targetList = target.ToList();
// check the list count :: { 1,1,1 } != { 1,1,1,1 }
if (sourceList.Count != targetList.Count) return false;
var keySelector = keySelectorExpression.Compile();
var groupedSourceList = sourceList.GroupBy(keySelector).ToList();
var groupedTargetList = targetList.GroupBy(keySelector).ToList();
// check that the number of grouptings match :: { 1,1,2,3,4 } != { 1,1,2,3,4,5 }
var groupCountIsSame = groupedSourceList.Count == groupedTargetList.Count;
if (!groupCountIsSame) return false;
// check that the count of each group in source has the same count in target :: for values { 1,1,2,3,4 } & { 1,1,1,2,3,4 }
// key:count
// { 1:2, 2:1, 3:1, 4:1 } != { 1:3, 2:1, 3:1, 4:1 }
var countsMissmatch = groupedSourceList.Any(sourceGroup =>
{
var targetGroup = groupedTargetList.Single(y => y.Key.Equals(sourceGroup.Key));
return sourceGroup.Count() != targetGroup.Count();
});
return !countsMissmatch;
}
In unbuffered Input/Output(FileWriter, FileReader) read or write request is handled directly by the underlying OS. https://hajsoftutorial.com/java/wp-content/uploads/2018/04/Unbuffered.gif
This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive. To reduce this kind of overhead, the Java platform implements buffered I/O streams. The BufferedReader and BufferedWriter classes provide internal character buffers. Text that’s written to a buffered writer is stored in the internal buffer and only written to the underlying writer when the buffer fills up or is flushed. https://hajsoftutorial.com/java/wp-content/uploads/2018/04/bufferedoutput.gif
This is the simplest way you can have your own javascript function be called when an onSubmit
occurs.
HTML
<form>
<input type="text" name="name">
<input type="submit" name="submit">
</form>
JavaScript
window.onload = function() {
var form = document.querySelector("form");
form.onsubmit = submitted.bind(form);
}
function submitted(event) {
event.preventDefault();
}
Are you sure you can't alter the HTML in the popup window?
If you can, add a <script>
tag at the end of the popup's HTML, and call window.print()
inside it. Then it won't be called until the HTML has loaded.
That's JSON, or JavaScript Object Notation. It's a quick way of describing an object, or a hash map. The thing before the colon is the property name, and the thing after the colon is its value. So in this example, there's a property "r", whose value is whatever's in the variable r. Same for t.
This is the way I do it.
document.querySelector('scrollHere').scrollIntoView({ behavior: 'smooth' })
Works in any browser.
It can easily be wrapped into a function
function scrollTo(selector) {
document.querySelector(selector).scrollIntoView({ behavior: 'smooth' })
}
Here is a working example
$(".btn").click(function() {_x000D_
document.getElementById("scrollHere").scrollIntoView( {behavior: "smooth" })_x000D_
})
_x000D_
.btn {margin-bottom: 500px;}_x000D_
.middle {display: block; margin-bottom: 500px; color: red;}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<button class="btn">Scroll down</button>_x000D_
_x000D_
<h1 class="middle">You see?</h1>_x000D_
_x000D_
<div id="scrollHere">Arrived at your destination</div>
_x000D_
I ran into a similar problem while creating a library to handle authentication. I want the app owner using my library to be able to register a callback with the library for checking authorization against LDAP groups the authenticated person is in. The configuration is getting passed in as a config.py file that gets imported and contains a dict with all the config parameters.
I got this to work:
>>> class MyClass(object):
... def target_func(self):
... print "made it!"
...
... def __init__(self,config):
... self.config = config
... self.config['funcname'] = getattr(self,self.config['funcname'])
... self.config['funcname']()
...
>>> instance = MyClass({'funcname':'target_func'})
made it!
Is there a pythonic-er way to do this?
For a variable:
foo.h:
class foo
{
private:
static int i;
};
foo.cpp:
int foo::i = 0;
This is because there can only be one instance of foo::i
in your program. It's sort of the equivalent of extern int i
in a header file and int i
in a source file.
For a constant you can put the value straight in the class declaration:
class foo
{
private:
static int i;
const static int a = 42;
};
The C# foreach doesn't have a built in index. You'll need to add an integer outside the foreach loop and increment it each time.
int i = -1;
foreach (Widget w in widgets)
{
i++;
// do something
}
Alternatively, you could use a standard for loop as follows:
for (int i = 0; i < widgets.Length; i++)
{
w = widgets[i];
// do something
}
Method A is recommended by httpclient developer community.
Please refer http://www.mail-archive.com/[email protected]/msg02455.html for more details.
In IntelliJ IDEA 14, it has moved to: File -> Settings -> Editor -> General -> "Show quick doc on mouse move"
Use DATE_FORMAT
from Date Conversions:
In your initializer:
DateTime::DATE_FORMATS[:my_date_format] = "%a %b %d %H:%M:%S %Z %Y"
In your view:
date = DateTime.parse("2011-05-19 10:30:14")
date.to_formatted_s(:my_date_format)
date.to_s(:my_date_format)
Try this: B = A ( : )
, or try the reshape
function.
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/reshape.html
Add this Code in C:\xampp\apache\conf\extra\httpd-vhosts.conf
<VirtualHost *:80>
DocumentRoot "C:/xampp/htdocs"
ServerName qa-staging.com
ServerAlias www.qa-staging.com
<Directory "c:/xampp/htdocs">
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Now Add your virtual host name in bellow file.
C:\Windows\System32\drivers\etc\hosts
127.0.0.1 qa-staging.com
If you are not able to save this code in host file then right click on notpad select Run as administrator and then you can able to save your custom code now restart your XAMP
element.style.height = null;
output:
<div style="height:100px;">
// results:
<div style="">
you can use the following Bootstrap class with
<tr class="w-25">
</tr>
for more details check the following page https://getbootstrap.com/docs/4.1/utilities/sizing/
- My first question is about the abstract factory. Is its role to allow you to create families of concrete objects in (that can depend on what specific factory you use) rather than just a single concrete object?
Yes. The intent of Abstract Factory is:
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
- Does the abstract factory only return one very large object or many objects depending on what methods you call?
Ideally it should return one object per the method client is invoking.
- My understanding is that the factory method pattern has a Creator interface that will make the ConcreteCreator be in charge of knowing which ConcreteProduct to instantiate. Is this what it means by using inheritance to handle object instantiation?
Yes. Factory method uses inheritance.
- Abstract Factory pattern delegate the responsibility of object instantiation to another object via composition? What does this mean?
AbstractFactory defines a FactoryMethod and ConcreteFactory is responsible for building a ConcreteProduct. Just follow through the code example in this article.
You can find more details in related SE posts:
What is the basic difference between the Factory and Abstract Factory Patterns?
Design Patterns: Factory vs Factory method vs Abstract Factory
You must reference Context name before using getResources()
in Android.
String user=getApplicationContext().getResources().getString(R.string.muser);
OR
Context mcontext=getApplicationContext();
String user=mcontext.getResources().getString(R.string.muser);
u can try this..
<div id="placeholder" style="width:auto;height:auto"></div>
width and height depends on your flot or graph..
hope u want this...
or
By clicking, u can use this by jquery
$("#placeholder").css("width", $(window).width());
$("#placeholder").css("height", $(window).height());
You might want to take a look this:
HotSwap support: the object-oriented architecture of the Java HotSpot VM enables advanced features such as on-the-fly class redefinition, or "HotSwap". This feature provides the ability to substitute modified code in a running application through the debugger APIs. HotSwap adds functionality to the Java Platform Debugger Architecture, enabling a class to be updated during execution while under the control of a debugger. It also allows profiling operations to be performed by hotswapping in versions of methods in which profiling code has been inserted.
For the moment, this only allows for newly compiled method body to be redeployed without restarting the application. All you have to do is to run it with a debugger. I tried it in Eclipse and it works splendidly.
Also, as Emmanuel Bourg mentioned in his answer (JEP 159), there is hope to have support for the addition of supertypes and the addition and removal of methods and fields.
Reference: Java Whitepaper 135217: Reliability, Availability and Serviceability
@AVB's answer in ruby
det = Matrix[
[(x2 - x1), (x3 - x1)],
[(y2 - y1), (y3 - y1)]
].determinant
If det
is positive its above, if negative its below. If 0, its on the line.
Here's a variation of Shiv Kumar's answer, using Newtonsoft.Json (aka Json.NET):
public static bool SendAnSMSMessage(string message)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
var serializer = new Newtonsoft.Json.JsonSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter))
{
serializer.Serialize(tw,
new {method= "send",
@params = new string[]{
"IPutAGuidHere",
"[email protected]",
"MyTenDigitNumberWasHere",
message
}});
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
return true;
}
}
You can implement startForeground
for the service and even if it dies you can restart it by using START_STICKY
on startCommand()
. Not sure though this is the right implementation.
C# in .NET 3.5 using System.DirectoryServices.AccountManagement.
bool valid = false;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
valid = context.ValidateCredentials( username, password );
}
This will validate against the current domain. Check out the parameterized PrincipalContext constructor for other options.
Avoid multiple place enabling CORS,Like WebApiCOnfig.cs, GrantResourceOwnerCredentials method in provider and Controller Header attribute etc. Below are the list which also cause the Access Control Allow Origin
Below code is more then enough to fix the access control allow origin. //Make sure app.UseCors should be top of the code line of configuration.
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
//All other configurations
}
}
This slowed my problem.
From the help file about $
(See ?"$"
) you can read:
$ is only valid for recursive objects, and is only discussed in the section below on recursive objects.
Now, let's check whether x
is recursive
> is.recursive(x)
[1] FALSE
A recursive object has a list-like structure. A vector is not recursive, it is an atomic object instead, let's check
> is.atomic(x)
[1] TRUE
Therefore you get an error when applying $
to a vector (non-recursive object), use [
instead:
> x["ed"]
ed
2
You can also use getElement
> getElement(x, "ed")
[1] 2
The "manual bootstrap" case can gain access to Angular services by manually creating an injector before bootstrap. This initial injector will stand alone (not be attached to any elements) and include only a subset of the modules that are loaded. If all you need is core Angular services, it's sufficient to just load ng
, like this:
angular.element(document).ready(
function() {
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
$http.get('/config.json').then(
function (response) {
var config = response.data;
// Add additional services/constants/variables to your app,
// and then finally bootstrap it:
angular.bootstrap(document, ['myApp']);
}
);
}
);
You can, for example, use the module.constant
mechanism to make data available to your app:
myApp.constant('myAppConfig', data);
This myAppConfig
can now be injected just like any other service, and in particular it's available during the configuration phase:
myApp.config(
function (myAppConfig, someService) {
someService.config(myAppConfig.someServiceConfig);
}
);
or, for a smaller app, you could just inject the global config directly into your service, at the expense of spreading knowledge about the configuration format throughout the application.
Of course, since the async operations here will block the bootstrap of the application, and thus block the compilation/linking of the template, it's wise to use the ng-cloak
directive to prevent the unparsed template from showing up during the work. You could also provide some sort of loading indication in the DOM , by providing some HTML that gets shown only until AngularJS initializes:
<div ng-if="initialLoad">
<!-- initialLoad never gets set, so this div vanishes as soon as Angular is done compiling -->
<p>Loading the app.....</p>
</div>
<div ng-cloak>
<!-- ng-cloak attribute is removed once the app is done bootstrapping -->
<p>Done loading the app!</p>
</div>
I created a complete, working example of this approach on Plunker, loading the configuration from a static JSON file as an example.
Not sure if this is what you need but this is how I did it.
Using import org.json.JSONObject :
val jsonObj = JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1))
val foodJson = jsonObj.getJSONArray("Foods")
for (i in 0..foodJson!!.length() - 1) {
val categories = FoodCategoryObject()
val name = foodJson.getJSONObject(i).getString("FoodName")
categories.name = name
}
Here's a sample of the json :
{"Foods": [{"FoodName": "Apples","Weight": "110" } ]}
this will return first match
@fathers.detect {|f| f["age"] > 35 }
This error might occur when you return an object instead of a string in your __unicode__
method. For example:
class Author(models.Model):
. . .
name = models.CharField(...)
class Book(models.Model):
. . .
author = models.ForeignKey(Author, ...)
. . .
def __unicode__(self):
return self.author # <<<<<<<< this causes problems
To avoid this error you can cast the author instance to unicode:
class Book(models.Model):
. . .
def __unicode__(self):
return unicode(self.author) # <<<<<<<< this is OK
I recomend use this code for stable work, it optimized for nested fragments in tab (for example nested MapFragment) and tested on "do not keep activities": https://stackoverflow.com/a/23150258/2765497
Just have a application.properties
in src/main/resources
of the project and give there
server.port=****
where ****
refers to the port number.
Probably you use Microsoft SQL Server which support Common Table Expressions (CTE) (see http://msdn.microsoft.com/en-us/library/ms190766.aspx) which are very friendly for query optimization. So I suggest you my favor construction:
WITH GetNumberOfPlans(Id,NumberOfPlans) AS (
SELECT tableA.Id, COUNT(tableC.Id)
FROM tableC
RIGHT OUTER JOIN tableA ON tableC.tableAId = tableA.Id
GROUP BY tableA.Id
),GetUserInformation(Id,Name,Owner,ImageUrl,
CompanyImageUrl,NumberOfUsers) AS (
SELECT tableA.Id, tableA.Name, tableB.Username AS Owner, tableB.ImageUrl,
tableB.CompanyImageUrl,COUNT(tableD.UserId),p.NumberOfPlans
FROM tableA
INNER JOIN tableB ON tableB.Id = tableA.Owner
RIGHT OUTER JOIN tableD ON tableD.tableAId = tableA.Id
GROUP BY tableA.Name, tableB.Username, tableB.ImageUrl, tableB.CompanyImageUrl
)
SELECT u.Id,u.Name,u.Owner,u.ImageUrl,u.CompanyImageUrl
,u.NumberOfUsers,p.NumberOfPlans
FROM GetUserInformation AS u
INNER JOIN GetNumberOfPlans AS p ON p.Id=u.Id
After some experiences with CTE you will be find very easy to write code using CTE and you will be happy with the performance.
Try the :lt selector: http://docs.jquery.com/Selectors/lt#index
$('a:lt(20)');
I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering
Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date
'You said time1 doesn't change, so I left it in a singe cell.
'If that is not correct, you will have to play with this some more.
time1 = Range("A6").Value
'Looping through each of our output cells.
For Each t In Range("B7:E9") 'Change these to match your real ranges.
'Looping through each departure date/time.
'(Only one row in your example. This can be adjusted if needed.)
For Each x In Range("B2:E2") 'Change these to match your real ranges.
'Check to see if our dep time corresponds to
'the matching column in our output
If t.Column = x.Column Then
'If it does, then check to see what our time value is
If x > 0 Then
time2 = x.Value
'Apply the change to the output cell.
t.Value = time1 - time2
'Exit out of this loop and move to the next output cell.
Exit For
End If
End If
'If the columns don't match, or the x value is not a time
'then we'll move to the next dep time (x)
Next x
Next t
End Sub
EDIT
I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).
A B C D E
1 LOAD_NUMBER 1 2 3 4
2 DEPARTURE_TIME_DATE 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 20:00
4 Dry_Refrig 7585.1 0 10099.8 16700
6 1/4/2012 19:30
Using the sub I got this output:
A B C D E
7 Friday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
8 Saturday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
9 Thursday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
It means that in table kontakty
you have a row referencing the row in osoby
you want to delete. You have do delete that row first or set a cascade delete on the relation between tables.
Powodzenia!
Try using;
PHP_EOL
To terminate each new line in your CSV output.
I'm assuming that the text is delimiting, but isn't moving to the next row?
That's a PHP constant. It will determine the correct end of line you need.
Windows, for example, uses "\r\n". I wracked my brains with that one when my output wasn't breaking to a new line.
A simple solution using fscanf
:
void read_ints (const char* file_name)
{
FILE* file = fopen (file_name, "r");
int i = 0;
fscanf (file, "%d", &i);
while (!feof (file))
{
printf ("%d ", i);
fscanf (file, "%d", &i);
}
fclose (file);
}
For Laravel 6.X you can do the following:
$user = Auth::guard(<GUARD_NAME>)->user();
$user_id = $user->id;
$full_name = $user->full_name;
Just register an Eventhandler on keydown
events and check the length of the input field on that function and write it into a separate element.
See the demo.
var maxchar = 160;
var i = document.getElementById("textinput");
var c = document.getElementById("count");
c.innerHTML = maxchar;
i.addEventListener("keydown",count);
function count(e){
var len = i.value.length;
if (len >= maxchar){
e.preventDefault();
} else{
c.innerHTML = maxchar - len-1;
}
}
?
You should check the length on your server too, because Javascript might be disabled or the user wants to do something nasty on purpose.
Need to add quote for that need to use dot operator:
mysql_query("UPDATE blogEntry SET content = '".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."'");
This last error is caused by the library SLF4J not being found. HikariCP has two dependencies: slf4j and javassist. BTW, HikariDataSource does have a default constructor and does not need HikariConfig, see this link. So that was never the problem.
SELECT * FROM (SELECT * FROM tb1 ORDER BY signin DESC) GROUP BY id;
In React-Native we have an Option called Dimensions
Include Dimensions at the top var where you have include the Image,and Text and other components.
Then in your Stylesheets you can use as below,
ex: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height
}
In this way you can get the device window and height.
what language is this? If you're using a language that passes everything by reference like Java (except for native types), typically you can call .clone()
method. The .clone() method is typically implemented by copying/cloning all relevant instance fields into the new object.
You can use the following code to check if the file can be opened with exclusive access (that is, it is not opened by another application). If the file isn't closed, you could wait a few moments and check again until the file is closed and you can safely copy it.
You should still check if File.Copy fails, because another application may open the file between the moment you check the file and the moment you copy it.
public static bool IsFileClosed(string filename)
{
try
{
using (var inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
{
return true;
}
}
catch (IOException)
{
return false;
}
}
Try either
sudo apt-get install php-zip
orsudo apt-get install php5.6-zip
Then, you might have to restart your web server.
sudo service apache2 restart
orsudo service nginx restart
If you are installing on centos or fedora OS then use yum in place of apt-get. example:-
sudo yum install php-zip
or
sudo yum install php5.6-zip
and
sudo service httpd restart
You can't use a subselect inside a CREATE SEQUENCE
statement. You'll have to select the value beforehand.
Float them both the same way and add the margin of 40px. If you have 2 elements floating opposite ways you will have much less control and the containing element will determine how far apart they are.
#left{
float: left;
margin-right: 40px;
}
#right{
float: left;
}
After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?
BUT there was an import that was screwing the rest of it up:
.vue
files<script>
var mylib = require('./mylib');
export default {
....
mylib
exports.myfunc = () => {....}
import
The actual issue in my case (which I didn't think was relevant!) was that mylib.js
was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack
but anyway I had:
import models from './model/models'
import axios from 'axios'
This works so long as I'm not using mylib
in a .vue
component. However as soon as I use mylib
there, the error described in this issue arises.
I changed to:
let models = require('./model/models');
let axios = require('axios');
And all works as expected.
I've faced with the same problem, have struggled a couple of day with it and should say that the most easiest way to overcome I found this is to use fragment.hide() / fragment.show() when tab is selected/unselected().
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft)
{
if (mFragment != null)
ft.hide(mFragment);
}
When screen rotation occurs all parent and child fragments get correctly destroyed.
This approach has also one additional advantage - using hide()/show() does not cause fragment views to loose their state, so there is no need to restore the previous scroll position for ScrollViews for example.
The problem is that I don't know whether it is correct to not detach fragments when they are not visible. I think the official example of TabListener is designed with a thought in mind that fragments are reusable and you should not pollute with them memory, however, I think if you have just a few tabs and you know that users will be switching between them frequently it will be appropriate to keep them attached to the current activity.
I would like to hear comments from more experienced developers.
This error is a result of the protection level of ClassB
's constructor, not ClassB
itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal
by default. Declaring the constructor public
will fix this problem:
public ClassB() { }
* One could also say that constructors have no name, only a type; this does not change the essence of the problem.
Instead of using 2 separate queries, you can use aggregate()
in a single query:
Aggregate "$facet" can be fetch more quickly, the Total Count and the Data with skip & limit
db.collection.aggregate([
//{$sort: {...}}
//{$match:{...}}
{$facet:{
"stage1" : [ {"$group": {_id:null, count:{$sum:1}}} ],
"stage2" : [ { "$skip": 0}, {"$limit": 2} ]
}},
{$unwind: "$stage1"},
//output projection
{$project:{
count: "$stage1.count",
data: "$stage2"
}}
]);
output as follows:-
[{
count: 50,
data: [
{...},
{...}
]
}]
Also, have a look at https://docs.mongodb.com/manual/reference/operator/aggregation/facet/
The best solution is to use async Task
. You should avoid async void
for several reasons, one of which is composability.
If the method cannot be made to return Task
(e.g., it's an event handler), then you can use SemaphoreSlim
to have the method signal when it is about to exit. Consider doing this in a finally
block.
I think the description of the error is misleading and has originally to do with wrong usage of the player object.
I had the same issue when switching to new Videos in a Slider.
When simply using the player.destroy()
function described here the problem is gone.
Diff has an option -r
which is meant to do just that.
diff -r dir1 dir2
FIXED SOLUTION FOR SWIFT 3+ (iOS 9, 10)
1- In info.plist set below property
2- Paste below code to Root controller , To
private var isStatusBarHidden = true {
didSet {
setNeedsStatusBarAppearanceUpdate()
}
}
override var prefersStatusBarHidden: Bool {
return isStatusBarHidden
}
You can call isStatusBarHidden = true
and isStatusBarHidden = false
where you want to hide/show
status bar
When you have opened a folder in a workspace you can do Ctrl+P (Cmd+P on Mac) and start typing the filename, or extension to filter the list of filenames
if you have:
You can type css
and press enter and it will open the page.css
. If you type .ts
the list is filtered and contains two items.
If you have Apache add this to the .htaccess
file:
<FilesMatch "\.(?i:pdf)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
.catch(error => { throw error})
is a no-op. It results in unhandled rejection in route handler.
As explained in this answer, Express doesn't support promises, all rejections should be handled manually:
router.get("/emailfetch", authCheck, async (req, res, next) => {
try {
//listing messages in users mailbox
let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
emailFetch = emailFetch.data
res.send(emailFetch)
} catch (err) {
next(err);
}
})
Surprisingly (or not), the vertical-align
tool actually works best for this job. Best of all, no Javascript is required.
In the following example, I am positioning the outer
class in the middle of the body, and the inner
class in the middle of the outer
class.
Preview: http://jsfiddle.net/tLkSV/513/
HTML:
<div id="container">
<span></span><div class="outer">
<span></span><div class="inner">
</div>
</div>
</div>
CSS:
html, body {
height: 100%;
margin: 0;
padding: 0; }
#container {
text-align: center;
height: 100%; }
span {
height: 100%;
vertical-align: middle;
display: inline-block; }
.outer {
width: 100px;
height: 200px;
padding: 0;
border: 1px solid #000;
vertical-align: middle;
display: inline-block; }
.inner {
background: red;
width: 30px;
height: 20px;
vertical-align: middle;
display: inline-block; }
Vertical align works by aligning the centers of elements that are next to each other. Applying vertical-align to a single element does absolutely nothing. If you add a second element that has no width but is the height of the container, your single element will move to vertically center with this no-width element, thus vertically centering it. The only requirements are that you set both elements to inline (or inline-block), and set their vertical-align attribute to vertical-align: middle
.
Note: You may notice in my code below that my <span>
tag and <div>
tag are touching. Because they are both inline elements, a space will actually add a space between the no-width element and your div, so be sure to leave it out.
When you have a more complex id string the double quotes are mandatory.
For example if you have an id like this: id="2.2"
, the correct way to access it is: $('input[id="2.2"]')
As much as possible use the double quotes, for safety reasons.
The major difference between Spring MVC and Struts is: Spring MVC is loosely coupled framework whereas Struts is tightly coupled. For enterprise Application you need to build your application as loosely coupled as it would make your application more reusable and robust as well as distributed.
Use gsub
:
data1$c <- gsub('_', '-', data1$c)
data1
a b c
1 0.34597094 a A-B
2 0.92791908 b A-B
3 0.30168772 c A-B
4 0.46692738 d A-B
5 0.86853784 e A-C
6 0.11447618 f A-C
7 0.36508645 g A-C
8 0.09658292 h A-C
9 0.71661842 i A-C
10 0.20064575 j A-C
There is a built in method for this:
byte[] data = { 1, 2, 4, 8, 16, 32 };
string hex = BitConverter.ToString(data);
Result: 01-02-04-08-10-20
If you want it without the dashes, just remove them:
string hex = BitConverter.ToString(data).Replace("-", string.Empty);
Result: 010204081020
If you want a more compact representation, you can use Base64:
string base64 = Convert.ToBase64String(data);
Result: AQIECBAg
SELECT id FROM tbl GROUP BY cat HAVING MAX(date)
VI search and replace command examples
Let us say you would like to find a word called “foo” and replace with “bar”.
First hit [Esc]
key
Type : (colon) followed by %s/foo/bar/
and hit [Enter] key
:%s/foo/bar/
To avoid the race condition @GregPettit mentions, one can use:
($("element").data('bs.modal') || {})._isShown // Bootstrap 4
($("element").data('bs.modal') || {}).isShown // Bootstrap <= 3
as discussed in Twitter Bootstrap Modal - IsShown.
When the modal is not yet opened, .data('bs.modal')
returns undefined
, hence the || {}
- which will make isShown
the (falsy) value undefined
. If you're into strictness one could do ($("element").data('bs.modal') || {isShown: false}).isShown
Try this:
urlString=Request.RawUrl.ToString.Substring(0, Request.RawUrl.ToString.IndexOf("?"))
from this: http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye you'll get this: mypage.aspx
The steps to remove the newline character in the perhaps most obvious way:
NAME
by using strlen()
, header string.h
. Note that strlen()
does not count the terminating \0
.size_t sl = strlen(NAME);
\0
character (empty string). In this case sl
would be 0
since strlen()
as I said above doesn´t count the \0
and stops at the first occurrence of it: if(sl == 0)
{
// Skip the newline replacement process.
}
'\n'
. If this is the case, replace \n
with a \0
. Note that index counts start at 0
so we will need to do NAME[sl - 1]
:if(NAME[sl - 1] == '\n')
{
NAME[sl - 1] = '\0';
}
Note if you only pressed Enter at the fgets()
string request (the string content was only consisted of a newline character) the string in NAME
will be an empty string thereafter.
if
-statement by using the logic operator &&
:if(sl > 0 && NAME[sl - 1] == '\n')
{
NAME[sl - 1] = '\0';
}
size_t sl = strlen(NAME);
if(sl > 0 && NAME[sl - 1] == '\n')
{
NAME[sl - 1] = '\0';
}
If you rather like a function for use this technique by handling fgets
output strings in general without retyping each and every time, here is fgets_newline_kill
:
void fgets_newline_kill(char a[])
{
size_t sl = strlen(a);
if(sl > 0 && a[sl - 1] == '\n')
{
a[sl - 1] = '\0';
}
}
In your provided example, it would be:
printf("Enter your Name: ");
if (fgets(Name, sizeof Name, stdin) == NULL) {
fprintf(stderr, "Error reading Name.\n");
exit(1);
}
else {
fgets_newline_kill(NAME);
}
Note that this method does not work if the input string has embedded \0
s in it. If that would be the case strlen()
would only return the amount of characters until the first \0
. But this isn´t quite a common approach, since the most string-reading functions usually stop at the first \0
and take the string until that null character.
Aside from the question on its own. Try to avoid double negations that make your code unclearer: if (!(fgets(Name, sizeof Name, stdin) != NULL) {}
. You can simply do if (fgets(Name, sizeof Name, stdin) == NULL) {}
.
All the above-given answers only solved one thing: compare two dates.
Indeed, they seem to be the answers to the question, but a big part is missing:
What if I want to check whether a person is fully 18 years old?
Unfortunately, NONE of the above-given answers would be able to answer that question.
For example, the current time (around the time when I started to type these words) is Fri Jan 31 2020 10:41:04 GMT-0600 (Central Standard Time), while a customer enters his Date of Birth as "01/31/2002".
If we use "365 days/year", which is "31536000000" milliseconds, we would get the following result:
let currentTime = new Date();
let customerTime = new Date(2002, 1, 31);
let age = (currentTime.getTime() - customerTime.getTime()) / 31536000000
console.log("age: ", age);
with the following print-out:
age: 17.92724710838407
But LEGALLY, that customer is already 18 years old. Even he enters "01/30/2002", the result would still be
age: 17.930039743467784
which is less than 18. The system would report the "under age" error.
And this would just keep going for "01/29/2002", "01/28/2002", "01/27/2002" ... "01/05/2002", UNTIL "01/04/2002".
A system like that would just kill all the customers who were born between 18 years 0 days and 18 years 26 days ago, because they are legally 18 years old, while the system shows "under age".
The following is an answer to a question like that:
invalidBirthDate: 'Invalid date. YEAR cannot be before 1900.',
invalidAge: 'Invalid age. AGE cannot be less than 18.',
public static birthDateValidator(control: any): any {
const val = control.value;
if (val != null) {
const slashSplit = val.split('-');
if (slashSplit.length === 3) {
const customerYear = parseInt(slashSplit[0], 10);
const customerMonth = parseInt(slashSplit[1], 10);
const customerDate = parseInt(slashSplit[2], 10);
if (customerYear < 1900) {
return { invalidBirthDate: true };
} else {
const currentTime = new Date();
const currentYear = currentTime.getFullYear();
const currentMonth = currentTime.getMonth() + 1;
const currentDate = currentTime.getDate();
if (currentYear - customerYear < 18) {
return { invalidAge: true };
} else if (
currentYear - customerYear === 18 &&
currentMonth - customerMonth < 0) {
return { invalidAge: true };
} else if (
currentYear - customerYear === 18 &&
currentMonth - customerMonth === 0 &&
currentDate - customerDate < 0) {
return { invalidAge: true };
} else {
return null;
}
}
}
}
}
Okay, first intuition is here:
handlers = java.util.logging.FileHandler, java.util.logging.ConsoleHandler
.level = ALL
The Java prop file parser isn't all that smart, I'm not sure it'll handle this. But I'll go look at the docs again....
In the mean time, try:
handlers = java.util.logging.FileHandler
java.util.logging.ConsoleHandler.level = ALL
Update
No, duh, needed more coffee. Nevermind.
While I think more, note that you can use the methods in Properties to load and print a prop-file: it might be worth writing a minimal program to see what java thinks it reads in that file.
Another update
This line:
FileInputStream configFile = new FileInputStream("/path/to/app.properties"));
has an extra end-paren. It won't compile. Make sure you're working with the class file you think you are.
AllDogs.First(d => d.Id == "2").Name = "some value";
However, a safer version of that might be this:
var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }
USE This Assembly Referance in your Project
Add a reference to System.Net.Http.Formatting.dll
The ?
operand makes match non-greedy. E.g. .*
is greedy while .*?
isn't. So you can use something like <img.*?>
to match the whole tag. Or <img[^>]*>
.
But remember that the whole set of HTML can't be actually parsed with regular expressions.
UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Tutorial" bundle:nil];
self.window.rootViewController = [storyboard instantiateInitialViewController];
I know it's a bit late, but I've tried everything above and nothing worked. The real problem was that I'm using hibernate, so it was trying to connect to mysql but was not able, thats why it showed time out.
Just to let u guys know, I'm using RDS(Amazon), so just to make a test I changed to my local mysql and it worked perfectly.
Hope that this answer helps somebody.
Thanks.
how is this
=((?:(?:(?:http)s?:)?\/\/)?(?:(?:[a-zA-Z0-9]+)\.?)*(?:(?:[a-zA-Z0-9]+))\.[a-zA-Z0-9]{2,3})
(you may want to add "\/" to end of pattern
if your goal is to rid url's passed in as a param you may add the equal sign as the first char, like:
=((?:(?:(?:http)s?:)?//)?(?:(?:[a-zA-Z0-9]+).?)*(?:(?:[a-zA-Z0-9]+)).[a-zA-Z0-9]{2,3}/)
and replace with "/"
The goal of this example to get rid of any domain name regardless of the form it appears in. (i.e. to ensure url parameters don't incldue domain names to avoid xss attack)
HTML
<div class="row">
<div class="col-xs-2 pull-bottom"
style="height:100px;background:blue">
</div>
<div class="col-xs-8 pull-bottom"
style="height:50px;background:yellow">
</div>
</div>
CSS
.pull-bottom {
display: inline-block;
vertical-align: bottom;
float: none;
}
You have to aggregate by anything NOT IN
the group by
clause.
So,there are two options...Add Credit_Initial and Disponible_v to the group by
OR
Change them to MAX( Credit_Initial ) as Credit_Initial, MAX( Disponible_v ) as Disponible_v
if you know the values are constant anyhow and have no other impact.
I'm assuming you don't want any other session to be able to read the row while this specific query is running...
Wrapping your SELECT in a transaction while using WITH (XLOCK,READPAST) locking hint will get the results you want. Just make sure those other concurrent reads are NOT using WITH (NOLOCK). READPAST allows other sessions to perform the same SELECT but on other rows.
BEGIN TRAN
SELECT *
FROM <tablename> WITH (XLOCK,READPAST)
WHERE RowId = @SomeId
-- Do SOMETHING
UPDATE <tablename>
SET <column>=@somevalue
WHERE RowId=@SomeId
COMMIT
var res = from element in list
group element by element.F1
into groups
select groups.OrderBy(p => p.F2).First();
hey, sorry if my opinion agrees with someone, I'm just trying to explain recursion in plain english.
suppose you have three managers - Jack, John and Morgan. Jack manages 2 programmers, John - 3, and Morgan - 5. you are going to give every manager 300$ and want to know what would it cost. The answer is obvious - but what if 2 of Morgan-s employees are also managers?
HERE comes the recursion. you start from the top of the hierarchy. the summery cost is 0$. you start with Jack, Then check if he has any managers as employees. if you find any of them are, check if they have any managers as employees and so on. Add 300$ to the summery cost every time you find a manager. when you are finished with Jack, go to John, his employees and then to Morgan.
You'll never know, how much cycles will you go before getting an answer, though you know how many managers you have and how many Budget can you spend.
Recursion is a tree, with branches and leaves, called parents and children respectively. When you use a recursion algorithm, you more or less consciously are building a tree from the data.
Is there a simple way to convert a LocalDate (introduced with Java 8) to java.util.Date object? By 'simple', I mean simpler than this
Nope. You did it properly, and as concisely as possible.
java.util.Date.from( // Convert from modern java.time class to troublesome old legacy class. DO NOT DO THIS unless you must, to inter operate with old code not yet updated for java.time.
myLocalDate // `LocalDate` class represents a date-only, without time-of-day and without time zone nor offset-from-UTC.
.atStartOfDay( // Let java.time determine the first moment of the day on that date in that zone. Never assume the day starts at 00:00:00.
ZoneId.of( "America/Montreal" ) // Specify time zone using proper name in `continent/region` format, never 3-4 letter pseudo-zones such as “PST”, “CST”, “IST”.
) // Produce a `ZonedDateTime` object.
.toInstant() // Extract an `Instant` object, a moment always in UTC.
)
Read below for issues, and then think about it. How could it be simpler? If you ask me what time does a date start, how else could I respond but ask you “Where?”?. A new day dawns earlier in Paris FR than in Montréal CA, and still earlier in Kolkata IN, and even earlier in Auckland NZ, all different moments.
So in converting a date-only (LocalDate
) to a date-time we must apply a time zone (ZoneId
) to get a zoned value (ZonedDateTime
), and then move into UTC (Instant
) to match the definition of a java.util.Date
.
Firstly, avoid the old legacy date-time classes such as java.util.Date
whenever possible. They are poorly designed, confusing, and troublesome. They were supplanted by the java.time classes for a reason, actually, for many reasons.
But if you must, you can convert to/from java.time types to the old. Look for new conversion methods added to the old classes.
java.util.Date
? java.time.LocalDate
Keep in mind that a java.util.Date
is a misnomer as it represents a date plus a time-of-day, in UTC. In contrast, the LocalDate
class represents a date-only value without time-of-day and without time zone.
Going from java.util.Date
to java.time means converting to the equivalent class of java.time.Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myUtilDate.toInstant();
The LocalDate
class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
So we need to move that Instant
into a time zone. We apply ZoneId
to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
From there, ask for a date-only, a LocalDate
.
LocalDate ld = zdt.toLocalDate();
java.time.LocalDate
? java.util.Date
To move the other direction, from a java.time.LocalDate
to a java.util.Date
means we are going from a date-only to a date-time. So we must specify a time-of-day. You probably want to go for the first moment of the day. Do not assume that is 00:00:00
. Anomalies such as Daylight Saving Time (DST) means the first moment may be another time such as 01:00:00
. Let java.time determine that value by calling atStartOfDay
on the LocalDate
.
ZonedDateTime zdt = myLocalDate.atStartOfDay( z );
Now extract an Instant
.
Instant instant = zdt.toInstant();
Convert that Instant
to java.util.Date
by calling from( Instant )
.
java.util.Date d = java.util.Date.from( instant );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
add the lines in your /res/values.xml file in resource root tab like this:
<resources
xmlns:tools="http://schemas.android.com/tools"
tools:locale="en" tools:ignore="MissingTranslation">
tools:locale set the local language to English, no need of language translation later on that for all resource strings and tools:ignore let Lint to isnore the missing translations of the resource string values.
Well one thing you could do is if you have a switch:
switch(SomeEnum)
{
case SomeEnum.One:
DoThings(someUser);
break;
case SomeEnum.Two:
DoSomethingElse(someUser);
break;
}
And with the might power of actions you can turn that switch into a dictionary:
Dictionary<SomeEnum, Action<User>> methodList =
new Dictionary<SomeEnum, Action<User>>()
methodList.Add(SomeEnum.One, DoSomething);
methodList.Add(SomeEnum.Two, DoSomethingElse);
...
methodList[SomeEnum](someUser);
Or you could take this farther:
SomeOtherMethod(Action<User> someMethodToUse, User someUser)
{
someMethodToUse(someUser);
}
....
var neededMethod = methodList[SomeEnum];
SomeOtherMethod(neededMethod, someUser);
Just a couple of examples. Of course the more obvious use would be Linq extension methods.
There are 3 things I can think of off the top of my head:
Try using django.core.urlresolvers.reverse
at the command line for a (possibly) better error
>>> from django.core.urlresolvers import reverse
>>> reverse('products.views.filter_by_led')
Check to see if you have more than one url that points to that view
First Collection is class Interface and you can not instantiate. Collection API
List Ver APi is also an interface class.
It may be so
List list = Collections.synchronizedList(new ArrayList(...));
ver enter link description here
Collection collection= Collections.synchronizedList(new ArrayList(...));
Another option is to use the cor.test function, instead of lm:
> x <- c(44.4, 45.9, 41.9, 53.3, 44.7, 44.1, 50.7, 45.2, 60.1)
> y <- c( 2.6, 3.1, 2.5, 5.0, 3.6, 4.0, 5.2, 2.8, 3.8)
> mycor = cor.test(x,y)
> mylm = lm(x~y)
# r and rsquared:
> cor.test(x,y)$estimate ** 2
cor
0.3262484
> summary(lm(x~y))$r.squared
[1] 0.3262484
# P.value
> lmp(lm(x~y)) # Using the lmp function defined in Chase's answer
[1] 0.1081731
> cor.test(x,y)$p.value
[1] 0.1081731
Here is some code which extends Object with rad(deg)
, deg(rad)
and also two more useful functions: getAngle(point1,point2)
and getDistance(point1,point2)
where a point needs to have a x
and y
property.
Object.prototype.rad = (deg) => Math.PI/180 * deg;
Object.prototype.deg = (rad) => 180/Math.PI * rad;
Object.prototype.getAngle = (point1, point2) => Math.atan2(point1.y - point2.y, point1.x - point2.x);
Object.prototype.getDistance = (point1, point2) => Math.sqrt(Math.pow(point1.x-point2.x, 2) + Math.pow(point1.y-point2.y, 2));
You can use the -quit
option of find
:
find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit
Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.
For background, see the Understanding ASP.NET dynamic compilation article on MSDN.
grep '^[0-9]\{1,16\}' | wc -l
Gives the counts with exact match count with limit
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
I was referencing a mapped drive and I found that the mapped drives are not always available to the user account that is running the scheduled task so I used \\IPADDRESS
instead of MAPDRIVELETTER:
and I am up and running.
For me the error was caused by wrong type hint of url string. I used:
export class TodoService {
apiUrl: String = 'https://jsonplaceholder.typicode.com/todos' // wrong uppercase String
constructor(private httpClient: HttpClient) { }
getTodos(): Observable<Todo[]> {
return this.httpClient.get<Todo[]>(this.apiUrl)
}
}
where I should have used
export class TodoService {
apiUrl: string = 'https://jsonplaceholder.typicode.com/todos' // lowercase string!
constructor(private httpClient: HttpClient) { }
getTodos(): Observable<Todo[]> {
return this.httpClient.get<Todo[]>(this.apiUrl)
}
}
I faced the same problem when connecting to EC2, the issue was with Security Group, I solved by adding the allowed IPs at port 5432
It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?
Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:
UPDATE INVOICE
SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
, INV_TOTAL = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)
WHERE INV_ID = I_INV_ID;
Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.
A small improvement from the accepted answer is to do the null check and also get full object.
public class DateComparator {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1, "name1", addDays(new Date(), 1)));
employees.add(new Employee(2, "name2", addDays(new Date(), 3)));
employees.add(new Employee(3, "name3", addDays(new Date(), 6)));
employees.add(new Employee(4, "name4", null));
employees.add(new Employee(5, "name5", addDays(new Date(), 4)));
employees.add(new Employee(6, "name6", addDays(new Date(), 5)));
System.out.println(employees);
Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).get();
System.out.println(format.format(maxDate));
//Comparator<Employee> comparator = (p1, p2) -> p1.getJoiningDate().compareTo(p2.getJoiningDate());
Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).get();
System.out.println(" maxDatedEmploye : " + maxDatedEmploye);
Employee minDatedEmployee = employees.stream().filter(emp -> emp.getJoiningDate() != null).min(comparator).get();
System.out.println(" minDatedEmployee : " + minDatedEmployee);
}
public static Date addDays(Date date, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); // minus number would decrement the days
return cal.getTime();
}
}
You would get below results :
[Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018],
Employee [empId=2, empName=name2, joiningDate=Fri Mar 23 13:33:09 EDT 2018],
Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018],
Employee [empId=4, empName=name4, joiningDate=null],
Employee [empId=5, empName=name5, joiningDate=Sat Mar 24 13:33:09 EDT 2018],
Employee [empId=6, empName=name6, joiningDate=Sun Mar 25 13:33:09 EDT 2018]
]
2018-03-26
maxDatedEmploye : Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018]
minDatedEmployee : Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018]
Update : What if list itself is empty ?
Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).orElse(new Date());
System.out.println(format.format(maxDate));
Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).orElse(null);
System.out.println(" maxDatedEmploye : " + maxDatedEmploye);
The asynchronous solution from Edward:
is simple and might just work for you.
I would also like to give a more advanced version which has these advantages:
This might be in particular useful in large software projects where you have many task executed repetitively in your process and you care about resource usage (threads) and also startup overhead.
Idea: Have one service thread which processes all registered timed tasks. Use boost io_service for that.
Code similar to: http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/tutorial/tuttimer2/src.html
#include <cstdio>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int main()
{
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
t.async_wait([](const boost::system::error_code& /*e*/){
printf("Printed after 1s\n"); });
boost::asio::deadline_timer t2(io, boost::posix_time::seconds(1));
t2.async_wait([](const boost::system::error_code& /*e*/){
printf("Printed after 1s\n"); });
// both prints happen at the same time,
// but only a single thread is used to handle both timed tasks
// - namely the main thread calling io.run();
io.run();
return 0;
}
These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit
for Chrome, Safari; -moz
for Firefox, -o
for Opera, -ms
for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.
This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.
To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:
.elementClass {
-moz-border-radius: 2em;
-ms-border-radius: 2em;
-o-border-radius: 2em;
-webkit-border-radius: 2em;
border-radius: 2em;
}
Specifically, to address the CSS in your question, the lines you quote:
-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;
Specify the column-count
, column-gap
and column-fill
properties for Webkit browsers and Firefox.
References:
First you have load session library.
$this->load->library("session");
You can load it in auto load, which I think is better.
To set session
$this->session->set_userdata("SESSION_NAME","VALUE");
To extract Data
$this->session->userdata("SESSION_NAME");
If you run a batch file calling PowerShell as a administrator, you better run it like this, saving you all the trouble:
powershell.exe -ExecutionPolicy Bypass -Command "Path\xxx.ps1"
It is better to use Bypass
...
Hi there is my code for pagination: Use in blade @include('pagination.default', ['paginator' => $users])
Views/pagination/default.blade.php
@if ($paginator->lastPage() > 1)
si la pagina actual es distinto a 1 y hay mas de 5 hojas muestro el boton de 1era hoja --> if actual page is not equals 1, and there is more than 5 pages then I show first page button --> @if ($paginator->currentPage() != 1 && $paginator->lastPage() >= 5) << @endif
<!-- si la pagina actual es distinto a 1 muestra el boton de atras -->
@if($paginator->currentPage() != 1)
<li>
<a href="{{ $paginator->url($paginator->currentPage()-1) }}" >
<
</a>
</li>
@endif
<!-- dibuja las hojas... Tomando un rango de 5 hojas, siempre que puede muestra 2 hojas hacia atras y 2 hacia adelante -->
<!-- I draw the pages... I show 2 pages back and 2 pages forward -->
@for($i = max($paginator->currentPage()-2, 1); $i <= min(max($paginator->currentPage()-2, 1)+4,$paginator->lastPage()); $i++)
<li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
<a href="{{ $paginator->url($i) }}">{{ $i }}</a>
</li>
@endfor
<!-- si la pagina actual es distinto a la ultima muestra el boton de adelante -->
<!-- if actual page is not equal last page then I show the forward button-->
@if ($paginator->currentPage() != $paginator->lastPage())
<li>
<a href="{{ $paginator->url($paginator->currentPage()+1) }}" >
>
</a>
</li>
@endif
<!-- si la pagina actual es distinto a la ultima y hay mas de 5 hojas muestra el boton de ultima hoja -->
<!-- if actual page is not equal last page, and there is more than 5 pages then I show last page button -->
@if ($paginator->currentPage() != $paginator->lastPage() && $paginator->lastPage() >= 5)
<li>
<a href="{{ $paginator->url($paginator->lastPage()) }}" >
>>
</a>
</li>
@endif
</ul>
compile ("com.android.support:support-v4:22.2.0")
compile ("com.android.support:appcompat-v7:22.2.0")
compile ("com.android.support:support-annotations:22.2.0")
compile ("com.android.support:recyclerview-v7:22.2.0")
compile ("com.android.support:design:22.2.0")
paste the above code in your app gradle.
and while setting up the project select empty activity instead of blank activity.