Issue is with remote server, can you login to the remote server and check if "scp" works
probable causes: - scp is not in path - openssh client not installed correctly
for more details http://www.linuxquestions.org/questions/linux-newbie-8/bash-scp-command-not-found-920513/
One nice bonus of the already-mentioned sshpass
is that you can use it with autossh
, eliminating even more of the interactive inefficiency.
sshpass -p mypassword autossh -M0 -t [email protected]
This will allow autoreconnect if, e.g. your wifi is interrupted by closing your laptop.
ssh-keygen -f private.pem -y > public.pub
Extending @RobBednark's solution to a specific Windows + PuTTY scenario, you can do so:
Generate SSH key pair with PuTTYgen (following Manually generating your SSH key in Windows), saving it to a PPK file;
With the context menu in Windows Explorer, choose Edit with PuTTYgen. It will prompt for a password.
If you type the wrong password, it will just prompt again.
Note, if you like to type, use the following command on a folder that contains the PPK file: puttygen private-key.ppk -y
.
You can create a configuration file named config
in your ~/.ssh
folder. It can contain:
Host aws
HostName *yourip*
User *youruser*
IdentityFile *idFile*
This will allow you to connect to machines like this
ssh aws
Convert PPK to OpenSSh
OS X: Install Homebrew, then run
brew install putty
Place your keys in some directory, e.g. your home folder. Now convert the PPK keys to SSH keypairs:cache search
To generate the private key:
cd ~
puttygen id_dsa.ppk -O private-openssh -o id_dsa
and to generate the public key:
puttygen id_dsa.ppk -O public-openssh -o id_dsa.pub
Move these keys to ~/.ssh and make sure the permissions are set to private for your private key:
mkdir -p ~/.ssh
mv -i ~/id_dsa* ~/.ssh
chmod 600 ~/.ssh/id_dsa
chmod 666 ~/.ssh/id_dsa.pub
connect with ssh server
ssh -i ~/.ssh/id_dsa username@servername
Port Forwarding to connect mysql remote server
ssh -i ~/.ssh/id_dsa -L 9001:127.0.0.1:3306 username@serverName
I solved the problem by changing the StartupType of the ssh-agent to Manual
via Set-Service ssh-agent -StartupType Manual
.
Then I was able to start the service via Start-Service ssh-agent
or just ssh-agent.exe
.
After comming across the problem recently and this being one of the top google results i thought i would chip in with a simple work around documented in discussion here: http://code.google.com/p/msysgit/issues/detail?id=261#c40
Simply involves overwriting the mysys ssh.exe with your cygwin ssh.exe
Short answer:
$ ssh-keygen -p
This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase).
If you would like to do it all on one line without prompts do:
$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]
Important: Beware that when executing commands they will typically be logged in your ~/.bash_history
file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise.
Notice though that you can still use -f keyfile
without having to specify -P
nor -N
, and that the keyfile defaults to ~/.ssh/id_rsa
, so in many cases, it's not even needed.
You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent.
You need to get a reference of your form, and after that you can iterate the elements
collection. So, assuming for instance:
<form method="POST" action="submit.php" id="my-form">
..etc..
</form>
You will have something like:
var elements = document.getElementById("my-form").elements;
for (var i = 0, element; element = elements[i++];) {
if (element.type === "text" && element.value === "")
console.log("it's an empty textfield")
}
Notice that in browser that would support querySelectorAll you can also do something like:
var elements = document.querySelectorAll("#my-form input[type=text][value='']")
And you will have in elements
just the element that have an empty value attribute. Notice however that if the value is changed by the user, the attribute will be remain the same, so this code is only to filter by attribute not by the object's property. Of course, you can also mix the two solution:
var elements = document.querySelectorAll("#my-form input[type=text]")
for (var i = 0, element; element = elements[i++];) {
if (element.value === "")
console.log("it's an empty textfield")
}
You will basically save one check.
I have wondered the same thing. Basically it appears that the html spec has different content types for html and form data. Json only has a single content type.
According to the spec, a POST of json data should have the content-type:
application/json
Relevant portion of the HTML spec
6.7 Content types (MIME types)
...
Examples of content types include "text/html", "image/png", "image/gif", "video/mpeg", "text/css", and "audio/basic".17.13.4 Form content types
...
application/x-www-form-urlencoded
This is the default content type. Forms submitted with this content type must be encoded as follows
Relevant portion of the JSON spec
- IANA Considerations
The MIME media type for JSON text is application/json.
How about:
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(date1).equals(fmt.format(date2));
You can also set the timezone to the SimpleDateFormat, if needed.
NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24'
- it is a performance killer:
DATE()
for all rows, including those, that don't matchIt is much faster to use
SELECT * FROM tablename
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'
as this will allow index use without calculation.
EDIT
As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read
SELECT * FROM tablename
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'
The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.
Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.
Reference: http://developer.android.com/reference/android/view/View.html
In my case, I had checked out a different branch with a new library on it. I fixed my issue by only running npm install
without doing anything else. I was confused why I was getting ELIFECYCLE
error when the port was not being used, but it must have been because I did not have the library installed. So, you might not have to delete node_modules
to fix the issue.
Javascript's inheritance is prototype based, so you extend the prototypes of objects such as Date, Math, and even your own custom ones.
Date.prototype.lol = function() {
alert('hi');
};
( new Date ).lol() // alert message
In the snippet above, I define a method for all Date objects ( already existing ones and all new ones ).
extend
is usually a high level function that copies the prototype of a new subclass that you want to extend from the base class.
So you can do something like:
extend( Fighter, Human )
And the Fighter
constructor/object will inherit the prototype of Human
, so if you define methods such as live
and die
on Human
then Fighter
will also inherit those.
Updated Clarification:
"high level function" meaning .extend isn't built-in but often provided by a library such as jQuery or Prototype.
Have you tried:
Dim result As String
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets("Data")
result = Application.WorksheetFunction.VLookup(sheet.Range("AN2"), sheet.Range("AA9:AF20"), 5, False)
How about something like: Using HTML Agility Pack
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
Console.WriteLine("Found: " + table.Id);
foreach (HtmlNode row in table.SelectNodes("tr")) {
Console.WriteLine("row");
foreach (HtmlNode cell in row.SelectNodes("th|td")) {
Console.WriteLine("cell: " + cell.InnerText);
}
}
}
Note that you can make it prettier with LINQ-to-Objects if you want:
var query = from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
from row in table.SelectNodes("tr").Cast<HtmlNode>()
from cell in row.SelectNodes("th|td").Cast<HtmlNode>()
select new {Table = table.Id, CellText = cell.InnerText};
foreach(var cell in query) {
Console.WriteLine("{0}: {1}", cell.Table, cell.CellText);
}
VSCode is a code editor, not a full IDE. Think of VSCode as a notepad on steroids with IntelliSense code completion, richer semantic code understanding of multiple languages, code refactoring, including navigation, keyboard support with customizable bindings, syntax highlighting, bracket matching, auto indentation, and snippets.
It's not meant to replace Visual Studio, but making "Visual Studio" part of the name in VSCode will of course confuse some people at first.
One advantage that the aforementioned copy-webpack-plugin brings that hasn't been explained before is that all the other methods mentioned here still bundle the resources into your bundle files (and require you to "require" or "import" them somewhere). If I just want to move some images around or some template partials, I don't want to clutter up my javascript bundle file with useless references to them, I just want the files emitted in the right place. I haven't found any other way to do this in webpack. Admittedly it's not what webpack originally was designed for, but it's definitely a current use case. (@BreakDS I hope this answers your question - it's only a benefit if you want it)
Because you have this:
Blowfish(BlowfishAlgorithm algorithm);
It's not a default constructor. The default constructor is one which takes no parameters. i.e.
Blowfish();
Check out printf...
#!/bin/bash
mystr="say \"hi\""
Without using printf
echo -e $mystr
Output: say "hi"
Using printf
echo -e $(printf '%q' $mystr)
Output: say \"hi\"
You can also use an object-oriented path with pathlib
(available as a standard library as of Python 3.4):
from pathlib import Path
start_path = Path('/my/root/directory')
final_path = start_path / 'in' / 'here'
The line height of the <br>
can be different from the line height of the rest of the text inside a <p>
. You can control the line height of your <br>
tags independently of the rest of the text by enclosing two of them in a <span>
that is styled. Use the line-height
css property, as others have suggested.
<p class="normalLineHeight">
Lots of text here which will display on several lines with normal line height if you put it in a narrow container...
<span class="customLineHeight"><br><br></span>
After a custom break, this text will again display on several lines with normal line height...
</p>
You are not providing a lot of information, but assuming you want to open just any file on your computer with the application that is specified for the default handler for that filetype, you can use something like this:
var fileToOpen = "SomeFilePathHere";
var process = new Process();
process.StartInfo = new ProcessStartInfo()
{
UseShellExecute = true,
FileName = fileToOpen
};
process.Start();
process.WaitForExit();
The UseShellExecute parameter tells Windows to use the default program for the type of file you are opening.
The WaitForExit will cause your application to wait until the application you luanched has been closed.
Just do System.out.println(e.getActionCommand());
inside actionPerformed(ActionEvent e)
function. This will tell you which command is just performed.
or
if(e.getActionCommand().equals("Add")){
System.out.println("Add button pressed");
}
It's the same in terms of functionality and support. (most OS recognize both, most Search Engines recognize both)
For my everyday use, I choose .htm because it's shorter to type by 25%.
There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that are defined in the List interface. If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.
Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).
That's called polymorphism. You can read up on it.
Minimal POSIX C exit status example
To understand $?
, you must first understand the concept of process exit status which is defined by POSIX. In Linux:
when a process calls the exit
system call, the kernel stores the value passed to the system call (an int
) even after the process dies.
The exit system call is called by the exit()
ANSI C function, and indirectly when you do return
from main
.
the process that called the exiting child process (Bash), often with fork
+ exec
, can retrieve the exit status of the child with the wait
system call
Consider the Bash code:
$ false
$ echo $?
1
The C "equivalent" is:
false.c
#include <stdlib.h> /* exit */
int main(void) {
exit(1);
}
bash.c
#include <unistd.h> /* execl */
#include <stdlib.h> /* fork */
#include <sys/wait.h> /* wait, WEXITSTATUS */
#include <stdio.h> /* printf */
int main(void) {
if (fork() == 0) {
/* Call false. */
execl("./false", "./false", (char *)NULL);
}
int status;
/* Wait for a child to finish. */
wait(&status);
/* Status encodes multiple fields,
* we need WEXITSTATUS to get the exit status:
* http://stackoverflow.com/questions/3659616/returning-exit-code-from-child
**/
printf("$? = %d\n", WEXITSTATUS(status));
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o bash bash.c
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o false false.c
./bash
Output:
$? = 1
In Bash, when you hit enter, a fork + exec + wait happens like above, and bash then sets $?
to the exit status of the forked process.
Note: for built-in commands like echo
, a process need not be spawned, and Bash just sets $?
to 0 to simulate an external process.
Standards and documentation
POSIX 7 2.5.2 "Special Parameters" http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_05_02 :
? Expands to the decimal exit status of the most recent pipeline (see Pipelines).
man bash
"Special Parameters":
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. [...]
? Expands to the exit status of the most recently executed foreground pipeline.
ANSI C and POSIX then recommend that:
0
means the program was successful
other values: the program failed somehow.
The exact value could indicate the type of failure.
ANSI C does not define the meaning of any vaues, and POSIX specifies values larger than 125: What is the meaning of "POSIX"?
Bash uses exit status for if
In Bash, we often use the exit status $?
implicitly to control if
statements as in:
if true; then
:
fi
where true
is a program that just returns 0.
The above is equivalent to:
true
result=$?
if [ $result = 0 ]; then
:
fi
And in:
if [ 1 = 1 ]; then
:
fi
[
is just an program with a weird name (and Bash built-in that behaves like it), and 1 = 1 ]
its arguments, see also: Difference between single and double square brackets in Bash
A list can be sorted and deduplicated using built-in functions:
myList = sorted(set(myList))
only one side outline
wont work you can use the border-left/right/top/bottom
if i an getting properly your comment
First to answer your question, you set a variable to true or false by assigning True
or False
to it:
myFirstVar = True
myOtherVar = False
If you have a condition that is basically like this though:
if <condition>:
var = True
else:
var = False
then it is much easier to simply assign the result of the condition directly:
var = <condition>
In your case:
match_var = a == b
This stuff comes from ES file explorer
Just go into this app > settings
Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good
For texts in utf-8, it worked for me mb_convert_encoding. To process everything regardless of errors, make sure you use the "@".
The basic code I use is:
$dom = new DOMDocument();
@$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
$body = $dom->getElementsByTagName('body')->item(0);
echo $body->textContent;
If you want something more advanced, you can iteratively analyze the nodes, but you will encounter many problems with whitespaces.
I have implemented a converter based on what I say here. If you are interested, you can download it from git https://github.com/kranemora/html2text
It may serve as a reference to make yours
You can use it like this:
$html = <<<EOF
<p>Welcome to <strong>html2text<strong></p>
<p>It's <em>works</em> for you?</p>
EOF;
$html2Text = new \kranemora\Html2Text\Html2Text;
$text = $html2Text->convert($html);
keystore simply stores private keys, wheras truststore stores public keys. You will want to generate a java certificate for SSL communication. You can use a keygen command in windows, this will probably be the most easy solution.
The problem here is that a compliant implementation does not need to put your classes in a compile .cpp file. If the compiler can optimize out the existence of a class, so long as the program behaves the same way without it, then it can be omitted from the output executable.
C has a standardized binary interface. Therefore you'll be able to know that your functions are exported. But C++ has no such standard behind it.
Firstly, use these settings for Google:
$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls"; //edited from tsl
$mail->Username = "myEmail";
$mail->Password = "myPassword";
$mail->Port = "587";
But also, what firewall have you got set up?
If you're filtering out TCP ports 465/995, and maybe 587, you'll need to configure some exceptions or take them off your rules list.
I have found that in order to really do it right you end up having to do something similar to
if ( ( ![myString isEqual:[NSNull null]] ) && ( [myString length] != 0 ) ) {
}
Otherwise you get weird situations where control will still bypass your check. I haven't come across one that makes it past the isEqual
and length checks.
i will provide mine because @muni s solution was a bit overkill for me
note: if you want to add custom definitions for several resolutions together, say something like this:
//mobile generally
@media screen and (max-width: 1199) {
.irns-desktop{
display: none;
}
.irns-mobile{
display: initial;
}
}
Be sure to add those definitions on top of the accurate definitions, so it cascades correctly (e.g. 'smartphone portrait' must win versus 'mobile generally')
//here all definitions to apply globally
//desktop
@media only screen
and (min-width : 1200) {
}
//tablet landscape
@media screen and (min-width: 1024px) and (max-width: 1600px) {
} // end media query
//tablet portrait
@media screen and (min-width: 768px) and (max-width: 1023px) {
}//end media definition
//smartphone landscape
@media screen and (min-width: 480px) and (max-width: 767px) {
}//end media query
//smartphone portrait
@media screen /*and (min-width: 320px)*/
and (max-width: 479px) {
}
//end media query
You may use the following code to remove non-English letters:
import re
str = "123456790 ABC#%? .(???)"
result = re.sub(r'[^\x00-\x7f]',r'', str)
print(result)
This will return
123456790 ABC#%? .()
If you want more control over how the conversion takes place, you can use ConvertAll:
var stringList = myList.ConvertAll(obj => obj.SomeToStringMethod());
List<string> myCollection = new List<string>()
{
"Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};
myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}
output: Abdi 3 Alex 2 Bob 4
Yep:
WITH tab (
bla bla
)
INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos ( BatchID, AccountNo,
APartyNo,
SourceRowID)
SELECT * FROM tab
Note that this is for SQL Server, which supports multiple CTEs:
WITH x AS (), y AS () INSERT INTO z (a, b, c) SELECT a, b, c FROM y
Teradata allows only one CTE and the syntax is as your example.
There maybe various answers for the above issue, below is a aggregated solution.
For Ubuntu:
$ sudo apt update
$ sudo apt install python-dev
$ sudo apt install python-MySQLdb
For CentOS:
$ yum install python-devel mysql-devel
if you want to add column name from a list
df=pd.DataFrame()
a=['col1','col2','col3','col4']
for i in a:
df[i]=np.nan
MVVM + WinForms FolderBrowserDialog as behavior
public class FolderDialogBehavior : Behavior<Button>
{
public string SetterName { get; set; }
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Click += OnClick;
}
protected override void OnDetaching()
{
AssociatedObject.Click -= OnClick;
}
private void OnClick(object sender, RoutedEventArgs e)
{
var dialog = new FolderBrowserDialog();
var result = dialog.ShowDialog();
if (result == DialogResult.OK && AssociatedObject.DataContext != null)
{
var propertyInfo = AssociatedObject.DataContext.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => p.CanRead && p.CanWrite)
.Where(p => p.Name.Equals(SetterName))
.First();
propertyInfo.SetValue(AssociatedObject.DataContext, dialog.SelectedPath, null);
}
}
}
Usage
<Button Grid.Column="3" Content="...">
<Interactivity:Interaction.Behaviors>
<Behavior:FolderDialogBehavior SetterName="SomeFolderPathPropertyName"/>
</Interactivity:Interaction.Behaviors>
</Button>
Blogpost: http://kostylizm.blogspot.ru/2014/03/wpf-mvvm-and-winforms-folder-dialog-how.html
I used jQuery .scroll() function to track the event of the toolbar scroll value using scrollTop. I then used a conditional to determine if it was greater than the value on what I wanted to replace. In the below example it was "Results". If the value was true then the results-label added a class 'fixedSimilarLabel' and the new styles were then taken into account.
$('.toolbar').scroll(function (e) {
//console.info(e.currentTarget.scrollTop);
if (e.currentTarget.scrollTop >= 130) {
$('.results-label').addClass('fixedSimilarLabel');
}
else {
$('.results-label').removeClass('fixedSimilarLabel');
}
});
adb reboot
should not reboot your linux box.
But in any case, you can redirect the command to a specific adb device using adb -s <device_id> command
, where
Device ID can be obtained from the command adb devices
command in this case is reboot
You can set its before
and after
to force a constant width-to-height ratio
HTML:
<div class="squared"></div>
CSS:
.squared {
background: #333;
width: 300px;
}
.squared::before {
content: '';
padding-top: 100%;
float: left;
}
.squared::after {
content: '';
display: block;
clear: both;
}
if you are using mysql .. you can save date as "2009-12-31" for example.
update person set birthday_date = '2009-12-31'
but i prefer to use jdbc although you have to create java.sql.Date ...
*Date is kind of evil in this world ... :)
Note the ""
at the beginning and at the end!
Run a program and pass a Long Filename
cmd /c write.exe "c:\sample documents\sample.txt"
Spaces in Program Path
cmd /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in Program Path + parameters
cmd /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
Spaces in Program Path + parameters with spaces
cmd /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch Demo1 and then Launch Demo2
cmd /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
string[] a = new string[0];
or short notation:
string[] a = { };
The preferred way now is:
var a = Array.Empty<string>();
I have written a short regular expression that you can use in Visual Studio if you want to replace zero-length allocations e.g. new string[0]
.
Use Find (search) in Visual Studio with Regular Expression option turned on:
new[ ][a-zA-Z0-9]+\[0\]
Now Find All or F3 (Find Next) and replace all with Array.Empty<…>() !
You can just pass it on the command line, as
mvn -DmyVariable=someValue install
[Update] Note that the order of parameters is significant - you need to specify any options before the command(s).[/Update]
Within the POM file, you may refer to system variables (specified on the command line, or in the pom) as ${myVariable}
, and environment variables as ${env.myVariable}
. (Thanks to commenters for the correction.)
OK, so you want to pass your system variable to your tests. If - as I assume - you use the Surefire plugin for testing, the best is to specify the needed system variable(s) within the pom, in your plugins
section, e.g.
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
...
<configuration>
...
<systemPropertyVariables>
<WSNSHELL_HOME>conf</WSNSHELL_HOME>
</systemPropertyVariables>
</configuration>
</plugin>
...
</plugins>
</build>
Your question How can I just get the file-names (with paths)
Your syntax example find . -iname "*php" -exec grep -H myString {} \;
My Command suggestion
sudo find /home -name *.php
The output from this command on my Linux OS:
compose-sample-3/html/mail/contact_me.php
As you require the filename with path, enjoy!
I'll try to explain it visually:
/**_x000D_
* explaining margins_x000D_
*/_x000D_
_x000D_
body {_x000D_
padding: 3em 15%_x000D_
}_x000D_
_x000D_
.parent {_x000D_
width: 50%;_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
position: relative;_x000D_
background: lemonchiffon;_x000D_
}_x000D_
_x000D_
.parent:before,_x000D_
.parent:after {_x000D_
position: absolute;_x000D_
content: "";_x000D_
}_x000D_
_x000D_
.parent:before {_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 50%;_x000D_
border-left: dashed 1px #ccc;_x000D_
}_x000D_
_x000D_
.parent:after {_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 50%;_x000D_
border-top: dashed 1px #ccc;_x000D_
}_x000D_
_x000D_
.child {_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
background: rgba(200, 198, 133, .5);_x000D_
}_x000D_
_x000D_
ul {_x000D_
padding: 5% 20px;_x000D_
}_x000D_
_x000D_
.set1 .child {_x000D_
margin: 0;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.set2 .child {_x000D_
margin-left: 75px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.set3 .child {_x000D_
margin-left: -75px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
_x000D_
/* position absolute */_x000D_
_x000D_
.set4 .child {_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
margin: 0;_x000D_
position: absolute;_x000D_
}_x000D_
_x000D_
.set5 .child {_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
margin-left: 75px;_x000D_
position: absolute;_x000D_
}_x000D_
_x000D_
.set6 .child {_x000D_
top: 50%; /* level from which margin-top starts _x000D_
- downwards, in the case of a positive margin_x000D_
- upwards, in the case of a negative margin _x000D_
*/_x000D_
left: 50%; /* level from which margin-left starts _x000D_
- towards right, in the case of a positive margin_x000D_
- towards left, in the case of a negative margin _x000D_
*/_x000D_
margin: -75px;_x000D_
position: absolute;_x000D_
}
_x000D_
<!-- content to be placed inside <body>…</body> -->_x000D_
<h2><code>position: relative;</code></h2>_x000D_
<h3>Set 1</h3>_x000D_
<div class="parent set 1">_x000D_
<div class="child">_x000D_
<pre>_x000D_
.set1 .child {_x000D_
margin: 0;_x000D_
position: relative;_x000D_
}_x000D_
</pre>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 2</h3>_x000D_
<div class="parent set2">_x000D_
<div class="child">_x000D_
<pre>_x000D_
.set2 .child {_x000D_
margin-left: 75px;_x000D_
position: relative;_x000D_
}_x000D_
</pre>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 3</h3>_x000D_
<div class="parent set3">_x000D_
<div class="child">_x000D_
<pre>_x000D_
.set3 .child {_x000D_
margin-left: -75px;_x000D_
position: relative;_x000D_
}_x000D_
</pre>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h2><code>position: absolute;</code></h2>_x000D_
_x000D_
<h3>Set 4</h3>_x000D_
<div class="parent set4">_x000D_
<div class="child">_x000D_
<pre>_x000D_
.set4 .child {_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
margin: 0;_x000D_
position: absolute;_x000D_
}_x000D_
</pre>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 5</h3>_x000D_
<div class="parent set5">_x000D_
<div class="child">_x000D_
<pre>_x000D_
.set5 .child {_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
margin-left: 75px;_x000D_
position: absolute;_x000D_
}_x000D_
</pre>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 6</h3>_x000D_
<div class="parent set6">_x000D_
<div class="child">_x000D_
<pre>_x000D_
.set6 .child {_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
margin: -75px;_x000D_
position: absolute;_x000D_
}_x000D_
</pre>_x000D_
</div>_x000D_
</div>
_x000D_
You might want to look at the DecimalFormat
class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57
instead).
You also need to convert that string into a number, this can be done with:
double amount = Double.parseDouble(number);
Code sample:
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(amount));
I am also very much new to Dynamic Programming (a powerful algorithm for particular type of problems)
In most simple words, just think dynamic programming as a recursive approach with using the previous knowledge
Previous knowledge is what matters here the most, Keep track of the solution of the sub-problems you already have.
Consider this, most basic example for dp from Wikipedia
Finding the fibonacci sequence
function fib(n) // naive implementation
if n <=1 return n
return fib(n - 1) + fib(n - 2)
Lets break down the function call with say n = 5
fib(5)
fib(4) + fib(3)
(fib(3) + fib(2)) + (fib(2) + fib(1))
((fib(2) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + fib(1))
(((fib(1) + fib(0)) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + fib(1))
In particular, fib(2) was calculated three times from scratch. In larger examples, many more values of fib, or sub-problems, are recalculated, leading to an exponential time algorithm.
Now, lets try it by storing the value we already found out in a data-structure say a Map
var m := map(0 ? 0, 1 ? 1)
function fib(n)
if key n is not in map m
m[n] := fib(n - 1) + fib(n - 2)
return m[n]
Here we are saving the solution of sub-problems in the map, if we don't have it already. This technique of saving values which we already had calculated is termed as Memoization.
At last, For a problem, first try to find the states (possible sub-problems and try to think of the better recursion approach so that you can use the solution of previous sub-problem into further ones).
read
does not export the variable (which is a good thing most of the time). Here's an alternative which can be exported in one command, can preserve or discard linefeeds, and allows mixing of quoting-styles as needed. Works for bash and zsh.
oneLine=$(printf %s \
a \
" b " \
$'\tc\t' \
'd ' \
)
multiLine=$(printf '%s\n' \
a \
" b " \
$'\tc\t' \
'd ' \
)
I admit the need for quoting makes this ugly for SQL, but it answers the (more generally expressed) question in the title.
I use it like this
export LS_COLORS=$(printf %s \
':*rc=36:*.ini=36:*.inf=36:*.cfg=36:*~=33:*.bak=33:*$=33' \
...
':bd=40;33;1:cd=40;33;1:or=1;31:mi=31:ex=00')
in a file sourced from both my .bashrc
and .zshrc
.
For the above code to function; you need to make sure the following directories exist (mine didn't). Just add the following to a bat and run it:
mkdir C:\Windows\System32\GroupPolicy\Machine\Scripts\Startup
mkdir C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown
mkdir C:\Windows\System32\GroupPolicy\User\Scripts\Startup
mkdir C:\Windows\System32\GroupPolicy\User\Scripts\Shutdown
It's just that GP needs those directories to exist for:
Group Policy\Local Computer Policy\Windows Settings\Scripts (Startup/Shutdown)
to function properly.
I realize this is an old post but it's one of the first that comes up when searching for c++ serialization
.
I encourage anyone who has access to C++11 to take a look at cereal, a C++11 header only library for serialization that supports binary, JSON, and XML out of the box. cereal was designed to be easy to extend and use and has a similar syntax to Boost.
This is another example using values with select:
INSERT INTO table1(desc, id, email)
SELECT "Hello World", 3, email FROM table2 WHERE ...
Remove those char * ret
declarations inside if
blocks which hide outer ret
. Therefor you have memory leak and on the other hand un-allocated memory for ret
.
To compare a c-style string you should use strcmp(array,"")
not array!=""
. Your final code should looks like below:
char* appendCharToCharArray(char* array, char a)
{
size_t len = strlen(array);
char* ret = new char[len+2];
strcpy(ret, array);
ret[len] = a;
ret[len+1] = '\0';
return ret;
}
Note that, you must handle the allocated memory of returned ret
somewhere by delete[]
it.
Why you don't use std::string
? it has .append
method to append a character at the end of a string:
std::string str;
str.append('x');
// or
str += x;
I found this worked best for me:
docker image prune --all
By default Docker will not remove named images, even if they are unused. This command will remove unused images.
Note each layer in an image is a folder inside the /usr/lib/docker/overlay2/
folder.
I encountered this issue by putting a XML file into the src/main/resources
wrongly, I deleted it and then all back to normal.
Currently there are 2 options for Git Source Control in Visual Studio (2010 and 12):
I have tried both and have found 1st one to be more mature, and has more features. For instance it plays nicely with both tortoise git and git extensions, and even exposed their features.
Note: Whichever extension you use, make sure that you enable it from Tools -> Options -> Source control -> Plugin Selection
for it to work.
An incomplete type
error is when the compiler encounters the use of an identifier that it knows is a type, for instance because it has seen a forward-declaration of it (e.g. class stringstream;
), but it hasn't seen a full definition for it (class stringstream { ... };
).
This could happen for a type that you haven't used in your own code but is only present through included header files -- when you've included header files that use the type, but not the header file where the type is defined. It's unusual for a header to not itself include all the headers it needs, but not impossible.
For things from the standard library, such as the stringstream
class, use the language standard or other reference documentation for the class or the individual functions (e.g. Unix man
pages, MSDN library, etc.) to figure out what you need to #include
to use it and what namespace to find it in if any. You may need to search for pages where the class name appears (e.g. man -k stringstream
).
It's very easy to write in PHP using strlen
and strpos
functions:
function isRotation($string1, $string2) {
return strlen($string1) == strlen($string2) && (($string1.$string1).strpos($string2) != -1);
}
I don't know what strpos
uses internally, but if it uses KMP this will be linear in time.
Yes you can use CASE
UPDATE table
SET columnB = CASE fieldA
WHEN columnA=1 THEN 'x'
WHEN columnA=2 THEN 'y'
ELSE 'z'
END
WHERE columnC = 1
It happens because Build Tools revision 24.4.1 doesn't exist.
The latest version is 23.0.2.
These tools is included in the SDK package and installed in the <sdk>/build-tools/
directory.
Don't confuse the Android SDK Tools with SDK Build Tools.
Change in your build.gradle
android {
buildToolsVersion "23.0.2"
// ...
}
It worked for me, but only with ssh key and not with username and password.
After i added the ssh key to sourcetree, i changed the settings under Tools -> Options -> SSH-Client to work with PuTTY/Plink.
I run into trouble after i added the ssh key, because i forgot to restart sourceTree. "this is necessary so that there is an instance of ssh-agent running that SourceTree can talk to with your key loaded." See here: https://answers.atlassian.com/questions/189412/sourcetree-with-gitlab-ssh-not-working
A newer way to do this in .NET Core is with TagHelpers
.
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro
Building on these examples (MaxLength, Label), you can extend the existing TagHelper
to suit your needs.
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.Linq;
namespace ProjectName.TagHelpers
{
[HtmlTargetElement("input", Attributes = "asp-for")]
public class RequiredTagHelper : TagHelper
{
public override int Order
{
get { return int.MaxValue; }
}
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
base.Process(context, output);
if (context.AllAttributes["required"] == null)
{
var isRequired = For.ModelExplorer.Metadata.ValidatorMetadata.Any(a => a is RequiredAttribute);
if (isRequired)
{
var requiredAttribute = new TagHelperAttribute("required");
output.Attributes.Add(requiredAttribute);
}
}
}
}
}
You'll then need to add it to be used in your views:
@using ProjectName
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "*, ProjectName"
Given the following model:
using System;
using System.ComponentModel.DataAnnotations;
namespace ProjectName.Models
{
public class Foo
{
public int Id { get; set; }
[Required]
[Display(Name = "Full Name")]
public string Name { get; set; }
}
}
and view (snippet):
<label asp-for="Name"></label>
<input asp-for="Name"/>
Will result in this HTML:
<label for="Name">Full Name</label>
<input required type="text" data-val="true" data-val-required="The Full Name field is required." id="Name" name="Name" value=""/>
I hope this is helpful to anyone with same question but using .NET Core.
The simplest way that doesn't require third party libraries it to create a URL object and then call either openConnection or openStream on it. Note that this is a pretty basic API, so you won't have a lot of control over the headers.
Try this
<style>
@font-face {
font-family: Roboto Bold Condensed;
src: url(fonts/Roboto_Condensed/RobotoCondensed-Bold.ttf);
}
@font-face {
font-family:Roboto Condensed;
src: url(fonts/Roboto_Condensed/RobotoCondensed-Regular.tff);
}
div1{
font-family:Roboto Bold Condensed;
}
div2{
font-family:Roboto Condensed;
}
</style>
<div id='div1' >This is Sample text</div>
<div id='div2' >This is Sample text</div>
uint32_t
is defined in the standard, in
<cstdint>
synopsis [cstdint.syn]namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}
uint32
is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32
) for ease of use.
With recent Maven versions (3) and recent version of the maven compiler plugin (3.7.0), I notice that adding a source folder with the build-helper-maven-plugin
is not required if the folder that contains the source code to add in the build is located in the target
folder or a subfolder of it.
It seems that the compiler maven plugin compiles any java source code located inside this folder whatever the directory that contains them.
For example having some (generated or no) source code in target/a
, target/generated-source/foo
will be compiled and added in the outputDirectory : target/classes
.
As far as concerns, you want to delete rows in story_category
that do not exist in category
.
Here is your original query to identify the rows to delete:
SELECT *
FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category INNER JOIN
story_category ON category_id=category.id
);
Combining NOT IN
with a subquery that JOIN
s the original table seems unecessarily convoluted. This can be expressed in a more straight-forward manner with not exists
and a correlated subquery:
select sc.*
from story_category sc
where not exists (select 1 from category c where c.id = sc.category_id);
Now it is easy to turn this to a delete
statement:
delete from story_category
where not exists (select 1 from category c where c.id = story_category.category_id);
This quer would run on any MySQL version, as well as in most other databases that I know.
-- set-up
create table story_category(category_id int);
create table category (id int);
insert into story_category values (1), (2), (3), (4), (5);
insert into category values (4), (5), (6), (7);
-- your original query to identify offending rows
SELECT *
FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category INNER JOIN
story_category ON category_id=category.id);
| category_id | | ----------: | | 1 | | 2 | | 3 |
-- a functionally-equivalent, simpler query for this
select sc.*
from story_category sc
where not exists (select 1 from category c where c.id = sc.category_id)
| category_id | | ----------: | | 1 | | 2 | | 3 |
-- the delete query
delete from story_category
where not exists (select 1 from category c where c.id = story_category.category_id);
-- outcome
select * from story_category;
| category_id | | ----------: | | 4 | | 5 |
To start with Socket.IO I suggest you read first the example on the main page:
On the server side, read the "How to use" on the GitHub source page:
https://github.com/Automattic/socket.io
And on the client side:
https://github.com/Automattic/socket.io-client
Finally you need to read this great tutorial:
http://howtonode.org/websockets-socketio
Hint: At the end of this blog post, you will have some links pointing on source code that could be some help.
Using sshpass works best. To just include your password in scp use the ' ':
scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/
It seems that in VBA macro code for an ActiveX checkbox control you use
If (ActiveSheet.OLEObjects("CheckBox1").Object.Value = True)
and for a Form checkbox control you use
If (ActiveSheet.Shapes("CheckBox1").OLEFormat.Object.Value = 1)
If you are running the container as a service
using docker swarm
, you can do:
docker service update --env-add <you environment variable> <service_name>
Also remove using --env-rm
To make sure it's addedd as you wanted, just run:
docker exec -it <container id> env
yes you need to use a having clause after the Group by clause , as the where is just to filter the data on simple parameters , but group by followed by a Having statement is the idea to group the data and filter it on basis of some aggregate function......
#pragma comment(lib,"ntdll.lib")
EXTERN_C NTSTATUS NTAPI NtSuspendProcess(IN HANDLE ProcessHandle);
void SuspendSelf(){
NtSuspendProcess(GetCurrentProcess());
}
ntdll contains the exported function NtSuspendProcess, pass the handle to a process to do the trick.
A bit late maybe, but if you are not worried about duplicate column names:
df.columns = df.columns.tolist()
That's the HTML data attribute. See this for more detail: http://html5doctor.com/html5-custom-data-attributes/
Basically it's just a container of your custom data while still making the HTML valid.
It's data-
plus some unique identifier.
If you're talking MS SQL, here's the most efficient way. This retrieves the current identity seed from a table based on whatever column is the identity.
select IDENT_CURRENT('TableName') as LastIdentity
Using MAX(id)
is more generic, but for example I have an table with 400 million rows that takes 2 minutes to get the MAX(id)
. IDENT_CURRENT
is nearly instantaneous...
rmdir /s /q folder
powershell -Command "Remove-Item -LiteralPath 'folder' -Force -Recurse"
Note that in more cases del
and rmdir
wil leave you with leftover files, where Powershell manages to delete the files.
There are workarounds but no clean/short/sweet way to do it with streams and to be honest, you would probably be better off with:
int idx = 0;
for (Param p : params) query.bind(idx++, p);
Or the older style:
for (int idx = 0; idx < params.size(); idx++) query.bind(idx, params.get(idx));
How about this?
SUM(IF(PaymentType = "credit card", totalamount, 0)) AS CreditCardTotal
In HTML 5 you could also use:
onpageshow
: Script to be run when the window becomes visibleonpagehide
: Script to be run when the window is hiddenSee:
Here is the complete step-by-step method that worked for me in order to update the LINQ to SQL dbml and associated files to include a new column that I added to one of the database tables.
You need to make the changes to your design surface as suggested by other above; however, you need to do some extra steps. These are the complete steps:
Drag your updated table from Server Explorer onto the design surface
Copy the new column from this "new" table to the "old" table (see M463 answer for details on this step)
Delete the "new" table that you just dragged over
Click and highlight the stored procedure, then delete it
Drag the new stored procedure and drop into place.
Delete the .designer.vb file in the code-behind of the .dbml (if you do not delete this, your code-behind containing the schema will not update even if you rebuild and the new table field will not be included)
Clean and Rebuild the solution (this will rebuild the .designer.vb file to include all the new changes!).
As BrianCampbell points out here, SQLite 3.7.11 and above now supports the simpler syntax of the original post. However, the approach shown is still appropriate if you want maximum compatibility across legacy databases.
If I had privileges, I would bump river's reply: You can insert multiple rows in SQLite, you just need different syntax. To make it perfectly clear, the OPs MySQL example:
INSERT INTO 'tablename' ('column1', 'column2') VALUES
('data1', 'data2'),
('data1', 'data2'),
('data1', 'data2'),
('data1', 'data2');
This can be recast into SQLite as:
INSERT INTO 'tablename'
SELECT 'data1' AS 'column1', 'data2' AS 'column2'
UNION ALL SELECT 'data1', 'data2'
UNION ALL SELECT 'data1', 'data2'
UNION ALL SELECT 'data1', 'data2'
I originally used this technique to efficiently load large datasets from Ruby on Rails. However, as Jaime Cook points out, it's not clear this is any faster wrapping individual INSERTs
within a single transaction:
BEGIN TRANSACTION;
INSERT INTO 'tablename' table VALUES ('data1', 'data2');
INSERT INTO 'tablename' table VALUES ('data3', 'data4');
...
COMMIT;
If efficiency is your goal, you should try this first.
As several people commented, if you use UNION ALL
(as shown above), all rows will be inserted, so in this case, you'd get four rows of data1, data2
. If you omit the ALL
, then duplicate rows will be eliminated (and the operation will presumably be a bit slower). We're using UNION ALL since it more closely matches the semantics of the original post.
P.S.: Please +1 river's reply, as it presented the solution first.
RegEx to match everything between two strings using the Java approach.
List<String> results = new ArrayList<>(); //For storing results
String example = "Code will save the world";
Let's use Pattern and Matcher objects to use RegEx (.?)*.
Pattern p = Pattern.compile("Code "(.*?)" world"); //java.util.regex.Pattern;
Matcher m = p.matcher(example); //java.util.regex.Matcher;
Since Matcher might contain more than one match, we need to loop over the results and store it.
while(m.find()){ //Loop through all matches
results.add(m.group()); //Get value and store in collection.
}
This example will contain only "will save the" word, but in the bigger text it will probably find more matches.
You have another server_name ec2-xx-xx-xxx-xxx.us-west-1.compute.amazonaws.com
somewhere in the config.
Wikipedia makes heavy use of this feature like this:
<a href="#History">[...]</a>
<span class="mw-headline" id="History">History</span>
And Wikipedia is working for everybody, so I would feel safe sticking with this form.
Also don't forget, you can use this not only with spans but with divs or even table cells, and then you have access to the :target pseudo-class on the element. Just watch out not to change the width, like with bold text, cause that moves content around, which is disturbing.
Named anchors - my vote is to avoid:
You have to enable Developer options and enable USB Debugging:
http://www.androidcentral.com/how-enable-developer-settings-android-42
Inside Developer Options
, enable USB Debugging
One extra forward slash (/) in front of tx and the *.xml file troubled me for 8 hours!!
My mistake:
http://www.springframework.org/schema/tx/ http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
Correction:
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
Indeed one character less/more manages to keep programmers busy for hours!
As @Matt answered the reason of [object object]
, I will expand on how to inspect the value of the object. There are three options on top of my mind:
JSON.stringify(JSONobject)
console.log(JSONobject)
Basic example.
var jsonObj={
property1 : "one",
property2 : "two",
property3 : "three",
property4 : "fourth",
};
var strBuilder = [];
for(key in jsonObj) {
if (jsonObj.hasOwnProperty(key)) {
strBuilder.push("Key is " + key + ", value is " + jsonObj[key] + "\n");
}
}
alert(strBuilder.join(""));
// or console.log(strBuilder.join(""))
If you want to run this command using a python script within a Linux terminal...
import os,sys
LINE = 'include '+ <insert_line_STRING>
FILE = <insert_file_path_STRING>
os.system('grep -qxF $"'+LINE+'" '+FILE+' || echo $"'+LINE+'" >> '+FILE)
The $ and double quotations had me in a jungle, but this worked. Thanks everyone
Step 1
My computer > properties > Advance system settings
Step 2
environment variables > click New button under user variables > Enter variable name as 'PATH'
Copy the location of java bin (e.g:C:\Program Files\Java\jdk1.8.0_121\bin)
and paste it in Variable value and click OK Now open the eclipse.
This is similar to the top answer, but I like it better because it avoids explicit indexing. Assuming your list has the name lst
, you can generate
(item, next_item)
tuples from your list with zip
:
all(x <= y for x,y in zip(lst, lst[1:]))
In Python 3, zip
already returns a generator, in Python 2 you can use itertools.izip
for better memory efficiency.
Small demo:
>>> lst = [1, 2, 3, 4]
>>> zip(lst, lst[1:])
[(1, 2), (2, 3), (3, 4)]
>>> all(x <= y for x,y in zip(lst, lst[1:]))
True
>>>
>>> lst = [1, 2, 3, 2]
>>> zip(lst, lst[1:])
[(1, 2), (2, 3), (3, 2)]
>>> all(x <= y for x,y in zip(lst, lst[1:]))
False
The last one fails when the tuple (3, 2)
is evaluated.
Bonus: checking finite (!) generators which cannot be indexed:
>>> def gen1():
... yield 1
... yield 2
... yield 3
... yield 4
...
>>> def gen2():
... yield 1
... yield 2
... yield 4
... yield 3
...
>>> g1_1 = gen1()
>>> g1_2 = gen1()
>>> next(g1_2)
1
>>> all(x <= y for x,y in zip(g1_1, g1_2))
True
>>>
>>> g2_1 = gen2()
>>> g2_2 = gen2()
>>> next(g2_2)
1
>>> all(x <= y for x,y in zip(g2_1, g2_2))
False
Make sure to use itertools.izip
here if you are using Python 2, otherwise you would defeat the purpose of not having to create lists from the generators.
According to the closure
definition:
A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
You are using closure
if you define a function which use a variable which is defined outside of the function. (we call the variable a free variable).
They all use closure
(even in the 1st example).
str.replace(new RegExp(".","gm")," ")
You have to give a valid username. For example, to run query with user root
you have to type the following command and then enter password when prompted:
mysql -u root -p
Once you are connected, prompt will be something like:
mysql>
Here you can write your query, after database selection, for example:
mysql> USE your_database;
mysql> SELECT * FROM your_table;
You can use TelephonyManager to do that .
In a batch file solution
for /R c:\source %%f in (*.xml) do copy %%f x:\destination\
The code works as such;
for each file for
in directory c:\source
and subdirectories /R
that match pattern (\*.xml)
put the file name in variable %%f
, then for each file do
copy file copy %%f
to destination x:\\destination\\
Just tested it here on my Windows XP computer and it worked like a treat for me. But I typed it into command prompt so I used the single %f
variable name version, as described in the linked question above.
A simple check like this will let you know if it exists/defined:
if (this.onsubmit)
{
// do stuff;
}
I've got that problem because of some internall error in Android plugin. When I've tried to open some layout xml, I've got error:
The project target (Android 2.2) was not properly loaded.
Fortunatelly in my case restarting Eclipse and cleaning the project helped.
Yes. You can use Process.Start
to launch an executable, including a console application.
If you need to read the output from the application, you may need to read from it's StandardOutput stream in order to get anything printed from the application you launch.
import urllib.request
bank_pdf_list = ["https://www.hdfcbank.com/content/bbp/repositories/723fb80a-2dde-42a3-9793-7ae1be57c87f/?path=/Personal/Home/content/rates.pdf",
"https://www.yesbank.in/pdf/forexcardratesenglish_pdf",
"https://www.sbi.co.in/documents/16012/1400784/FOREX_CARD_RATES.pdf"]
def get_pdf(url):
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
#url = "https://www.yesbank.in/pdf/forexcardratesenglish_pdf"
headers={'User-Agent':user_agent,}
request=urllib.request.Request(url,None,headers) #The assembled request
response = urllib.request.urlopen(request)
#print(response.text)
data = response.read()
# print(type(data))
name = url.split("www.")[-1].split("//")[-1].split(".")[0]+"_FOREX_CARD_RATES.pdf"
f = open(name, 'wb')
f.write(data)
f.close()
for bank_url in bank_pdf_list:
try:
get_pdf(bank_url)
except:
pass
It helps me to see things in context. Here is a complete simple project for sending data back. Rather than providing the xml layout files, here is an image.
startActivityForResult
, providing it an arbitrary result code.onActivityResult
. This is called when the Second Activity finishes. You can make sure that it is actually the Second Activity by checking the request code. (This is useful when you are starting multiple different activities from the same main activity.)Intent
. The data is extracted using a key-value pair.MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// "Go to Second Activity" button click
public void onButtonClick(View view) {
// Start the SecondActivity
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
}
// This method is called when the second activity finishes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check that it is the SecondActivity with an OK result
if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Get String data from Intent
String returnString = data.getStringExtra("keyName");
// Set text view with string
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(returnString);
}
}
}
}
Intent
. The data is stored in the Intent
using a key-value pair.RESULT_OK
and add the intent holding your data.finish()
to close the Second Activity.SecondActivity.java
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
// "Send text back" button click
public void onButtonClick(View view) {
// Get the text from the EditText
EditText editText = (EditText) findViewById(R.id.editText);
String stringToPassBack = editText.getText().toString();
// Put the String to pass back into an Intent and close this activity
Intent intent = new Intent();
intent.putExtra("keyName", stringToPassBack);
setResult(RESULT_OK, intent);
finish();
}
}
RESULT_OK
. Just use the full name: Activity.RESULT_OK
.Try storing the connection string along with the password in a variable and assign the variable in the connection string using expression.I also faced the same issue and I solved like dis.
In Spring MVC you get the HtppServletResponce object by default .
@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception{
//Do service call passing the response
return new ModelAndView("CustomerAddView");
}
//Service code
Cookie myCookie =
new Cookie("name", "val");
response.addCookie(myCookie);
This happens because your click
handler fires before the value of the radio button changes. You need to listen to the change
event instead:
<input
type="radio"
name="optionsRadios"
id="optionsRadios2"
value=""
v-model="srStatus"
v-on:change="foo"> //here
Also, make sure you really want to call foo()
on ready... seems like maybe you don't actually want to do that.
ready:function(){
foo();
},
Another alternative, if you already have an instance of the object created and you want to add it as an @autowired dependency to initialize all the internal @autowired variables, could be the following:
@Autowired
private AutowireCapableBeanFactory autowireCapableBeanFactory;
public void doStuff() {
YourObject obj = new YourObject("Value X", "etc");
autowireCapableBeanFactory.autowireBean(obj);
}
The easiest way to handle this is to install the full package installer with all weblogic add ons from the oracle site. This will install eclipse with all the features/plug ins you need.
Hope this is your structure:
<ul>
<li>
<div ><img.. /><p>text</p></div>
</li>
<li>
<div ><img.. /><p>text</p></div>
</li>
<li>
<div ><img.. /><p>text</p></div>
</li>
</ul>
By default, it will be add one after another row:
-----
-----
-----
if you want to make it vertical, just add float left to li, give width and height, make sure that content will not break the width:
| | |
| | |
li
{
display:block;
float:left;
width:300px; /* adjust */
height:150px; /* adjust */
padding: 5px; /*adjust*/
}
Just add
model.addAttribute("login", new Login());
to your method ..
it will work..
If you don't want jquery then you can do it with javascript :-
@Html.DropDownList("Sortby", new SelectListItem[]
{
new SelectListItem() { Text = "Newest to Oldest", Value = "0" },
new SelectListItem() { Text = "Oldest to Newest", Value = "1" }},
new { @onchange="callChangefunc(this.value)"
});
<script>
function callChangefunc(val){
window.location.href = "/Controller/ActionMethod?value=" + val;
}
</script>
Just return an object literal
function newCodes(){
var dCodes = fg.codecsCodes.rs; // Linked ICDs
var dCodes2 = fg.codecsCodes2.rs; //Linked CPTs
return {
dCodes: dCodes,
dCodes2: dCodes2
};
}
var result = newCodes();
alert(result.dCodes);
alert(result.dCodes2);
One more code sample to showcase this:
void Main()
{
int k = 0;
TestPlain(k);
Console.WriteLine("TestPlain:" + k);
TestRef(ref k);
Console.WriteLine("TestRef:" + k);
string t = "test";
TestObjPlain(t);
Console.WriteLine("TestObjPlain:" +t);
TestObjRef(ref t);
Console.WriteLine("TestObjRef:" + t);
}
public static void TestPlain(int i)
{
i = 5;
}
public static void TestRef(ref int i)
{
i = 5;
}
public static void TestObjPlain(string s)
{
s = "TestObjPlain";
}
public static void TestObjRef(ref string s)
{
s = "TestObjRef";
}
And the output:
TestPlain:0
TestRef:5
TestObjPlain:test
TestObjRef:TestObjRef
You can inspect elements of a website in your Android device using Chrome browser.
Open your Chrome browser and go to the website you want to inspect.
Go to the address bar and type "view-source:" before the "HTTP" and reload the page.
The whole elements of the page will be shown.
As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data
with participants
.
The alternative to the solution they provided would be to prevent render until participants exist, something like this:
render: function() {
if (!this.props.data.participants) {
return null;
}
return (
<ul className="PlayerList">
// I'm the Player List {this.props.data}
// <Player author="The Mini John" />
{
this.props.data.participants.map(function(player) {
return <li key={player}>{player}</li>
})
}
</ul>
);
}
Yes, H2 supports executing SQL statements when connecting. You could run a script, or just a statement or two:
String url = "jdbc:h2:mem:test;" +
"INIT=CREATE SCHEMA IF NOT EXISTS TEST"
String url = "jdbc:h2:mem:test;" +
"INIT=CREATE SCHEMA IF NOT EXISTS TEST\\;" +
"SET SCHEMA TEST";
String url = "jdbc:h2:mem;" +
"INIT=RUNSCRIPT FROM '~/create.sql'\\;" +
"RUNSCRIPT FROM '~/populate.sql'";
Please note the double backslash (\\
) is only required within Java. The backslash(es) before ;
within the INIT
is required.
Using jQuery, the following solution handles even the "drag off the page then release case".
$(document).mousedown(function(e) {
mouseDown = true;
}).mouseup(function(e) {
mouseDown = false;
}).mouseleave(function(e) {
mouseDown = false;
});
I don't know how it handles multiple mouse buttons. If there were a way to start the click outside the window, then bring the mouse into the window, then this would probably not work properly there either.
The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:
git push origin master
Which will create this new master branch for you. Little things like this are very confusing with git.
If this didn't fix your issue then it's probably a gitolite-related issue:
Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:
repo phonegap
RW+ = myusername otherusername
repo gitolite-admin
RW+ = myusername
Please make sure you're setting your conf file correctly.
Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.
Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.
Using a supposed name property as the map key:
for (Product p: productList) { s.put(p.getName(), p); }
one way is if you have a jdk installed , in bin folder there is a utility called jconsole(even visualvm can be used). Launch it and connect to the relevant java process and you can see what are the heap size settings set and many other details
When running headless or cli only, jConsole can be used over lan, if you specify a port to connect on when starting the service in question.
I also faced the same issue when I started using following maven dependency version for log4j (1.2.15) in my project.
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
</dependency>
Following error was thrown at me.
The following artifacts could not be resolved: javax.jms:jms:jar:1.1, com.sun.jdmk:jmxtools:jar:1.2.1, com.sun.jmx:jmxri:jar:1.2.1: Could not transfer artifact javax.jms:jms:jar:1.1 from/to java.net (https://maven-repository.dev.java.net/nonav/repository): Cannot access https://maven-repository.dev.java.net/nonav/repository with type legacy using the available connector factories: BasicRepositoryConnectorFactory: Cannot access https://maven-repository.dev.java.net/nonav/repository with type legacy using the available layout factories: Maven2RepositoryLayoutFactory: Unsupported repository layout legacy -> [Help 1]
I started using following log4j (1.2.17) version and it helped me solve this issue without any configurations related fixes.
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
$start_date="17/02/2012";
$end_date="21/02/2012";
$date_from_user="19/02/2012";
function geraTimestamp($data)
{
$partes = explode('/', $data);
return mktime(0, 0, 0, $partes[1], $partes[0], $partes[2]);
}
$startDatedt = geraTimestamp($start_date);
$endDatedt = geraTimestamp($end_date);
$usrDatedt = geraTimestamp($date_from_user);
if (($usrDatedt >= $startDatedt) && ($usrDatedt <= $endDatedt))
{
echo "Dentro";
}
else
{
echo "Fora";
}
I don't know is there any method in Python API.But you can use this simple code to add Salt-and-Pepper noise to an image.
import numpy as np
import random
import cv2
def sp_noise(image,prob):
'''
Add salt and pepper noise to image
prob: Probability of the noise
'''
output = np.zeros(image.shape,np.uint8)
thres = 1 - prob
for i in range(image.shape[0]):
for j in range(image.shape[1]):
rdn = random.random()
if rdn < prob:
output[i][j] = 0
elif rdn > thres:
output[i][j] = 255
else:
output[i][j] = image[i][j]
return output
image = cv2.imread('image.jpg',0) # Only for grayscale image
noise_img = sp_noise(image,0.05)
cv2.imwrite('sp_noise.jpg', noise_img)
ssh user@machine 'bash -s' < local_script.sh
or you can just
ssh user@machine "remote command to run"
I can offer you a jquery solution
add this in your <head></head>
tag
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
add this after </ul>
<script> $('ul li:first').remove(); </script>
In Swift 4:
let formatString = "12345"
if let number = Decimal(string:formatString){
print("String contains only number")
}
else{
print("String doesn't contains only number")
}
Each array and get max value with Math.
data.reduce((max, b) => Math.max(max, b.costo), data[0].costo);
This would be eliminate the select query from running twice and be better for performance:
Declare @rate int
select
@rate = rate
from
d_payment_index
where
fy = 2007
and payment_year = 2008
and program_id = 18
IF @@rowcount = 0
Set @rate = 0
Select @rate 'rate'
I found some useful information in a forum page, quoted below.
From this, mainly the sentences in bold formatting, my answer is:
Make a bash (shell) script version of your .bat file (like other
answers, with \
changed to /
in file paths). For example:
# File "example.command":
#!/bin/bash
java -cp ".;./supportlibraries/Framework_Core.jar; ...etc.
Then rename it to have the Mac OS file extension .command
.
That should make the script run using the Terminal app.
If the app user is going to use a bash script version of the file on Linux
or run it from the command line, they need to add executable rights
(change mode bits) using this command, in the folder that has the file:
chmod +rx [filename].sh
#or:# chmod +rx [filename].command
The forum page question:
Good day, [...] I wondering if there are some "simple" rules to write an equivalent
of the Windows (DOS) bat file. I would like just to click on a file and let it run.
Info from some answers after the question:
Write a shell script, and give it the extension ".command". For example:
#!/bin/bash printf "Hello World\n"
- Mar 23, 2010, Tony T1.
The DOS .BAT file was an attempt to bring to MS-DOS something like the idea of the UNIX script.
In general, UNIX permits you to make a text file with commands in it and run it by simply flagging
the text file as executable (rather than give it a specific suffix). This is how OS X does it.However, OS X adds the feature that if you give the file the suffix
.command
, Finder
will run Terminal.app to execute it (similar to how BAT files work in Windows).Unlike MS-DOS, however, UNIX (and OS X) permits you to specify what interpreter is used
for the script. An interpreter is a program that reads in text from a file and does something
with it. [...] In UNIX, you can specify which interpreter to use by making the first line in the
text file one that begins with "#!" followed by the path to the interpreter. For example [...]#!/bin/sh echo Hello World
- Mar 23, 2010, J D McIninch.
Also, info from an accepted answer for Equivalent of double-clickable .sh and .bat on Mac?:
On mac, there is a specific extension for executing shell
scripts by double clicking them: this is.command
.
Both if (one.length() > 0) {}
and if (!"".equals(one)) {}
will check against an empty foo parameter, and an empty parameter is what you'd get if the the form is submitted with no value in the foo
text field.
If there's any chance you can use the Expression Language to handle the parameter, you could
access it with empty param.foo
in an expression.
<c:if test='${not empty param.foo}'>
This page code gets rendered.
</c:if>
There is no native boolean data type for SQLite. Per the Datatypes doc:
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).
The proper way is mvn package
if you did things correctly for the core part of your build then there should be no need to install your packages in the local repository.
In addition if you use Travis you can "cache" your dependencies because it will not touch your $HOME.m2/repository
if you use package for your own project.
In practicality if you even attempt to do a mvn site
you usually need to do a mvn install
before. There's just too many bugs with either site
or it's numerous poorly maintained plugins.
With an Android-powered device, you can develop and debug your Android applications just as you would on the emulator.
1. Declare your application as "debuggable" in AndroidManifest.xml
.
<application
android:debuggable="true"
... >
...
</application>
2. On your handset, navigate to Settings > Security and check Unknown sources
3. Go to Settings > Developer Options and check USB debugging
Note that if Developer Options
is invisible you will need to navigate to Settings > About Phone and tap on Build number
several times until you are notified that it has been unlocked.
4. Set up your system to detect your device.
Follow the instructions below for your OS:
Install the Google USB Driver from the ADT SDK Manager
(Support for: ADP1, ADP2, Verizon Droid, Nexus One, Nexus S).
For devices not listed above, install an OEM driver for your device
Your device should automatically work; Go to the next step
Add a udev
rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property. For a list of vendor IDs, click here. To set up device detection on Ubuntu Linux:
/etc/udev/rules.d/51-android.rules
.SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"
chmod a+r /etc/udev/rules.d/51-android.rules
Note: The rule syntax may vary slightly depending on your environment. Consult the udev documentation for your system as needed. For an overview of rule syntax, see this guide to writing udev rules.
5. Run the project with your connected device.
With Eclipse/ADT: run or debug your application as usual. You will be presented with a Device Chooser dialog that lists the available emulator(s) and connected device(s).
With ADB: issue commands with the -d flag to target your connected device.
Still need help? Click here for the full guide.
In Ansible >1.4 you can actually specify a remote user at the task level which should allow you to login as that user and execute that command without resorting to sudo. If you can't login as that user then the sudo_user solution will work too.
---
- hosts: webservers
remote_user: root
tasks:
- name: test connection
ping:
remote_user: yourname
See http://docs.ansible.com/playbooks_intro.html#hosts-and-users
public void keyReleased(KeyEvent e)
{
int key=e.getKeyCode();
if(e.getSource()==textField)
{
if(key==KeyEvent.VK_ENTER)
{
Toolkit.getDefaultToolkit().beep();
textField_1.requestFocusInWindow();
}
}
To write logic for 'Enter press' in JTextField
, it is better to keep logic inside the keyReleased()
block instead of keyTyped()
& keyPressed()
.
If you have a SSHClient, you can also use open_sftp()
:
import paramiko
# lets say you have SSH client...
client = paramiko.SSHClient()
sftp = client.open_sftp()
# then you can use upload & download as shown above
...
One classic instance of a bus error is on certain architecures, such as the SPARC (at least some SPARCs, maybe this has been changed), is when you do a mis-aligned access. For instance:
unsigned char data[6];
(unsigned int *) (data + 2) = 0xdeadf00d;
This snippet tries to write the 32-bit integer value 0xdeadf00d
to an address that is (most likely) not properly aligned, and will generate a bus error on architectures that are "picky" in this regard. The Intel x86 is, by the way, not such an architecture, it would allow the access (albeit execute it more slowly).
Both node-schedule and node-cron we can use to implement cron-based schedullers.
NOTE : for generating cron expressions , you can use this cron_maker
First if there is not .env file in your laravel repository. Copy and paste .env.example file and rename it to .env. then open .env file and in database part give your database description. Run: php artisan key:generate php artisan cache:clear php artisan config:cache php artisan config:clear composer dump-autoload php artisan serve
Here we go:
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if(!roleManager.RoleExists("ROLE NAME"))
{
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "ROLE NAME";
roleManager.Create(role);
}
If, like me, you struggled to find an example that uses headers with basic authentication and the rest template exchange API, this is what I finally worked out...
private HttpHeaders createHttpHeaders(String user, String password)
{
String notEncoded = user + ":" + password;
String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic " + encodedAuth);
return headers;
}
private void doYourThing()
{
String theUrl = "http://blah.blah.com:8080/rest/api/blah";
RestTemplate restTemplate = new RestTemplate();
try {
HttpHeaders headers = createHttpHeaders("fred","1234");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
}
catch (Exception eek) {
System.out.println("** Exception: "+ eek.getMessage());
}
}
Try this:
subset(studentdata, Drink=='water')
that should do it.
This is the Linux out of memory manager (OOM). Your process was selected due to 'badness' - a combination of recentness, resident size (memory in use, rather than just allocated) and other factors.
sudo journalctl -xb
You'll see a message like:
Jul 20 11:05:00 someapp kernel: Mem-Info:
Jul 20 11:05:00 someapp kernel: Node 0 DMA per-cpu:
Jul 20 11:05:00 someapp kernel: CPU 0: hi: 0, btch: 1 usd: 0
Jul 20 11:05:00 someapp kernel: Node 0 DMA32 per-cpu:
Jul 20 11:05:00 someapp kernel: CPU 0: hi: 186, btch: 31 usd: 30
Jul 20 11:05:00 someapp kernel: active_anon:206043 inactive_anon:6347 isolated_anon:0
active_file:722 inactive_file:4126 isolated_file:0
unevictable:0 dirty:5 writeback:0 unstable:0
free:12202 slab_reclaimable:3849 slab_unreclaimable:14574
mapped:792 shmem:12802 pagetables:1651 bounce:0
free_cma:0
Jul 20 11:05:00 someapp kernel: Node 0 DMA free:4576kB min:708kB low:884kB high:1060kB active_anon:10012kB inactive_anon:488kB active_file:4kB inactive_file:4kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present
Jul 20 11:05:00 someapp kernel: lowmem_reserve[]: 0 968 968 968
Jul 20 11:05:00 someapp kernel: Node 0 DMA32 free:44232kB min:44344kB low:55428kB high:66516kB active_anon:814160kB inactive_anon:24900kB active_file:2884kB inactive_file:16500kB unevictable:0kB isolated(anon):0kB isolated
Jul 20 11:05:00 someapp kernel: lowmem_reserve[]: 0 0 0 0
Jul 20 11:05:00 someapp kernel: Node 0 DMA: 17*4kB (UEM) 22*8kB (UEM) 15*16kB (UEM) 12*32kB (UEM) 8*64kB (E) 9*128kB (UEM) 2*256kB (UE) 3*512kB (UM) 0*1024kB 0*2048kB 0*4096kB = 4580kB
Jul 20 11:05:00 someapp kernel: Node 0 DMA32: 216*4kB (UE) 601*8kB (UE) 448*16kB (UE) 311*32kB (UEM) 135*64kB (UEM) 74*128kB (UEM) 5*256kB (EM) 0*512kB 0*1024kB 1*2048kB (R) 0*4096kB = 44232kB
Jul 20 11:05:00 someapp kernel: Node 0 hugepages_total=0 hugepages_free=0 hugepages_surp=0 hugepages_size=2048kB
Jul 20 11:05:00 someapp kernel: 17656 total pagecache pages
Jul 20 11:05:00 someapp kernel: 0 pages in swap cache
Jul 20 11:05:00 someapp kernel: Swap cache stats: add 0, delete 0, find 0/0
Jul 20 11:05:00 someapp kernel: Free swap = 0kB
Jul 20 11:05:00 someapp kernel: Total swap = 0kB
Jul 20 11:05:00 someapp kernel: 262141 pages RAM
Jul 20 11:05:00 someapp kernel: 7645 pages reserved
Jul 20 11:05:00 someapp kernel: 264073 pages shared
Jul 20 11:05:00 someapp kernel: 240240 pages non-shared
Jul 20 11:05:00 someapp kernel: [ pid ] uid tgid total_vm rss nr_ptes swapents oom_score_adj name
Jul 20 11:05:00 someapp kernel: [ 241] 0 241 13581 1610 26 0 0 systemd-journal
Jul 20 11:05:00 someapp kernel: [ 246] 0 246 10494 133 22 0 -1000 systemd-udevd
Jul 20 11:05:00 someapp kernel: [ 264] 0 264 29174 121 26 0 -1000 auditd
Jul 20 11:05:00 someapp kernel: [ 342] 0 342 94449 466 67 0 0 NetworkManager
Jul 20 11:05:00 someapp kernel: [ 346] 0 346 137495 3125 88 0 0 tuned
Jul 20 11:05:00 someapp kernel: [ 348] 0 348 79595 726 60 0 0 rsyslogd
Jul 20 11:05:00 someapp kernel: [ 353] 70 353 6986 72 19 0 0 avahi-daemon
Jul 20 11:05:00 someapp kernel: [ 362] 70 362 6986 58 18 0 0 avahi-daemon
Jul 20 11:05:00 someapp kernel: [ 378] 0 378 1621 25 8 0 0 iprinit
Jul 20 11:05:00 someapp kernel: [ 380] 0 380 1621 26 9 0 0 iprupdate
Jul 20 11:05:00 someapp kernel: [ 384] 81 384 6676 142 18 0 -900 dbus-daemon
Jul 20 11:05:00 someapp kernel: [ 385] 0 385 8671 83 21 0 0 systemd-logind
Jul 20 11:05:00 someapp kernel: [ 386] 0 386 31573 153 15 0 0 crond
Jul 20 11:05:00 someapp kernel: [ 391] 999 391 128531 2440 48 0 0 polkitd
Jul 20 11:05:00 someapp kernel: [ 400] 0 400 9781 23 8 0 0 iprdump
Jul 20 11:05:00 someapp kernel: [ 419] 0 419 27501 32 10 0 0 agetty
Jul 20 11:05:00 someapp kernel: [ 855] 0 855 22883 258 43 0 0 master
Jul 20 11:05:00 someapp kernel: [ 862] 89 862 22926 254 44 0 0 qmgr
Jul 20 11:05:00 someapp kernel: [23631] 0 23631 20698 211 43 0 -1000 sshd
Jul 20 11:05:00 someapp kernel: [12884] 0 12884 81885 3754 80 0 0 firewalld
Jul 20 11:05:00 someapp kernel: [18130] 0 18130 33359 291 65 0 0 sshd
Jul 20 11:05:00 someapp kernel: [18132] 1000 18132 33791 748 64 0 0 sshd
Jul 20 11:05:00 someapp kernel: [18133] 1000 18133 28867 122 13 0 0 bash
Jul 20 11:05:00 someapp kernel: [18428] 99 18428 208627 42909 151 0 0 node
Jul 20 11:05:00 someapp kernel: [18486] 89 18486 22909 250 46 0 0 pickup
Jul 20 11:05:00 someapp kernel: [18515] 1000 18515 352905 141851 470 0 0 npm
Jul 20 11:05:00 someapp kernel: [18520] 0 18520 33359 291 66 0 0 sshd
Jul 20 11:05:00 someapp kernel: [18522] 1000 18522 33359 294 64 0 0 sshd
Jul 20 11:05:00 someapp kernel: [18523] 1000 18523 28866 115 12 0 0 bash
Jul 20 11:05:00 someapp kernel: Out of memory: Kill process 18515 (npm) score 559 or sacrifice child
Jul 20 11:05:00 someapp kernel: Killed process 18515 (npm) total-vm:1411620kB, anon-rss:567404kB, file-rss:0kB
You should declare toString()
and valueOf()
method in enum
.
import java.io.Serializable;
public enum Gesture implements Serializable {
ROCK,PAPER,SCISSORS;
public String toString(){
switch(this){
case ROCK :
return "Rock";
case PAPER :
return "Paper";
case SCISSORS :
return "Scissors";
}
return null;
}
public static Gesture valueOf(Class<Gesture> enumType, String value){
if(value.equalsIgnoreCase(ROCK.toString()))
return Gesture.ROCK;
else if(value.equalsIgnoreCase(PAPER.toString()))
return Gesture.PAPER;
else if(value.equalsIgnoreCase(SCISSORS.toString()))
return Gesture.SCISSORS;
else
return null;
}
}
It looks like you indented so_far = new
too much. Try this:
if guess in word:
print("\nYes!", guess, "is in the word!")
# Create a new variable (so_far) to contain the guess
new = ""
i = 0
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new # unindented this
I would do it like this:
variable = "string"
message = ""
for b in variable:
message = b+message
print (message)
and it prints: gnirts
Check out for the static before the main method, this declares the method as a class method, which means it needs no instance to be called. So as you are going to call a non static method, Java complains because you are trying to call a so called "instance method", which, of course needs an instance first ;)
If you want a better understanding about classes and instances, create a new class with instance and class methods, create a object in your main loop and call the methods!
class Foo{
public static void main(String[] args){
Bar myInstance = new Bar();
myInstance.do(); // works!
Bar.do(); // doesn't work!
Bar.doSomethingStatic(); // works!
}
}
class Bar{
public do() {
// do something
}
public static doSomethingStatic(){
}
}
Also remember, classes in Java should start with an uppercase letter.
You could use DATE_ADD : (or ADDDATE with INTERVAL
)
UPDATE table SET date = DATE_ADD(date, INTERVAL 1 YEAR)
Just use /\s+/ against '' as a splitter. In this case all "extra" blanks were removed. Usually this particular behaviour is required. So, in you case it will be:
my $line = "file1.gz file1.gz file3.gz";
my @abc = split(/\s+/, $line);
You can define a Range, the size of your array and use it's value property:
Sub PrintArray(Data, SheetName As String, intStartRow As Integer, intStartCol As Integer)
Dim oWorksheet As Worksheet
Dim rngCopyTo As Range
Set oWorksheet = ActiveWorkbook.Worksheets(SheetName)
' size of array
Dim intEndRow As Integer
Dim intEndCol As Integer
intEndRow = UBound(Data, 1)
intEndCol = UBound(Data, 2)
Set rngCopyTo = oWorksheet.Range(oWorksheet.Cells(intStartRow, intStartCol), oWorksheet.Cells(intEndRow, intEndCol))
rngCopyTo.Value = Data
End Sub
I tried to install to VS 2015 using the Web installer. It seemed to work, but there was still no MySQL entry for Data Connections. I ended up going to http://dev.mysql.com/downloads/windows/visualstudio/, using it to uninstall then re-install the connector. Not it works as expected.
The following transact SQL script works for all languages (international). The solution is not to check for alphanumeric but to check for not containing special characters.
DECLARE @teststring nvarchar(max)
SET @teststring = 'Test''Me'
SELECT 'IS ALPHANUMERIC: ' + @teststring
WHERE @teststring NOT LIKE '%[-!#%&+,./:;<=>@`{|}~"()*\\\_\^\?\[\]\'']%' {ESCAPE '\'}
Well this really depends on the compiler environment. gcc does not catch these. Visual Studio and the last Borland that I used did.
So the conclusion about crashes is that it depends on the quality of your development environment.
The C++ specification says that catch(...) must catch any exceptions, but it doesn't in all cases.
At least from what I tried.
If you do Code-First and already have a Database:
public override void Up()
{
AlterColumn("dbo.MyTable","Id", c => c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()"));
}
You need to use document.getElementById()
in line 3.
If you try this right now in the console:
var img = document.createElement("img");_x000D_
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";_x000D_
var src = document.getElementById("header");_x000D_
src.appendChild(img);
_x000D_
<div id="header"></div>
_x000D_
... you'd get this:
For me that function worked:
private static JSONObject concatJSONS(JSONObject json, JSONObject obj) {
JSONObject result = new JSONObject();
for(Object key: json.keySet()) {
System.out.println("adding " + key + " to result json");
result.put(key, json.get(key));
}
for(Object key: obj.keySet()) {
System.out.println("adding " + key + " to result json");
result.put(key, obj.get(key));
}
return result;
}
(notice) - this implementation of concataion of json is for import org.json.simple.JSONObject;
Parameters are key-value pairs that can appear inside URL path, and start with a semicolon character (;
).
Query string appears after the path (if any) and starts with a question mark character (?
).
Both parameters and query string contain key-value pairs.
In a GET
request, parameters appear in the URL itself:
<scheme>://<username>:<password>@<host>:<port>/<path>;<parameters>?<query>#<fragment>
In a POST
request, parameters can appear in the URL itself, but also in the datastream (as known as content).
Query string is always a part of the URL.
Parameters can be buried in form-data
datastream when using POST method so they may not appear in the URL. Yes a POST
request can define parameters as form data and in the URL, and this is not inconsistent because parameters can have several values.
I've found no explaination for this behavior so far. I guess it might be useful sometimes to "unhide" parameters from a POST
request, or even let the code handling a GET
request share some parts with the code handling a POST
. Of course this can work only with server code supporting parameters in a URL.
Until you get better insights, I suggest you to use parameters only in form-data
datastream of POST
requests.
Sources:
that syntax is now deprecated, you will get this error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 14: Expected a stage @ line 14, column 9.
parallel firstTask: {
^
WorkflowScript: 14: Stage does not have a name @ line 14, column 9.
parallel secondTask: {
^
2 errors
You should do something like:
stage("Parallel") {
steps {
parallel (
"firstTask" : {
//do some stuff
},
"secondTask" : {
// Do some other stuff in parallel
}
)
}
}
Just to add the use of node here, to distribute jobs across multiple build servers/ VMs:
pipeline {
stages {
stage("Work 1"){
steps{
parallel ( "Build common Library":
{
node('<Label>'){
/// your stuff
}
},
"Build Utilities" : {
node('<Label>'){
/// your stuff
}
}
)
}
}
All VMs should be labelled as to use as a pool.
Have you entered the virtual environment for django? Run python -m venv myvenv
if you have not yet installed.
There is a bug in the new version of NOX app. Software keyboard doesn't work after switching to it in settings. To fix this, I installed Gboard using the Play Market.
If you are not worrying about opening a console on-command, you can go into the properties for your project and change it to Console Application
This will still show your form as well as popping up a console window. You can't close the console window, but it works as an excellent temporary logger for debugging.
Just remember to turn it back off before you deploy the program.
In intellij8 I was using a specific plugin "Jar Tool" that is configurable and allows to pack a JAR archive.
Look at
For Each c as DataColumn in dt.Columns
'... = c.ColumnName
Next
or:
dt.GetDataTableSchema(...)
If you set the cell formatting to Text prior to adding a numeric value with a leading zero, the leading zero is retained without having to skew results by adding an apostrophe. If you try and manually add a leading zero value to a default sheet in Excel and then convert it to text, the leading zero is removed. If you convert the cell to Text first, then add your value, it is fine. Same principle applies when doing it programatically.
// Pull in all the cells of the worksheet
Range cells = xlWorkBook.Worksheets[1].Cells;
// set each cell's format to Text
cells.NumberFormat = "@";
// reset horizontal alignment to the right
cells.HorizontalAlignment = XlHAlign.xlHAlignRight;
// now add values to the worksheet
for (i = 0; i <= dataGridView1.RowCount - 1; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
DataGridViewCell cell = dataGridView1[j, i];
xlWorkSheet.Cells[i + 1, j + 1] = cell.Value.ToString();
}
}
This Should Work:
import glob
extensions = ('*.txt', '*.mdown', '*.markdown')
for i in extensions:
for files in glob.glob(i):
print (files)
Use curl
instead of file_get_contents
:
$address = "India+Panchkula";
$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=India";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response);
echo $lat = $response_a->results[0]->geometry->location->lat;
echo "<br />";
echo $long = $response_a->results[0]->geometry->location->lng;
Object.prototype.toString.call(myVar)
will return:
"[object Object]"
if myVar is an object"[object Array]"
if myVar is an arrayFor more information on this and why it is a good alternative to typeof, check out this article.
You can use a for loop:
for file in * ; do echo "$file" done
Note that if the command in question accepts multiple arguments, then using xargs is almost always more efficient as it only has to spawn the utility in question once instead of multiple times.
You can use either = or "space". For instance following two commands return the same
git log --author="Developer1"
git log --author "Developer1"
/([0-9]+[.,]*)+/
matches any number with or without coma or dots
it can match
122
122,354
122.88
112,262,123.7678
bug: it also matches 262.4377,3883 ( but it doesn't matter parctically)
You can set the special character, which is looked for upon execution of a script, to another value by means of using the SET DEFINE <1_CHARACTER>
By default, the DEFINE function itself is on, and it is set to &
It can be turned off - as mentioned already - but it can be avoided as well by means of setting it to a different value. Be very aware of what sign you set it to. In the below example, I've chose the # character, but that choice is just an example.
SQL> select '&var_ampersand #var_hash' from dual;
Enter value for var_ampersand: a value
'AVALUE#VAR_HASH'
-----------------
a value #var_hash
SQL> set define #
SQL> r
1* select '&var_ampersand #var_hash' from dual
Enter value for var_hash: another value
'&VAR_AMPERSANDANOTHERVALUE'
----------------------------
&var_ampersand another value
SQL>
Files in your project are available to you relative to your src folder. if you know which package or folder myfile.txt will be in, say it is in
----src
--------package1
------------myfile.txt
------------Prog.java
you can specify its path as "src/package1/myfile.txt" from Prog.java
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
int i;
cout << "Please enter an integer value: ";
// cin >> i; leaves '\n' among possible other junk in the buffer.
// '\n' also happens to be the default delim character for getline() below.
cin >> i;
if (cin.fail())
{
cout << "\ncin failed - substituting: i=1;\n\n";
i = 1;
}
cin.clear(); cin.ignore(INT_MAX,'\n');
cout << "The value you entered is: " << i << " and its double is " << i*2 << ".\n\n";
string myString;
cout << "What's your full name? (spaces inclded) \n";
getline (cin, myString);
cout << "\nHello '" << myString << "'.\n\n\n";
for first key of object you can use
console.log(Object.keys(object)[0]);//print key's name
for value
console.log(object[Object.keys(object)[0]]);//print key's value
As so many good answers said, an object must implement the Iterable interface
if it wants to use a for-each
loop.
I'll post a simple example and try to explain in a different way how a for-each
loop works.
The for-each
loop example:
public class ForEachTest {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("111");
list.add("222");
for (String str : list) {
System.out.println(str);
}
}
}
Then, if we use javap
to decompile this class, we will get this bytecode sample:
public static void main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=4, args_size=1
0: new #16 // class java/util/ArrayList
3: dup
4: invokespecial #18 // Method java/util/ArrayList."<init>":()V
7: astore_1
8: aload_1
9: ldc #19 // String 111
11: invokeinterface #21, 2 // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
16: pop
17: aload_1
18: ldc #27 // String 222
20: invokeinterface #21, 2 // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
25: pop
26: aload_1
27: invokeinterface #29, 1 // InterfaceMethod java/util/List.iterator:()Ljava/util/Iterator;
As we can see from the last line of the sample, the compiler will automatically convert the use of for-each
keyword to the use of an Iterator
at compile time. That may explain why object, which doesn't implement the Iterable interface
, will throw an Exception
when it tries to use the for-each
loop.
put function
etname=(EditText)findViewById(R.id.Name);
tvname=(TextView)findViewById(R.id.tvName);
b1= (ImageButton) findViewById(R.id.Submit);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String s=etname.getText().toString();
Intent ii=new Intent(getApplicationContext(), MainActivity2.class);
ii.putExtra("name", s);
Toast.makeText(getApplicationContext(),"Page 222", Toast.LENGTH_LONG).show();
startActivity(ii);
}
});
getfunction
public class MainActivity2 extends Activity {
TextView tvname;
EditText etname;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
tvname = (TextView)findViewById(R.id.tvName);
etname=(EditText)findViewById(R.id.Name);
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
String j2 =(String) b.get("name");
etname.setText(j2);
Toast.makeText(getApplicationContext(),"ok",Toast.LENGTH_LONG).show();
}
}
The accepted answer didn't work for me in Android 2.2. I don't know why, but it was "eating" some of my zeros (0) . Apache commons also didn't work on Android 2.2, because it uses methods that are supported only starting from Android 2.3.x. Also, if you want to just MD5 a string, Apache commons is too complex for that. Why one should keep a whole library to use just a small function from it...
Finally I found the following code snippet here which worked perfectly for me. I hope it will be useful for someone...
public String MD5(String md5) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes("UTF-8"));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
} catch(UnsupportedEncodingException ex){
}
return null;
}
Rename the solution's corresponding .SUO file. The SUO file contains the TFS status (online/offline), amongst a host of other goodies.
Do this only if the "right-click on the solution name right at the top of the Solution Explorer and select the Go Online option" fails (because e.g. you installed VS2015 preview).
There is the way of current thread getting:
Thread t = Thread.currentThread();
After you have got Thread class object (t) you are able to get information you need using Thread class methods.
Thread ID gettting:
long tId = t.getId(); // e.g. 14291
Thread name gettting:
String tName = t.getName(); // e.g. "pool-29-thread-7"
take a look at shutil
. shutil.copyfile(src, dst)
will copy a file to another file.
Note that shutil.copyfile
will not create directories that do not already exist. for that, use os.makedirs
As you can see in the below source code, BeanUtils.copyProperties internally uses reflection and there's additional internal cache lookup steps as well which is going to add cost wrt performance
private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
@Nullable String... ignoreProperties) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
if (editable != null) {
if (!editable.isInstance(target)) {
throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
"] not assignable to Editable class [" + editable.getName() + "]");
}
actualEditable = editable;
}
**PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);**
List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
for (PropertyDescriptor targetPd : targetPds) {
Method writeMethod = targetPd.getWriteMethod();
if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null) {
Method readMethod = sourcePd.getReadMethod();
if (readMethod != null &&
ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
try {
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
}
catch (Throwable ex) {
throw new FatalBeanException(
"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
}
}
}
}
}
}
So it's better to use plain setters given the cost reflection
I think you are looking for std::any_of
, which will return a true/false answer to detect if an element is in a container (array, vector, deque, etc.)
int val = SOME_VALUE; // this is the value you are searching for
bool exists = std::any_of(std::begin(myArray), std::end(myArray), [&](int i)
{
return i == val;
});
If you want to know where the element is, std::find
will return an iterator to the first element matching whatever criteria you provide (or a predicate you give it).
int val = SOME_VALUE;
int* pVal = std::find(std::begin(myArray), std::end(myArray), val);
if (pVal == std::end(myArray))
{
// not found
}
else
{
// found
}
Another simple way would be add some log statement to the bar.someMethod() and then ascertain you can see the said message when your test executed, see examples here: How to do a JUnit assert on a message in a logger
That is especially handy when your Bar.someMethod() is private
.
Actually, you can make cross domain requests with i.e. Firefox, se this for a overview: http://ajaxian.com/archives/cross-site-xmlhttprequest-in-firefox-3
Webkit and IE8 supports it as well in some fashion.
I just wanted to add these from TLDP:
~:$ echo $SHELL
/bin/bash
~:$ echo ${#SHELL}
9
~:$ ARRAY=(one two three)
~:$ echo ${#ARRAY}
3
~:$ echo ${TEST:-test}
test
~:$ echo $TEST
~:$ export TEST=a_string
~:$ echo ${TEST:-test}
a_string
~:$ echo ${TEST2:-$TEST}
a_string
~:$ echo $TEST2
~:$ echo ${TEST2:=$TEST}
a_string
~:$ echo $TEST2
a_string
~:$ export STRING="thisisaverylongname"
~:$ echo ${STRING:4}
isaverylongname
~:$ echo ${STRING:6:5}
avery
~:$ echo ${ARRAY[*]}
one two one three one four
~:$ echo ${ARRAY[*]#one}
two three four
~:$ echo ${ARRAY[*]#t}
one wo one hree one four
~:$ echo ${ARRAY[*]#t*}
one wo one hree one four
~:$ echo ${ARRAY[*]##t*}
one one one four
~:$ echo $STRING
thisisaverylongname
~:$ echo ${STRING%name}
thisisaverylong
~:$ echo ${STRING/name/string}
thisisaverylongstring
I will try to get the answer with one query using CTE and window function rank()
create the tables
create table Students
(student_id int,
Name varchar(255),
details varchar(255));
create table Subject(
Sub_id int,
name varchar(255));
create table marks
(student_id int,
subject_id int,
mark int);
the answer should be a table with the below fields
student_name | subject_name | mark
plan the execution steps
with CTE as (select s.name, sb.name as subject_name, m.mark, rank() over(partition by sb.name order by m.mark desc) as rn
from Students s
join marks m on s.student_id = m.student_id
join subject sb
on sb.Sub_id = m.subject_id)
select name , subject_name, mark
from CTE
where rn = 1
Field[] field = model.getClass().getDeclaredFields();
for(int j=0 ; j<field.length ; j++){
String name = field[j].getName();
name = name.substring(0,1).toUpperCase()+name.substring(1);
String type = field[j].getGenericType().toString();
if(type.equals("class java.lang.String")){
Method m = model.getClass().getMethod("get"+name);
String value = (String) m.invoke(model);
if(value == null){
... something to do...
}
}
I guess it's just because the onblur event is called as a result of the input losing focus, there isn't a blur action associated with an input, like there is a click action associated with a button
I'd suggest reading the W3 wiki page about structuring HTML5:
<header>
Used to contain the header content of a site.<footer>
Contains the footer content of a site.<nav>
Contains the navigation menu, or other navigation functionality for the page.
<article>
Contains a standalone piece of content that would make
sense if syndicated as an RSS item, for example a news item.
<section>
Used to either group different articles into different
purposes or subjects, or to define the different sections of a single article.
<aside>
Defines a block of content that is related to the main content around it, but not central to the flow of it.
They include an image that I've cleaned up here:
In code, this looks like so:
<body> <header></header> <nav></nav> <section id="sidebar"></section> <section id="content"></section> <aside></aside> <footer></footer> </body>
Let's explore some of the HTML5 elements in more detail.
<section>
The
<section>
element is for containing distinct different areas of functionality or subjects area, or breaking an article or story up into different sections. So in this case: "sidebar1" contains various useful links that will persist on every page of the site, such as "subscribe to RSS" and "Buy music from store". "main" contains the main content of this page, which is blog posts. On other pages of the site, this content will change. It is a fairly generic element, but still has way more semantic meaning than the plain old<div>
.
<article>
<article>
is related to<section>
, but is distinctly different. Whereas<section>
is for grouping distinct sections of content or functionality,<article>
is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way - if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then<article>
is suitable for marking them up. In our example,<section id="main">
contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore<article>
is perfect for them:<section id="main"> <article><!-- first blog post --></article> <article><!-- second blog post --></article> <article><!-- third blog post --></article> </section>
Simple huh? Be aware though that you can also nest sections inside articles, where it makes sense to do so. For example, if each one of these blog posts has a consistent structure of distinct sections, then you could put sections inside your articles as well. It could look something like this:
<article> <section id="introduction"></section> <section id="content"></section> <section id="summary"></section> </article>
<header>
and<footer>
as we already mentioned above, the purpose of the
<header>
and<footer>
elements is to wrap header and footer content, respectively. In our particular example the<header>
element contains a logo image, and the<footer>
element contains a copyright notice, but you could add more elaborate content if you wished. Also note that you can have more than one header and footer on each page - as well as the top level header and footer we have just discussed, you could also have a<header>
and<footer>
element nested inside each<article>
, in which case they would just apply to that particular article. Adding to our above example:<article> <header></header> <section id="introduction"></section> <section id="content"></section> <section id="summary"></section> <footer></footer> </article>
<nav>
The
<nav>
element is for marking up the navigation links or other constructs (eg a search form) that will take you to different pages of the current site, or different areas of the current page. Other links, such as sponsored links, do not count. You can of course include headings and other structuring elements inside the<nav>
, but it's not compulsory.
<aside>
you may have noticed that we used an
<aside>
element to markup the 2nd sidebar: the one containing latest gigs and contact details. This is perfectly appropriate, as<aside>
is for marking up pieces of information that are related to the main flow, but don't fit in to it directly. And the main content in this case is all about the band! Other good choices for an<aside>
would be information about the author of the blog post(s), a band biography, or a band discography with links to buy their albums.Where does that leave
<div>
?So, with all these great new elements to use on our pages, the days of the humble
<div>
are numbered, surely? NO. In fact, the<div>
still has a perfectly valid use. You should use it when there is no other more suitable element available for grouping an area of content, which will often be when you are purely using an element to group content together for styling/visual purposes. A common example is using a<div>
to wrap all of the content on the page, and then using CSS to centre all the content in the browser window, or apply a specific background image to the whole content.
Use sorted()
with a key
as follows -
>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
The lambda
returns the fourth element of each of the inner lists and the sorted
function uses that to sort those list. This assumes that int(elem)
will not fail for the list.
Or use itemgetter
(As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)
>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
Your class JSON_result
does not match your JSON string. Note how the object JSON_result
is going to represent is wrapped in another property named "Venue"
.
So either create a class for that, e.g.:
Public Class Container
Public Venue As JSON_result
End Class
Public Class JSON_result
Public ID As Integer
Public Name As String
Public NameWithTown As String
Public NameWithDestination As String
Public ListingType As String
End Class
Dim obj = JsonConvert.DeserializeObject(Of Container)(...your_json...)
or change your JSON string to
{
"ID": 3145,
"Name": "Big Venue, Clapton",
"NameWithTown": "Big Venue, Clapton, London",
"NameWithDestination": "Big Venue, Clapton, London",
"ListingType": "A",
"Address": {
"Address1": "Clapton Raod",
"Address2": "",
"Town": "Clapton",
"County": "Greater London",
"Postcode": "PO1 1ST",
"Country": "United Kingdom",
"Region": "Europe"
},
"ResponseStatus": {
"ErrorCode": "200",
"Message": "OK"
}
}
or use e.g. a ContractResolver
to parse the JSON string.
make sure your controller extends Symfony\Bundle\FrameworkBundle\Controller\Controller;
you should also check app/console debug:router
in terminal to see what name symfony has named the route
in my case it used a minus instead of an underscore
i.e blog-show
$uri = $this->generateUrl('blog-show', ['slug' => 'my-blog-post']);
SELECT DATENAME(MONTH, GETDATE())
+ RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9) AS [Month DD, YYYY]
OR Date without Comma Between date and year, you can use the following
SELECT DATENAME(MONTH, GETDATE()) + ' ' + CAST(DAY(GETDATE()) AS VARCHAR(2))
+ ' ' + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [Month DD YYYY]
if you want sin
then
__asm__ __volatile__("fsin" : "=t"(vsin) : "0"(xrads));
if you want cos
then
__asm__ __volatile__("fcos" : "=t"(vcos) : "0"(xrads));
if you want sqrt
then
__asm__ __volatile__("fsqrt" : "=t"(vsqrt) : "0"(value));
so why use inaccurate code when the machine instructions will do?
Have a table row with nested table:
<tr class='dummyRow' style='display: none;'>
<td>
<table style='display: none;'>All row content inside here</table>
</td>
</tr>
$('.dummyRow').show().find("table").slideDown();
Note: the row and it's content (here it is "table"
) both should be hidden before animation starts.
$('.dummyRow').find("table").slideUp('normal', function(){$('.dummyRow').hide();});
The second parameter (function()
) is a callback.
Simple!!
Note that there are also several options that can be added as parameters of the slide up/down functions (the most common being durations of 'slow'
and 'fast'
).
Sample code you can use to let Tika take care of container files for you. http://wiki.apache.org/tika/RecursiveMetadata
Form what I can tell, the accepted solution will not work for cases where there are nested zip files. Tika, however will take care of such situations as well.
Both are used to count elements in a array. sizeof() function is an alias of count() function used in PHP. However, count() function is faster and butter than sizeof().
I had a similar problem. I searched conda.exe
and I found it on Scripts folder. So, In Anaconda3 you need to add two variables to PATH
. The first is Anaconda_folder_path
and the second is Anaconda_folder_path\Scripts
it is better to include it in a <small>
tag
The HTML <small>
tag is used for specifying small print.
Small print (also referred to as "fine print" or "mouseprint") usually refers to the part of a document that contains disclaimers, caveats, or legal restrictions, such as copyrights. And this tag is supported in all major browsers.
<footer>
<small>© Copyright 2058, Example Corporation</small>
</footer>