Unlike other answers I'd additionally also add focus()
along with scrollIntoView()
.
Also I'm using setTimeout
since it jumps to top otherwise when changing the URL. Not sure what was the reason for that but it seems setTimeout
does the workaround.
Origin:
<a [routerLink] fragment="some-id" (click)="scrollIntoView('some-id')">Jump</a>
Destination:
<a id="some-id" tabindex="-1"></a>
Typescript:
scrollIntoView(anchorHash) {
setTimeout(() => {
const anchor = document.getElementById(anchorHash);
if (anchor) {
anchor.focus();
anchor.scrollIntoView();
}
});
}
None of the solution above works for me, but I just tried this, and it worked,
<a href="#/#faq-1">Question 1</a>
So I realized I need to notify the page to start with the index page and then use the traditional anchor.
To get more than 20 you can use a load more button.
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Instagram more button example</title>
<!--
Instagram PHP API class @ Github
https://github.com/cosenary/Instagram-PHP-API
-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
ul {
width: 950px;
}
ul > li {
float: left;
list-style: none;
padding: 4px;
}
#more {
bottom: 8px;
margin-left: 80px;
position: fixed;
font-size: 13px;
font-weight: 700;
line-height: 20px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#more').click(function() {
var tag = $(this).data('tag'),
maxid = $(this).data('maxid');
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {
tag: tag,
max_id: maxid
},
dataType: 'json',
cache: false,
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
$('ul#photos').append('<li><img src="' + src + '"></li>');
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
});
});
});
</script>
</head>
<body>
<?php
/**
* Instagram PHP API
*/
require_once 'instagram.class.php';
// Initialize class with client_id
// Register at http://instagram.com/developer/ and replace client_id with your own
$instagram = new Instagram('ENTER CLIENT ID HERE');
// Get latest photos according to geolocation for Växjö
// $geo = $instagram->searchMedia(56.8770413, 14.8092744);
$tag = 'sweden';
// Get recently tagged media
$media = $instagram->getTagMedia($tag);
// Display first results in a <ul>
echo '<ul id="photos">';
foreach ($media->data as $data)
{
echo '<li><img src="'.$data->images->thumbnail->url.'"></li>';
}
echo '</ul>';
// Show 'load more' button
echo '<br><button id="more" data-maxid="'.$media->pagination->next_max_id.'" data-tag="'.$tag.'">Load more ...</button>';
?>
</body>
</html>
ajax.php
<?php
/**
* Instagram PHP API
*/
require_once 'instagram.class.php';
// Initialize class for public requests
$instagram = new Instagram('ENTER CLIENT ID HERE');
// Receive AJAX request and create call object
$tag = $_GET['tag'];
$maxID = $_GET['max_id'];
$clientID = $instagram->getApiKey();
$call = new stdClass;
$call->pagination->next_max_id = $maxID;
$call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";
// Receive new data
$media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));
// Collect everything for json output
$images = array();
foreach ($media->data as $data) {
$images[] = $data->images->thumbnail->url;
}
echo json_encode(array(
'next_id' => $media->pagination->next_max_id,
'images' => $images
));
?>
instagram.class.php
Find the function getTagMedia() and replace with:
public function getTagMedia($name, $auth=false, $params=null) {
return $this->_makeCall('tags/' . $name . '/media/recent', $auth, $params);
}
I suggest you put this code into a method and create a unit test.
public static boolean isLeapYear(int year) {
assert year >= 1583; // not valid before this date.
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
In the unit test
assertTrue(isLeapYear(2000));
assertTrue(isLeapYear(1904));
assertFalse(isLeapYear(1900));
assertFalse(isLeapYear(1901));
If you want to use \newcommand
, you can also include \usepackage{xspace}
and define command by \newcommand{\newCommandName}{text to insert\xspace}
.
This can allow you to just use \newCommandName
rather than \newCommandName{}
.
For more detail, http://www.math.tamu.edu/~harold.boas/courses/math696/why-macros.html
Sounds like you're looking for rbind
:
> a<-matrix(nrow=10,ncol=5)
> b<-matrix(nrow=20,ncol=5)
> dim(rbind(a,b))
[1] 30 5
Similarly, cbind
stacks the matrices horizontally.
I am not entirely sure what you mean by the last question ("Can I do this for matrices of different rows and columns.?")
I don't like the auto-commit that git revert
does, so this might be helpful for some.
If you just want the modified files not the auto-commit, you can use --no-commit
% git revert --no-commit <commit hash>
which is the same as the -n
% git revert -n <commit hash>
Not sure if this is the cause of the problem, but I got this issue only after installing JVM Monitor.
Uninstalling JVM Monitor solved the issue for me.
This Code work for me..
//Get Time and Date
private String getTimeMethod(String formate)
{
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(formate);
String formattedDate= dateFormat.format(date);
return formattedDate;
}
//this method is used to refresh Time every Second
private void refreshTime() //Call this method to refresh time
{
new Timer().schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
txtV_Time.setText(getTimeMethod("hh:mm:ss a")); //hours,Min and Second with am/pm
txtV_Date.setText(getTimeMethod("dd-MMM-yy")); //You have to pass your DateFormate in getTimeMethod()
};
});
}
}, 0, 1000);//1000 is a Refreshing Time (1second)
}
you can use Intent for this:
Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("your Url"));
startActivity(browserIntent);
Short Answer:
Optional.isPresent()
valueOptional.isPresent() == false
In real code, you might want to consider the second approach when the required resource is expensive to get.
// Always get heavy resource
getResource(resourceId).orElse(getHeavyResource());
// Get heavy resource when required.
getResource(resourceId).orElseGet(() -> getHeavyResource())
For more details, consider the following example with this function:
public Optional<String> findMyPhone(int phoneId)
The difference is as below:
X : buyNewExpensivePhone() called
+——————————————————————————————————————————————————————————————————+——————————————+
| Optional.isPresent() | true | false |
+——————————————————————————————————————————————————————————————————+——————————————+
| findMyPhone(int phoneId).orElse(buyNewExpensivePhone()) | X | X |
+——————————————————————————————————————————————————————————————————+——————————————+
| findMyPhone(int phoneId).orElseGet(() -> buyNewExpensivePhone()) | | X |
+——————————————————————————————————————————————————————————————————+——————————————+
When optional.isPresent() == false
, there is no difference between two ways. However, when optional.isPresent() == true
, orElse()
always calls the subsequent function whether you want it or not.
Finally, the test case used is as below:
Result:
------------- Scenario 1 - orElse() --------------------
1.1. Optional.isPresent() == true (Redundant call)
Going to a very far store to buy a new expensive phone
Used phone: MyCheapPhone
1.2. Optional.isPresent() == false
Going to a very far store to buy a new expensive phone
Used phone: NewExpensivePhone
------------- Scenario 2 - orElseGet() --------------------
2.1. Optional.isPresent() == true
Used phone: MyCheapPhone
2.2. Optional.isPresent() == false
Going to a very far store to buy a new expensive phone
Used phone: NewExpensivePhone
Code:
public class TestOptional {
public Optional<String> findMyPhone(int phoneId) {
return phoneId == 10
? Optional.of("MyCheapPhone")
: Optional.empty();
}
public String buyNewExpensivePhone() {
System.out.println("\tGoing to a very far store to buy a new expensive phone");
return "NewExpensivePhone";
}
public static void main(String[] args) {
TestOptional test = new TestOptional();
String phone;
System.out.println("------------- Scenario 1 - orElse() --------------------");
System.out.println(" 1.1. Optional.isPresent() == true (Redundant call)");
phone = test.findMyPhone(10).orElse(test.buyNewExpensivePhone());
System.out.println("\tUsed phone: " + phone + "\n");
System.out.println(" 1.2. Optional.isPresent() == false");
phone = test.findMyPhone(-1).orElse(test.buyNewExpensivePhone());
System.out.println("\tUsed phone: " + phone + "\n");
System.out.println("------------- Scenario 2 - orElseGet() --------------------");
System.out.println(" 2.1. Optional.isPresent() == true");
// Can be written as test::buyNewExpensivePhone
phone = test.findMyPhone(10).orElseGet(() -> test.buyNewExpensivePhone());
System.out.println("\tUsed phone: " + phone + "\n");
System.out.println(" 2.2. Optional.isPresent() == false");
phone = test.findMyPhone(-1).orElseGet(() -> test.buyNewExpensivePhone());
System.out.println("\tUsed phone: " + phone + "\n");
}
}
print_r()
is mostly for debugging. If you want to print it in that format, loop through the array, and print the elements out.
foreach($data as $d){
foreach($d as $v){
echo $v."\n";
}
}
I would suggest Travis for Open source project. It's just simple to configure and use.
Simple steps to setup:
.travis.yml
file in root of your project. Add Travis as service in your repository settings page.Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.
As others have said, you can't do that either using alert()
or confirm()
.
You can, however, create an external HTML document containing your error message and an OK
button, set its <title>
element to whatever you want, then display it in a modal dialog box using showModalDialog().
There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0
tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.
The closest link I could find to be useful for more information is this
Quote from above link:
What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.
From the Documentation for GetEXitCodeThread
Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.
My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.
To create your custom log file, try this code
Mage::log('your debug message', null, 'yourlog_filename.log');
Refer this Answer
Found my solution on Apache/2.2.15 (Unix).
And Thanks for answer from @QuantumHive:
First: I finded all
Order allow,deny
Deny from all
instead of
Order allow,deny
Allow from all
and then:
I setted
#
# Control access to UserDir directories. The following is an example
# for a site where these directories are restricted to read-only.
#
#<Directory /var/www/html>
# AllowOverride FileInfo AuthConfig Limit
# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
# <Limit GET POST OPTIONS>
# Order allow,deny
# Allow from all
# </Limit>
# <LimitExcept GET POST OPTIONS>
# Order deny,allow
# Deny from all
# </LimitExcept>
#</Directory>
Remove the previous "#" annotation to
#
# Control access to UserDir directories. The following is an example
# for a site where these directories are restricted to read-only.
#
<Directory /var/www/html>
AllowOverride FileInfo AuthConfig Limit
Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
<Limit GET POST OPTIONS>
Order allow,deny
Allow from all
</Limit>
<LimitExcept GET POST OPTIONS>
Order deny,allow
Deny from all
</LimitExcept>
</Directory>
ps. my WebDir is: /var/www/html
Yes and you don't need to learn Objective-C and buying Apple software and hardware.
Adobe have created compilator from ActionScript 3 to program for iOS. And later Apple approved this method of application creation.
This is best way to create Apple applications under Windows or Linux/BSD (and another one for MacOS-X)
Wireshark (or Tshark) is probably the defacto standard traffic inspection tool. It is unobtrusive and works without fiddling with port redirecting and proxying. It is very generic, though, as does not (AFAIK) provide any tooling specifically to monitor web service traffic - it's all tcp/ip and http.
You have probably already looked at tcpmon but I don't know of any other tool that does the sit-in-between thing.
For Jackson 2+ (com.fasterxml.jackson
), the methods are little bit different:
Iterator<Entry<String, JsonNode>> nodes = rootNode.get("foo").fields();
while (nodes.hasNext()) {
Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodes.next();
logger.info("key --> " + entry.getKey() + " value-->" + entry.getValue());
}
The rest of answers are pretty good, but just wanted to add some extra information in case someone comes here looking for a solution to replace/update a multiline echo.
So I would like to share an example with you all. The following script was tried on a CentOS system and uses "timedatectl" command which basically prints some detailed time information of your system.
I decided to use that command as its output contains multiple lines and works perfectly for the example below:
#!/bin/bash
while true; do
COMMAND=$(timedatectl) #Save command result in a var.
echo "$COMMAND" #Print command result, including new lines.
sleep 3 #Keep above's output on screen during 3 seconds before clearing it
#Following code clears previously printed lines
LINES=$(echo "$COMMAND" | wc -l) #Calculate number of lines for the output previously printed
for (( i=1; i <= $(($LINES)); i++ ));do #For each line printed as a result of "timedatectl"
tput cuu1 #Move cursor up by one line
tput el #Clear the line
done
done
The above will print the result of "timedatectl
" forever and will replace the previous echo with updated results.
I have to mention that this code is only an example, but maybe not the best solution for you depending on your needs.
A similar command that would do almost the same (at least visually) is "watch -n 3 timedatectl
".
But that's a different story. :)
Hope that helps!
Use the following selector.
$('#attached_docs [value=123]').remove();
If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents
export JAVA_OPTS="-server -Xmx512m"
For Windows you will need, in setenv.bat, something like
set JAVA_OPTS=-server -Xmx768m
Original answer here
After you run startup.bat
, you can easily confirm the correct settings have been applied provided you have turned @echo
on somewhere in your catatlina.bat
file (a good place could be immediately after echo Using CLASSPATH: "%CLASSPATH%"
):
Try giving your divs a width of 100%
.
Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.
ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.
websocket-node WebSocket server and client for node.js
websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node
faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs
socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.
sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks
faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages
deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response
socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.
primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.
When to use:
use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities
use the fallback libraries when you care about browser fallbacks
use the full featured libraries when you care about channels
use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.
Where to test:
Firecamp is a GUI testing environment for SocketIO, WS and all major real-time technology. Debug the real-time events while you're developing it.
Perl versions 5.10 and later support subsidiary vertical and horizontal character classes, \v
and \h
, as well as the generic whitespace character class \s
The cleanest solution is to use the horizontal whitespace character class \h
. This will match tab and space from the ASCII set, non-breaking space from extended ASCII, or any of these Unicode characters
U+0009 CHARACTER TABULATION
U+0020 SPACE
U+00A0 NO-BREAK SPACE (not matched by \s)
U+1680 OGHAM SPACE MARK
U+2000 EN QUAD
U+2001 EM QUAD
U+2002 EN SPACE
U+2003 EM SPACE
U+2004 THREE-PER-EM SPACE
U+2005 FOUR-PER-EM SPACE
U+2006 SIX-PER-EM SPACE
U+2007 FIGURE SPACE
U+2008 PUNCTUATION SPACE
U+2009 THIN SPACE
U+200A HAIR SPACE
U+202F NARROW NO-BREAK SPACE
U+205F MEDIUM MATHEMATICAL SPACE
U+3000 IDEOGRAPHIC SPACE
The vertical space pattern \v
is less useful, but matches these characters
U+000A LINE FEED
U+000B LINE TABULATION
U+000C FORM FEED
U+000D CARRIAGE RETURN
U+0085 NEXT LINE (not matched by \s)
U+2028 LINE SEPARATOR
U+2029 PARAGRAPH SEPARATOR
There are seven vertical whitespace characters which match \v
and eighteen horizontal ones which match \h
. \s
matches twenty-three characters
All whitespace characters are either vertical or horizontal with no overlap, but they are not proper subsets because \h
also matches U+00A0 NO-BREAK SPACE, and \v
also matches U+0085 NEXT LINE, neither of which are matched by \s
If, as I just encountered, you happen to have a jar file listed in the Project Structures->Libraries that is not in your classpath, the correct answer can be found by following the link given by @CrazyCoder above: Look here http://www.jetbrains.com/idea/webhelp/configuring-module-dependencies-and-libraries.html
This says that to add the jar file as a module dependency within the Project Structure dialog:
Wasn't really happy with the output of jsbeautifier.org for what I was putting in, so I did some more searching and found this site: http://www.centralinternet.com.br/javascript-beautifier
Worked extremely well for me.
This is not your answer and this is an alternate way to process the form submission
$('.signinform').click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'index.php/user/signin', // target element(s) to be updated with server response
dataType:'json',
success : function(response){ console.log(response); alert(response)}
});
});
public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = supportedPermissions
};
return file.Id;
}
In google chrome element.value return the name + the path, but a fake path. Thus, for my case I used the name attribute on the file like below :
function getFileData(myFile){
var file = myFile.files[0];
var filename = file.name;
}
this is the call from the page :
<input id="ph1" name="photo" type="file" class="jq_req" onchange="getFileData(this);"/>
When you have changes on your working copy, from command line do:
git stash
This will stash your changes and clear your status report
git pull
This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge
git stash pop
This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.
if you need to see what is in your stash
git stash list
see the picture. but I have to type enough chars to post the picture.:)
From what I understand you would like to send the images and the values of the inputs together. This code works well for me, I hope it helps someone in the future.
<form id="my-form" method="post" enctype="multipart/form-data">
<input type="file" name="file[]" multiple="" />
<input type="hidden" name="page_id" value="<?php echo $page_id;?>"/>
<input type="hidden" name="category_id" value="<?php echo $item_category->category_id;?>"/>
<input type="hidden" name="method" value="upload"/>
<input type="hidden" name="required[category_id]" value="Category ID"/>
</form>
-
jQuery.ajax({
url: 'post.php',
data: new FormData($('#my-form')[0]),
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}});
Take a look at my short code for ajax multiple upload with preview.
You can use the LocalCommand
command-line option if the PermitLocalCommand
option is enabled:
ssh username@hostname -o LocalCommand="tmux list-sessions"
For more details about the available options, see the ssh_config
man page.
Alternatively, if your objective is to output directly to a file or stdout, you can use cat
:
cat(s1, s2, sep=", ")
here the problem is model binding if you specify a class then the model binding can understand it during the post if it an integer or string then you have to specify the [FromBody] to bind it properly.
make the following changes in FormMethod
using (@Html.BeginForm("myMethod", "Home", FormMethod.Post, new { id = @item.JobId })){
}
and inside your home controller for binding the string you should specify [FromBody]
using System.Web.Http;
[HttpPost]
public FileStreamResult myMethod([FromBody]string id)
{
// Set a local variable with the incoming data
string str = id;
}
FromBody is available in System.Web.Http. make sure you have the reference to that class and added it in the cs file.
It would make sense to maintain a lookup of exceptions to take care of The von Neumann's, McCain's, DeGuzman's, and the Johnson-Smith's.
Just to make this absolutely clear for all:
A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.
This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.
To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.
To qualify the preferred naming conventions:
$?
is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep
command succeeded.
The grep
manpage states:
The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2. (Note: POSIX error handling code should check for '2' or greater.)
So in this case it's checking whether any ERROR lines were found.
Here is a multifunctional function to tackle mail sending with several attachments:
enviaremail() {
values=$(echo "$@" | tr -d '\n')
listargs=()
listargs+=($values)
heirloom-mailx $( attachment=""
for (( a = 5; a < ${#listargs[@]}; a++ )); do
attachment=$(echo "-a ${listargs[a]} ")
echo "${attachment}"
done) -v -s "${titulo}" \
-S smtp-use-starttls \
-S ssl-verify=ignore \
-S smtp-auth=login \
-S smtp=smtp://$1 \
-S from="${2}" \
-S smtp-auth-user=$3 \
-S smtp-auth-password=$4 \
-S ssl-verify=ignore \
$5 < ${cuerpo}
}
function call: enviaremail "smtp.mailserver:port" "from_address" "authuser" "'pass'" "destination" "list of attachments separated by space"
Note: Remove the double quotes in the call
In addition please remember to define externally the $titulo (subject) and $cuerpo (body) of the email prior to using the function
This is a part from a REST-Service I´ve written recently.
var select = $("#productSelect")
for (var prop in data) {
var option = document.createElement('option');
option.innerHTML = data[prop].ProduktName
option.value = data[prop].ProduktName;
select.append(option)
}
The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.
i think i'd try with MAX something like this:
SELECT staff_id, max( date ) from owner.table group by staff_id
then link in your other columns:
select staff_id, site_id, pay_level, latest
from owner.table,
( SELECT staff_id, max( date ) latest from owner.table group by staff_id ) m
where m.staff_id = staff_id
and m.latest = date
This question is kind of old, but wanted to share something which worked for me. Hope it will be useful for people who are searching for some information accessing properties in an external location.
This is what has worked for me.
Property file contents:
PROVIDER_URL=t3://localhost:8003,localhost:8004
applicationContext.xml
file contents: (Spring 3.2.3)
Note: ${user.home}
is a system property from OS.
<context:property-placeholder system-properties-mode="OVERRIDE" location="file:${user.home}/myapp/latest/bin/my-env.properties"/>
<bean id="appsclusterJndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
<prop key="java.naming.provider.url">${PROVIDER_URL}</prop>
</props>
</property>
</bean>
${PROVIDER_URL}
got replaced with the value in the properties the file
You need to use the __getitem__
method.
class MyClass:
def __getitem__(self, key):
return key * 2
myobj = MyClass()
myobj[3] #Output: 6
And if you're going to be setting values you'll need to implement the __setitem__
method too, otherwise this will happen:
>>> myobj[5] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'
There's already a question about this, you could perhaps read it
There's no Clone() method as it exists in Java for example, but you could include a copy constructor in your clases, that's another good approach.
class A
{
private int attr
public int Attr
{
get { return attr; }
set { attr = value }
}
public A()
{
}
public A(A p)
{
this.attr = p.Attr;
}
}
This would be an example, copying the member 'Attr' when building the new object.
If You using Android 9.0 with legacy jar than you have to use. in your mainfest file.
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
You can create your own lock with GET_LOCK(lockName,timeOut)
If you do a GET_LOCK(lockName, 0)
with a 0 time out before you lock the tables and then follow that with a RELEASE_LOCK(lockName)
then all other threads performing a GET_LOCK()
will get a value of 0 which will tell them that the lock is being held by another thread.
However this won't work if you don't have all threads calling GET_LOCK()
before locking tables. The documentation for locking tables is here
Hope that helps!
You can simply write in Ajax Success like below :
$.ajax({
type: "POST",
url: '@Url.Action("GetUserList", "User")',
data: { id: $("#UID").val() },
success: function (data) {
window.location.href = '@Url.Action("Dashboard", "User")';
},
error: function () {
$("#loader").fadeOut("slow");
}
});
After reading the answer from Gilles, I decided to see if the $BASH_COMMAND
var was also available (and the desired value) in an EXIT
trap - and it is!
So, the following bash script works as expected:
#!/bin/bash
exit_trap () {
local lc="$BASH_COMMAND" rc=$?
echo "Command [$lc] exited with code [$rc]"
}
trap exit_trap EXIT
set -e
echo "foo"
false 12345
echo "bar"
The output is
foo
Command [false 12345] exited with code [1]
bar
is never printed because set -e
causes bash to exit the script when a command fails and the false command always fails (by definition). The 12345
passed to false
is just there to show that the arguments to the failed command are captured as well (the false
command ignores any arguments passed to it)
In general I fully agree with Jason's use of css selector, but in some cases you may not want to change the css, e.g. when using a 3rd party css-template, and rather prefer to add/remove a class on the element.
The following sample shows a simple way of adding/removing a class on ng-mouseenter/mouseleave:
<div ng-app>
<div
class="italic"
ng-class="{red: hover}"
ng-init="hover = false"
ng-mouseenter="hover = true"
ng-mouseleave="hover = false">
Test 1 2 3.
</div>
</div>
with some styling:
.red {
background-color: red;
}
.italic {
font-style: italic;
color: black;
}
See running example here: jsfiddle sample
Styling on hovering is a view concern. Although the solution above sets a "hover" property in the current scope, the controller does not need to be concerned about this.
If you want a (almost) one-liner:
from collections import deque d = {} deque((d.setdefault(year, []).append(value) for year, value in source_of_data), maxlen=0)
Using dict.setdefault
, you can encapsulate the idea of "check if the key already exists and make a new list if not" into a single call. This allows you to write a generator expression which is consumed by deque
as efficiently as possible since the queue length is set to zero. The deque will be discarded immediately and the result will be in d
.
This is something I just did for fun. I don't recommend using it. There is a time and a place to consume arbitrary iterables through a deque, and this is definitely not it.
Here's another answer that has an option to append decimal ONLY IF decimal was not zero.
/**
* Example: (isDecimalRequired = true)
* d = 12345
* returns 12,345.00
*
* d = 12345.12345
* returns 12,345.12
*
* ==================================================
* Example: (isDecimalRequired = false)
* d = 12345
* returns 12,345 (notice that there's no decimal since it's zero)
*
* d = 12345.12345
* returns 12,345.12
*
* @param d float to format
* @param zeroCount number decimal places
* @param isDecimalRequired true if it will put decimal even zero,
* false will remove the last decimal(s) if zero.
*/
fun formatDecimal(d: Float? = 0f, zeroCount: Int, isDecimalRequired: Boolean = true): String {
val zeros = StringBuilder()
for (i in 0 until zeroCount) {
zeros.append("0")
}
var pattern = "#,##0"
if (zeros.isNotEmpty()) {
pattern += ".$zeros"
}
val numberFormat = DecimalFormat(pattern)
var formattedNumber = if (d != null) numberFormat.format(d) else "0"
if (!isDecimalRequired) {
for (i in formattedNumber.length downTo formattedNumber.length - zeroCount) {
val number = formattedNumber[i - 1]
if (number == '0' || number == '.') {
formattedNumber = formattedNumber.substring(0, formattedNumber.length - 1)
} else {
break
}
}
}
return formattedNumber
}
Here's another module for consideration. It seems a viable choice for more demanding applications.
Py-notify is a Python package providing tools for implementing Observer programming pattern. These tools include signals, conditions and variables.
Signals are lists of handlers that are called when signal is emitted. Conditions are basically boolean variables coupled with a signal that is emitted when condition state changes. They can be combined using standard logical operators (not, and, etc.) into compound conditions. Variables, unlike conditions, can hold any Python object, not just booleans, but they cannot be combined.
i assume you are working with nullable datatypes, you can do something like this:
var t = things.Where(x => x!=null && x.Value.ID == long.Parse(options.ID)).FirstOrDefault();
var res = t == null ? "" : t.Value;
You'll need to also set the height of the element to 0 when it's hidden. I ran into this problem while using jQuery, my solution was to set the height and opacity to 0 when it's hidden, then change height to auto and opacity to 1 when it's un-hidden.
I'd recommend looking at jQuery. It's pretty easy to pick up and will allow you to do things like this a lot more easily.
$('#yesCheck').click(function() {
$('#ifYes').slideDown();
});
$('#noCheck').click(function() {
$('#ifYes').slideUp();
});
It's slightly better for performance to change the CSS with jQuery and use CSS3 animations to do the dropdown, but that's also more complex. The example above should work, but I haven't tested it.
Solution to this problem is simple
Go to build.gradle (module.app) file
It will help us to rebuild gradle for the project, to make it sync again.
The CURL extension ext/curl
is not installed or enabled in your PHP installation. Check the manual for information on how to install or enable CURL on your system.
So I found a solution. I created an angularJS service, we'll call it MyDataRepository and I created a module for it. I then serve up this javascript file from my server-side controller:
HTML:
<script src="path/myData.js"></script>
Server-side:
@RequestMapping(value="path/myData.js", method=RequestMethod.GET)
public ResponseEntity<String> getMyDataRepositoryJS()
{
// Populate data that I need into a Map
Map<String, String> myData = new HashMap<String,String>();
...
// Use Jackson to convert it to JSON
ObjectMapper mapper = new ObjectMapper();
String myDataStr = mapper.writeValueAsString(myData);
// Then create a String that is my javascript file
String myJS = "'use strict';" +
"(function() {" +
"var myDataModule = angular.module('myApp.myData', []);" +
"myDataModule.service('MyDataRepository', function() {" +
"var myData = "+myDataStr+";" +
"return {" +
"getData: function () {" +
"return myData;" +
"}" +
"}" +
"});" +
"})();"
// Now send it to the client:
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/javascript");
return new ResponseEntity<String>(myJS , responseHeaders, HttpStatus.OK);
}
I can then inject MyDataRepository where ever I need it:
someOtherModule.service('MyOtherService', function(MyDataRepository) {
var myData = MyDataRepository.getData();
// Do what you have to do...
}
This worked great for me, but I am open to any feedback if anyone has any. }
Edit the colorPrimary in the colors.xml in Values to the color you want the Status Bar to be. For example:
<resources>
<color name="colorPrimary">#800000</color> // changes the status bar color to Burgundy
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="red">#FF0000</color>
<color name="white">#FFFFFF</color>
<color name="cream">#fffdd0</color>
<color name="burgundy">#800000</color>
If you want to use Java 8 streams and are allergic to while
loops, you could try this:
public static int countPattern(String references, Pattern referencePattern) {
Matcher matcher = referencePattern.matcher(references);
return Stream.iterate(0, i -> i + 1)
.filter(i -> !matcher.find())
.findFirst()
.get();
}
Disclaimer: this only works for disjoint matches.
Example:
public static void main(String[] args) throws ParseException {
Pattern referencePattern = Pattern.compile("PASSENGER:\\d+");
System.out.println(countPattern("[ \"PASSENGER:1\", \"PASSENGER:2\", \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\", \"PASSENGER:1\" ]", referencePattern));
System.out.println(countPattern("[ ]", referencePattern));
}
This prints out:
2
0
1
0
This is a solution for disjoint matches with streams:
public static int countPattern(String references, Pattern referencePattern) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
new Iterator<Integer>() {
Matcher matcher = referencePattern.matcher(references);
int from = 0;
@Override
public boolean hasNext() {
return matcher.find(from);
}
@Override
public Integer next() {
from = matcher.start() + 1;
return 1;
}
},
Spliterator.IMMUTABLE), false).reduce(0, (a, c) -> a + c);
}
As well as the previous answers are you could always use the Pull attrib as well:
<ol class="row" id="possibilities">
<li class="span6">
<div class="row">
<div class="span3">
<p>some text here</p>
<p>Text Here too</p>
</div>
<figure class="span3 pull-right"><img src="img/screenshots/options.png" alt="Some text" /></figure>
</div>
</li>
<li class="span6">
<div class="row">
<figure class="span3"><img src="img/qrcode.png" alt="Some text" /></figure>
<div class="span3">
<p>Some text</p>
<p>Some text here too.</p>
</div>
</div>
</li>
Another option besides awk is nl which allows for options -v
for setting starting value and -n <lf,rf,rz>
for left, right and right with leading zeros justified. You can also include -s
for a field separator such as -s ","
for comma separation between line numbers and your data.
In a Unix environment, this can be done as
cat <infile> | ...other stuff... | nl -v 0 -n rz
or simply
nl -v 0 -n rz <infile>
Example:
echo "Here
are
some
words" > words.txt
cat words.txt | nl -v 0 -n rz
Out:
000000 Here
000001 are
000002 some
000003 words
If you need to add multiple key=>value, then try this.
$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));
Here's another way to drop a default constraint with an unknown name without having to first run a separate query to get the constraint name:
DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
WHERE NAME = N'__ColumnName__'
AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
You call both event listeners using .on()
then use a if
inside the function:
$(function(){
$('#searchButton').on('keypress click', function(e){
var search = $('#usersSearch').val();
if (e.which === 13 || e.type === 'click') {
$.post('../searchusers.php', {search: search}, function (response) {
$('#userSearchResultsTable').html(response);
});
}
});
});
select substring(your_field, CHARINDEX(';',your_field)+1 ,CHARINDEX('[',your_field)-CHARINDEX(';',your_field)-1) from your_table
Can't get the others to work. I believe you just want what is in between ';' and '[' in all cases regardless of how long the string in between is. After specifying the field in the substring function, the second argument is the starting location of what you will extract. That is, where the ';' is + 1 (fourth position - the c), because you don't want to include ';'. The next argument takes the location of the '[' (position 14) and subtracts the location of the spot after the ';' (fourth position - this is why I now subtract 1 in the query). This basically says substring(field,location I want substring to begin, how long I want substring to be). I've used this same function in other cases. If some of the fields don't have ';' and '[', you'll want to filter those out in the "where" clause, but that's a little different than the question. If your ';' was say... ';;;', you would use 3 instead of 1 in the example. Hope this helps!
This way you can create Observable from data, in my case I need to maintain shopping cart:
service.ts
export class OrderService {
cartItems: BehaviorSubject<Array<any>> = new BehaviorSubject([]);
cartItems$ = this.cartItems.asObservable();
// I need to maintain cart, so add items in cart
addCartData(data) {
const currentValue = this.cartItems.value; // get current items in cart
const updatedValue = [...currentValue, data]; // push new item in cart
if(updatedValue.length) {
this.cartItems.next(updatedValue); // notify to all subscribers
}
}
}
Component.ts
export class CartViewComponent implements OnInit {
cartProductList: any = [];
constructor(
private order: OrderService
) { }
ngOnInit() {
this.order.cartItems$.subscribe(items => {
this.cartProductList = items;
});
}
}
As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.
getRequest().getSession().setMaxInactiveInterval(123);
Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec
.
If you're still here, the following discussion should hopefully reveal why. When you run, say,
sh -c 'command'
you run a sh
instance, then start command
as a child of that sh
instance. When command
finishes, the sh
instance also finishes.
sh -c 'exec command'
runs a sh
instance, then replaces that sh
instance with the command
binary, and runs that instead.
Of course, both of these are useless in this limited context; you simply want
command
There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command
. This is pretty much the sole situation where exec command
is useful.
#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command
This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh
instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh
instance with the command
process, rather than have sh
run it as a child process and wait for it, then exit as soon as it finishes.
Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec
that command as an optimization.
If something forces you to run sh
but you really wanted to run something else, exec something else
is of course a workaround to replace the undesired sh
instance (like for example if you really wanted to run your own spiffy gosh
instead of sh
but yours isn't listed in /etc/shells
so you can't specify it as your login shell).
The second use of exec
to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec
is followed by a redirect instead of a command name.
I got things working nicely while exposing $
and jQuery
as global variables with Webpack 3.8.1 and the following.
Install jQuery as a project dependency. You can omit @3.2.1
to install the latest version or specify another version.
npm install --save [email protected]
Install expose-loader
as a development dependency if not installed already.
npm install expose-loader --save-dev
Configure Webpack to load and expose jQuery for us.
// webpack.config.js
const webpack = require('webpack')
module.exports = {
entry: [
// entry bits
],
output: {
// output bits
},
module: {
rules: [
// any other rules
{
// Exposes jQuery for use outside Webpack build
test: require.resolve('jquery'),
use: [{
loader: 'expose-loader',
options: 'jQuery'
},{
loader: 'expose-loader',
options: '$'
}]
}
]
},
plugins: [
// Provides jQuery for other JS bundled with Webpack
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
}
You could create a class to represent this
public class Range
{
private int low;
private int high;
public Range(int low, int high){
this.low = low;
this.high = high;
}
public boolean contains(int number){
return (number >= low && number <= high);
}
}
Sample usage:
Range range = new Range(0, 2147483647);
if (range.contains(foo)) {
//do something
}
As nobody published a solution with CountDownLatch. What about:
public class Lockeable {
private final CountDownLatch countDownLatch = new CountDownLatch(1);
public void doAfterEvent(){
countDownLatch.await();
doSomething();
}
public void reportDetonatingEvent(){
countDownLatch.countDown();
}
}
You can rename (changing URL of a remote repository) using :
git remote set-url origin new_URL
new_URL can be like https://github.com/abcdefgh/abcd.git
Too permanently delete the remote repository use :
git remote remove origin
Just Change your folder name from lib
to libs
,
Then you will see some error marks in your project, to resolve this rightClick on project >
Properties > Java Build Path > libraries
:
Remove all the library with red marks on it, then apply > ok >
after that clean your project . TADA see the magic :)
Try:
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Did you turn on the "Allow less secure apps" on? go to this link
https://myaccount.google.com/security#connectedapps
Take a look at the Sign-in & security -> Apps with account access menu.
You must turn the option "Allow less secure apps" ON.
If is still doesn't work try one of these:
Go to https://accounts.google.com/UnlockCaptcha , and click continue and unlock your account for access through other media/sites.
Use double quote in your password: "your password"
And change your .env file
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=xxxxxx
MAIL_ENCRYPTION=tls
because the one's you have specified in the mail.php will only be used if the value is not available in the .env file.
To fix this issue through R itself, I just used read.xlsx(..)
instead of a read.csv()
. Works like a charm!! You do not even have to rename. Renaming an xlsx into to csv is not a viable solution.
provide all custom services means written by you in component decorator section Example : providers: [serviceName]
note:if you are using service for exchanging data between components. declare providers: [serviceName] in module level
Semantically what you are trying is invalid html, table
element cannot have a div
element as a direct child. What you can do is, get your div
element inside a td
element and than try to hide it
If you're using Weebly, start by viewing the published site and right-clicking the image to Copy Image Address. Then in Weebly, go to Edit Site, Pages, click the page you wish to use, SEO Settings, under Header Code enter the code from Shef's answer:
<meta property="og:image" content="/uploads/..." />
just replacing /uploads/... with the copied image address. Click Publish to apply the change.
You can skip the part of Shef's answer about namespace, because that's already set by default in Weebly.
Try using the COLUMN command with the FORMAT option for that:
COLUMN COLUMN_NAME FORMAT 99.99
SELECT COLUMN_NAME FROM ....
pymssql is a DB-API Python module, based on FreeTDS. It worked for me. Create some helper functions, if you need, and use it from Python shell.
Based on a previous answer, I have created a function that can also handle brackets. But no dots inside them due to the split.
function get(obj, str) {
return str.split(/\.|\[/g).map(function(crumb) {
return crumb.replace(/\]$/, '').trim().replace(/^(["'])((?:(?!\1)[^\\]|\\.)*?)\1$/, (match, quote, str) => str.replace(/\\(\\)?/g, "$1"));
}).reduce(function(obj, prop) {
return obj ? obj[prop] : undefined;
}, obj);
}
i found none of the examples above met my needs, i wanted to copy a directory with sub directories, the problem is my source directory had too many files so i quickly hit the BITS file limit (i had > 1500 file) also the total directory size was quite large.
i found a function using robocopy that was a good starting point at https://keithga.wordpress.com/2014/06/23/copy-itemwithprogress/, however i found it wasn't quite robust enough, it didn't handle trailing slashes, spaces gracefully and did not stop the copy when the script was halted.
Here is my refined version:
function Copy-ItemWithProgress
{
<#
.SYNOPSIS
RoboCopy with PowerShell progress.
.DESCRIPTION
Performs file copy with RoboCopy. Output from RoboCopy is captured,
parsed, and returned as Powershell native status and progress.
.PARAMETER Source
Directory to copy files from, this should not contain trailing slashes
.PARAMETER Destination
DIrectory to copy files to, this should not contain trailing slahes
.PARAMETER FilesToCopy
A wildcard expresion of which files to copy, defaults to *.*
.PARAMETER RobocopyArgs
List of arguments passed directly to Robocopy.
Must not conflict with defaults: /ndl /TEE /Bytes /NC /nfl /Log
.PARAMETER ProgressID
When specified (>=0) will use this identifier for the progress bar
.PARAMETER ParentProgressID
When specified (>= 0) will use this identifier as the parent ID for progress bars
so that they appear nested which allows for usage in more complex scripts.
.OUTPUTS
Returns an object with the status of final copy.
REMINDER: Any error level below 8 can be considered a success by RoboCopy.
.EXAMPLE
C:\PS> .\Copy-ItemWithProgress c:\Src d:\Dest
Copy the contents of the c:\Src directory to a directory d:\Dest
Without the /e or /mir switch, only files from the root of c:\src are copied.
.EXAMPLE
C:\PS> .\Copy-ItemWithProgress '"c:\Src Files"' d:\Dest /mir /xf *.log -Verbose
Copy the contents of the 'c:\Name with Space' directory to a directory d:\Dest
/mir and /XF parameters are passed to robocopy, and script is run verbose
.LINK
https://keithga.wordpress.com/2014/06/23/copy-itemwithprogress
.NOTES
By Keith S. Garner ([email protected]) - 6/23/2014
With inspiration by Trevor Sullivan @pcgeek86
Tweaked by Justin Marshall - 02/20/2020
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Source,
[Parameter(Mandatory=$true)]
[string]$Destination,
[Parameter(Mandatory=$false)]
[string]$FilesToCopy="*.*",
[Parameter(Mandatory = $true,ValueFromRemainingArguments=$true)]
[string[]] $RobocopyArgs,
[int]$ParentProgressID=-1,
[int]$ProgressID=-1
)
#handle spaces and trailing slashes
$SourceDir = '"{0}"' -f ($Source -replace "\\+$","")
$TargetDir = '"{0}"' -f ($Destination -replace "\\+$","")
$ScanLog = [IO.Path]::GetTempFileName()
$RoboLog = [IO.Path]::GetTempFileName()
$ScanArgs = @($SourceDir,$TargetDir,$FilesToCopy) + $RobocopyArgs + "/ndl /TEE /bytes /Log:$ScanLog /nfl /L".Split(" ")
$RoboArgs = @($SourceDir,$TargetDir,$FilesToCopy) + $RobocopyArgs + "/ndl /TEE /bytes /Log:$RoboLog /NC".Split(" ")
# Launch Robocopy Processes
write-verbose ("Robocopy Scan:`n" + ($ScanArgs -join " "))
write-verbose ("Robocopy Full:`n" + ($RoboArgs -join " "))
$ScanRun = start-process robocopy -PassThru -WindowStyle Hidden -ArgumentList $ScanArgs
try
{
$RoboRun = start-process robocopy -PassThru -WindowStyle Hidden -ArgumentList $RoboArgs
try
{
# Parse Robocopy "Scan" pass
$ScanRun.WaitForExit()
$LogData = get-content $ScanLog
if ($ScanRun.ExitCode -ge 8)
{
$LogData|out-string|Write-Error
throw "Robocopy $($ScanRun.ExitCode)"
}
$FileSize = [regex]::Match($LogData[-4],".+:\s+(\d+)\s+(\d+)").Groups[2].Value
write-verbose ("Robocopy Bytes: $FileSize `n" +($LogData -join "`n"))
#determine progress parameters
$ProgressParms=@{}
if ($ParentProgressID -ge 0) {
$ProgressParms['ParentID']=$ParentProgressID
}
if ($ProgressID -ge 0) {
$ProgressParms['ID']=$ProgressID
} else {
$ProgressParms['ID']=$RoboRun.Id
}
# Monitor Full RoboCopy
while (!$RoboRun.HasExited)
{
$LogData = get-content $RoboLog
$Files = $LogData -match "^\s*(\d+)\s+(\S+)"
if ($null -ne $Files )
{
$copied = ($Files[0..($Files.Length-2)] | ForEach-Object {$_.Split("`t")[-2]} | Measure-Object -sum).Sum
if ($LogData[-1] -match "(100|\d?\d\.\d)\%")
{
write-progress Copy -ParentID $ProgressParms['ID'] -percentComplete $LogData[-1].Trim("% `t") $LogData[-1]
$Copied += $Files[-1].Split("`t")[-2] /100 * ($LogData[-1].Trim("% `t"))
}
else
{
write-progress Copy -ParentID $ProgressParms['ID'] -Complete
}
write-progress ROBOCOPY -PercentComplete ($Copied/$FileSize*100) $Files[-1].Split("`t")[-1] @ProgressParms
}
}
} finally {
if (!$RoboRun.HasExited) {Write-Warning "Terminating copy process with ID $($RoboRun.Id)..."; $RoboRun.Kill() ; }
$RoboRun.WaitForExit()
# Parse full RoboCopy pass results, and cleanup
(get-content $RoboLog)[-11..-2] | out-string | Write-Verbose
remove-item $RoboLog
write-output ([PSCustomObject]@{ ExitCode = $RoboRun.ExitCode })
}
} finally {
if (!$ScanRun.HasExited) {Write-Warning "Terminating scan process with ID $($ScanRun.Id)..."; $ScanRun.Kill() }
$ScanRun.WaitForExit()
remove-item $ScanLog
}
}
My solution:
Try to find if this is an inodes problem with:
df -ih
Try to find root folders with large inodes count:
for i in /*; do echo $i; find $i |wc -l; done
Try to find specific folders:
for i in /src/*; do echo $i; find $i |wc -l; done
If this is linux headers, try to remove oldest with:
sudo apt-get autoremove linux-headers-3.13.0-24
Personally I moved them to a mounted folder (because for me last command failed) and installed the latest with:
sudo apt-get autoremove -f
This solved my problem.
To list and see contents of all abc.def files on a server in the directories /ghi and /jkl
find /ghi /jkl -type f -name abc.def 2> /dev/null -exec ls {} \; -exec cat {} \;
To list the abc.def files which have commented entries and display see those entries in the directories /ghi and /jkl
find /ghi /jkl -type f -name abc.def 2> /dev/null -exec grep -H ^# {} \;
If you're using gnu sed then you can use \x0A
for newline:
sed 's/:/\x0A/g' ~/Desktop/myfile.txt
That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.
To change your Platform Toolset:
git pull
= git fetch
+ git merge origin/branch
git pull
and git pull origin branch
only differ in that the latter will only "update" origin/branch and not all origin/* as git pull
does.
git pull origin/branch
will just not work because it's trying to do a git fetch origin/branch
which is invalid.
Question related: git fetch + git merge origin/master vs git pull origin/master
time.time()
will do the job.
import time
start = time.time()
# run your code
end = time.time()
elapsed = end - start
You may want to look at this question, but I don't think it will be necessary.
You can use load_only function:
from sqlalchemy.orm import load_only
fields = ['name', 'addr', 'phone', 'url']
companies = session.query(SomeModel).options(load_only(*fields)).all()
You can define your title programatically using setTitle
within your Activity
, this method can accept either a String
or an ID defined in your values/strings.xml
file. Example:
public class YourActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
setTitle(R.string.your_title);
setContentView(R.layout.main);
}
}
Quite simple:
$input = array(
array(
'tag_name' => 'google'
),
array(
'tag_name' => 'technology'
)
);
echo implode(', ', array_map(function ($entry) {
return $entry['tag_name'];
}, $input));
and new in php v5.5.0, array_column
:
echo implode(', ', array_column($input, 'tag_name'));
Enter git-forward-merge:
Without needing to checkout destination,
git-forward-merge <source> <destination>
merges source into destination branch.
https://github.com/schuyler1d/git-forward-merge
Only works for automatic merges, if there are conflicts you need to use the regular merge.
I found good answer here Adding Role dynamically in new VS 2013 Identity UserManager
But in case to provide an example so you can check it I am gonna share some default code.
First make sure you have Roles inserted.
And second test it on user register method.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var currentUser = UserManager.FindByName(user.UserName);
var roleresult = UserManager.AddToRole(currentUser.Id, "Superusers");
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
And finally you have to get "Superusers" from the Roles Dropdown List somehow.
If selection is not important, it is better to use an ItemsControl wrapped in a ScrollViewer. This combination is more light-weight than the Listbox (which actually is derived from ItemsControl already) and using it would eliminate the need to use a cheap hack to override behavior that is already absent from the ItemsControl.
In cases where the selection behavior IS actually important, then this obviously will not work. However, if you want to change the color of the Selected Item Background in such a way that it is not visible to the user, then that would only serve to confuse them. In cases where your intention is to change some other characteristic to indicate that the item is selected, then some of the other answers to this question may still be more relevant.
Here is a skeleton of how the markup should look:
<ScrollViewer>
<ItemsControl>
<ItemsControl.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
I had to add a .toString
to the item in the values array. Without it, it would only match if the entire cell body matched the searchTerm
.
function foo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('spreadsheet-name');
var r = s.getRange('A:A');
var v = r.getValues();
var searchTerm = 'needle';
for(var i=v.length-1;i>=0;i--) {
if(v[0,i].toString().indexOf(searchTerm) > -1) {
// do something
}
}
};
This is what I came up with. In between web projects, unit tests (nunit and resharper test runner); I found this worked for me.
I have been looking for code to detect what configuration the build is in, Debug/Release/CustomName
. Alas, the #if DEBUG
. So if someone can improve that!
Feel free to edit and improve.
Getting app folder. Useful for web roots, unittests to get the folder of test files.
public static string AppPath
{
get
{
DirectoryInfo appPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
while (appPath.FullName.Contains(@"\bin\", StringComparison.CurrentCultureIgnoreCase)
|| appPath.FullName.EndsWith(@"\bin", StringComparison.CurrentCultureIgnoreCase))
{
appPath = appPath.Parent;
}
return appPath.FullName;
}
}
Getting bin folder: Useful for executing assemblies using reflection. If files are copied there due to build properties.
public static string BinPath
{
get
{
string binPath = AppDomain.CurrentDomain.BaseDirectory;
if (!binPath.Contains(@"\bin\", StringComparison.CurrentCultureIgnoreCase)
&& !binPath.EndsWith(@"\bin", StringComparison.CurrentCultureIgnoreCase))
{
binPath = Path.Combine(binPath, "bin");
//-- Please improve this if there is a better way
//-- Also note that apps like webapps do not have a debug or release folder. So we would just return bin.
#if DEBUG
if (Directory.Exists(Path.Combine(binPath, "Debug")))
binPath = Path.Combine(binPath, "Debug");
#else
if (Directory.Exists(Path.Combine(binPath, "Release")))
binPath = Path.Combine(binPath, "Release");
#endif
}
return binPath;
}
}
You need to do a while loop to get the result from the SQL query, like this:
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )
FROM modul1open) ORDER BY idM1O LIMIT 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
// If you want to display all results from the query at once:
print_r($row);
// If you want to display the results one by one
echo $row['column1'];
echo $row['column2']; // etc..
}
Also I would strongly recommend not using mysql_* since it's deprecated. Instead use the mysqli
or PDO
extension. You can read more about that here.
The main difference is that WHERE
cannot be used on grouped item (such as SUM(number)
) whereas HAVING
can.
The reason is the WHERE
is done before the grouping and HAVING
is done after the grouping is done.
If we use runnable method SwingUtilities.invokeLater() while using Document listener application is getting stuck sometimes and taking time to update the result(As per my experiment). Instead of that we can also use KeyReleased event for text field change listener as mentioned here.
usernameTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
textField.setText(text.toUpperCase());
}
});
function function_one() {_x000D_
function_two(); // considering the next alert, I figured you wanted to call function_two first_x000D_
alert("The function called 'function_one' has been called.");_x000D_
}_x000D_
_x000D_
function function_two() {_x000D_
alert("The function called 'function_two' has been called.");_x000D_
}_x000D_
_x000D_
function_one();
_x000D_
A little bit more context: this works in JavaScript because of a language feature called "variable hoisting" - basically, think of it like variable/function declarations are put at the top of the scope (more info).
According to the official ReactJs documentation, you need to pass argument in the default format witch is:
P = {} // default for your props
S = {} // default for yout state
interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }
Or to define your own type like below: (just an exp)
interface IProps {
clients: Readonly<IClientModel[]>;
onSubmit: (data: IClientModel) => void;
}
interface IState {
clients: Readonly<IClientModel[]>;
loading: boolean;
}
class ClientsPage extends React.Component<IProps, IState> {
// ...
}
You can do something like
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next().toString();
Integer value = map.get(key);
System.out.println(key + " " + value);
}
Here 'map' is your concurrent HashMap.
Dump DB by mongodump
mongodump --host <database-host> -d <database-name> --port <database-port> --out directory
Restore DB by mongorestore
With Index Restore
mongorestore --host <database-host> -d <database-name> --port <database-port> foldername
Without Index Restore
mongorestore --noIndexRestore --host <database-host> -d <database-name> --port <database-port> foldername
Import Single Collection from CSV [1st Column will be treat as Col/Key Name]
mongoimport --db <database-name> --port <database-port> --collection <collection-name> --type csv --headerline --file /path/to/myfile.csv
Import Single Collection from JSON
mongoimport --db <database-name> --port <database-port> --collection <collection-name> --file input.json
First, you need to add HttpHeaders with HttpClient
import { HttpClient,HttpHeaders } from '@angular/common/http';
your constructor should be like this.
constructor(private http: HttpClient) { }
then you can use like this
let header = new HttpHeaders({ "Authorization": "Bearer "+token});
const requestOptions = { headers: header};
return this.http.get<any>(url, requestOptions)
.toPromise()
.then(data=> {
//...
return data;
});
Example
public class myThread extends Thread{
@override
public void run(){
while(true){
threadCondWait();// Circle waiting...
//bla bla bla bla
}
}
public synchronized void threadCondWait(){
while(myCondition){
wait();//Comminucate with notify()
}
}
}
public class myAnotherThread extends Thread{
@override
public void run(){
//Bla Bla bla
notify();//Trigger wait() Next Step
}
}
Perhaps you want to do
soup.find("li", { "class" : "test" }).find('a')
This is an interesting discussion. I think that @flodel's example is excellent. However, I think it illustrates my point (and @koshke mentions this in a comment) that return
makes sense when you use an imperative instead of a functional coding style.
Not to belabour the point, but I would have rewritten foo
like this:
foo = function() ifelse(a,a,b)
A functional style avoids state changes, like storing the value of output
. In this style, return
is out of place; foo
looks more like a mathematical function.
I agree with @flodel: using an intricate system of boolean variables in bar
would be less clear, and pointless when you have return
. What makes bar
so amenable to return
statements is that it is written in an imperative style. Indeed, the boolean variables represent the "state" changes avoided in a functional style.
It is really difficult to rewrite bar
in functional style, because it is just pseudocode, but the idea is something like this:
e_func <- function() do_stuff
d_func <- function() ifelse(any(sapply(seq(d),e_func)),2,3)
b_func <- function() {
do_stuff
ifelse(c,1,sapply(seq(b),d_func))
}
bar <- function () {
do_stuff
sapply(seq(a),b_func) # Not exactly correct, but illustrates the idea.
}
The while
loop would be the most difficult to rewrite, because it is controlled by state changes to a
.
The speed loss caused by a call to return
is negligible, but the efficiency gained by avoiding return
and rewriting in a functional style is often enormous. Telling new users to stop using return
probably won't help, but guiding them to a functional style will payoff.
@Paul return
is necessary in imperative style because you often want to exit the function at different points in a loop. A functional style doesn't use loops, and therefore doesn't need return
. In a purely functional style, the final call is almost always the desired return value.
In Python, functions require a return
statement. However, if you programmed your function in a functional style, you will likely have only one return
statement: at the end of your function.
Using an example from another StackOverflow post, let us say we wanted a function that returned TRUE
if all the values in a given x
had an odd length. We could use two styles:
# Procedural / Imperative
allOdd = function(x) {
for (i in x) if (length(i) %% 2 == 0) return (FALSE)
return (TRUE)
}
# Functional
allOdd = function(x)
all(length(x) %% 2 == 1)
In a functional style, the value to be returned naturally falls at the ends of the function. Again, it looks more like a mathematical function.
@GSee The warnings outlined in ?ifelse
are definitely interesting, but I don't think they are trying to dissuade use of the function. In fact, ifelse
has the advantage of automatically vectorizing functions. For example, consider a slightly modified version of foo
:
foo = function(a) { # Note that it now has an argument
if(a) {
return(a)
} else {
return(b)
}
}
This function works fine when length(a)
is 1. But if you rewrote foo
with an ifelse
foo = function (a) ifelse(a,a,b)
Now foo
works on any length of a
. In fact, it would even work when a
is a matrix. Returning a value the same shape as test
is a feature that helps with vectorization, not a problem.
I am just updating this with Microsoft SQL Server Management Studio 2008 R2 version. if you run the installer normally, you can just add Management Tools – Basic, and by clicking Basic it should select Management Tools – Complete.
That is what worked for me.
Updated: As of React > 0.16
Render method does not necessarily have to return a single element. An array can also be returned.
var indents = [];
for (var i = 0; i < this.props.level; i++) {
indents.push(<span className='indent' key={i}></span>);
}
return indents;
OR
return this.props.level.map((item, index) => (
<span className="indent" key={index}>
{index}
</span>
));
Docs here explaining about JSX children
OLD:
You can use one loop instead
var indents = [];
for (var i = 0; i < this.props.level; i++) {
indents.push(<span className='indent' key={i}></span>);
}
return (
<div>
{indents}
"Some text value"
</div>
);
You can also use .map and fancy es6
return (
<div>
{this.props.level.map((item, index) => (
<span className='indent' key={index} />
))}
"Some text value"
</div>
);
Also, you have to wrap the return value in a container. I used div in the above example
As the docs say here
Currently, in a component's render, you can only return one node; if you have, say, a list of divs to return, you must wrap your components within a div, span or any other component.
recursion + memorization could lead to a more efficient solution compare with a pure iterative approach, e.g. check this: http://jsperf.com/fibonacci-memoized-vs-iterative-for-large-n
I converted the script to Python3 and ran it on my Raspberry Pi 3B+:
import time
import threading
def t():
with open('/dev/urandom', 'rb') as f:
for x in range(100):
f.read(4 * 65535)
if __name__ == '__main__':
start_time = time.time()
t()
t()
t()
t()
print("Sequential run time: %.2f seconds" % (time.time() - start_time))
start_time = time.time()
t1 = threading.Thread(target=t)
t2 = threading.Thread(target=t)
t3 = threading.Thread(target=t)
t4 = threading.Thread(target=t)
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
print("Parallel run time: %.2f seconds" % (time.time() - start_time))
python3 t.py
Sequential run time: 2.10 seconds
Parallel run time: 1.41 seconds
For me, running parallel was quicker.
Objects never go out of scope in C# as they do in C++. They are dealt with by the Garbage Collector automatically when they are not used anymore. This is a more complicated approach than C++ where the scope of a variable is entirely deterministic. CLR garbage collector actively goes through all objects that have been created and works out if they are being used.
An object can go "out of scope" in one function but if its value is returned, then GC would look at whether or not the calling function holds onto the return value.
Setting object references to null
is unnecessary as garbage collection works by working out which objects are being referenced by other objects.
In practice, you don't have to worry about destruction, it just works and it's great :)
Dispose
must be called on all objects that implement IDisposable
when you are finished working with them. Normally you would use a using
block with those objects like so:
using (var ms = new MemoryStream()) {
//...
}
EDIT On variable scope. Craig has asked whether the variable scope has any effect on the object lifetime. To properly explain that aspect of CLR, I'll need to explain a few concepts from C++ and C#.
In both languages the variable can only be used in the same scope as it was defined - class, function or a statement block enclosed by braces. The subtle difference, however, is that in C#, variables cannot be redefined in a nested block.
In C++, this is perfectly legal:
int iVal = 8;
//iVal == 8
if (iVal == 8){
int iVal = 5;
//iVal == 5
}
//iVal == 8
In C#, however you get a a compiler error:
int iVal = 8;
if(iVal == 8) {
int iVal = 5; //error CS0136: A local variable named 'iVal' cannot be declared in this scope because it would give a different meaning to 'iVal', which is already used in a 'parent or current' scope to denote something else
}
This makes sense if you look at generated MSIL - all the variables used by the function are defined at the start of the function. Take a look at this function:
public static void Scope() {
int iVal = 8;
if(iVal == 8) {
int iVal2 = 5;
}
}
Below is the generated IL. Note that iVal2, which is defined inside the if block is actually defined at function level. Effectively this means that C# only has class and function level scope as far as variable lifetime is concerned.
.method public hidebysig static void Scope() cil managed
{
// Code size 19 (0x13)
.maxstack 2
.locals init ([0] int32 iVal,
[1] int32 iVal2,
[2] bool CS$4$0000)
//Function IL - omitted
} // end of method Test2::Scope
Whenever a C++ variable, allocated on the stack, goes out of scope it gets destructed. Remember that in C++ you can create objects on the stack or on the heap. When you create them on the stack, once execution leaves the scope, they get popped off the stack and gets destroyed.
if (true) {
MyClass stackObj; //created on the stack
MyClass heapObj = new MyClass(); //created on the heap
obj.doSomething();
} //<-- stackObj is destroyed
//heapObj still lives
When C++ objects are created on the heap, they must be explicitly destroyed, otherwise it is a memory leak. No such problem with stack variables though.
In CLR, objects (i.e. reference types) are always created on the managed heap. This is further reinforced by object creation syntax. Consider this code snippet.
MyClass stackObj;
In C++ this would create an instance on MyClass
on the stack and call its default constructor. In C# it would create a reference to class MyClass
that doesn't point to anything. The only way to create an instance of a class is by using new
operator:
MyClass stackObj = new MyClass();
In a way, C# objects are a lot like objects that are created using new
syntax in C++ - they are created on the heap but unlike C++ objects, they are managed by the runtime, so you don't have to worry about destructing them.
Since the objects are always on the heap the fact that object references (i.e. pointers) go out of scope becomes moot. There are more factors involved in determining if an object is to be collected than simply presence of references to the object.
Jon Skeet compared object references in Java to pieces of string that are attached to the balloon, which is the object. Same analogy applies to C# object references. They simply point to a location of the heap that contains the object. Thus, setting it to null has no immediate effect on the object lifetime, the balloon continues to exist, until the GC "pops" it.
Continuing down the balloon analogy, it would seem logical that once the balloon has no strings attached to it, it can be destroyed. In fact this is exactly how reference counted objects work in non-managed languages. Except this approach doesn't work for circular references very well. Imagine two balloons that are attached together by a string but neither balloon has a string to anything else. Under simple ref counting rules, they both continue to exist, even though the whole balloon group is "orphaned".
.NET objects are a lot like helium balloons under a roof. When the roof opens (GC runs) - the unused balloons float away, even though there might be groups of balloons that are tethered together.
.NET GC uses a combination of generational GC and mark and sweep. Generational approach involves the runtime favouring to inspect objects that have been allocated most recently, as they are more likely to be unused and mark and sweep involves runtime going through the whole object graph and working out if there are object groups that are unused. This adequately deals with circular dependency problem.
Also, .NET GC runs on another thread(so called finalizer thread) as it has quite a bit to do and doing that on the main thread would interrupt your program.
The low_memory
option is not properly deprecated, but it should be, since it does not actually do anything differently[source]
The reason you get this low_memory
warning is because guessing dtypes for each column is very memory demanding. Pandas tries to determine what dtype to set by analyzing the data in each column.
Pandas can only determine what dtype a column should have once the whole file is read. This means nothing can really be parsed before the whole file is read unless you risk having to change the dtype of that column when you read the last value.
Consider the example of one file which has a column called user_id. It contains 10 million rows where the user_id is always numbers. Since pandas cannot know it is only numbers, it will probably keep it as the original strings until it has read the whole file.
adding
dtype={'user_id': int}
to the pd.read_csv()
call will make pandas know when it starts reading the file, that this is only integers.
Also worth noting is that if the last line in the file would have "foobar"
written in the user_id
column, the loading would crash if the above dtype was specified.
import pandas as pd
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
csvdata = """user_id,username
1,Alice
3,Bob
foobar,Caesar"""
sio = StringIO(csvdata)
pd.read_csv(sio, dtype={"user_id": int, "username": "string"})
ValueError: invalid literal for long() with base 10: 'foobar'
dtypes are typically a numpy thing, read more about them here: http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html
We have access to numpy dtypes: float, int, bool, timedelta64[ns] and datetime64[ns]. Note that the numpy date/time dtypes are not time zone aware.
Pandas extends this set of dtypes with its own:
'datetime64[ns, ]' Which is a time zone aware timestamp.
'category' which is essentially an enum (strings represented by integer keys to save
'period[]' Not to be confused with a timedelta, these objects are actually anchored to specific time periods
'Sparse', 'Sparse[int]', 'Sparse[float]' is for sparse data or 'Data that has a lot of holes in it' Instead of saving the NaN or None in the dataframe it omits the objects, saving space.
'Interval' is a topic of its own but its main use is for indexing. See more here
'Int8', 'Int16', 'Int32', 'Int64', 'UInt8', 'UInt16', 'UInt32', 'UInt64' are all pandas specific integers that are nullable, unlike the numpy variant.
'string' is a specific dtype for working with string data and gives access to the .str
attribute on the series.
'boolean' is like the numpy 'bool' but it also supports missing data.
Read the complete reference here:
Setting dtype=object
will silence the above warning, but will not make it more memory efficient, only process efficient if anything.
Setting dtype=unicode
will not do anything, since to numpy, a unicode
is represented as object
.
@sparrow correctly points out the usage of converters to avoid pandas blowing up when encountering 'foobar'
in a column specified as int
. I would like to add that converters are really heavy and inefficient to use in pandas and should be used as a last resort. This is because the read_csv process is a single process.
CSV files can be processed line by line and thus can be processed by multiple converters in parallel more efficiently by simply cutting the file into segments and running multiple processes, something that pandas does not support. But this is a different story.
mail can represent quite a couple of programs on a linux system. What you want behind it is either sendmail or postfix. I recommend the latter.
You can install it via your favorite package manager. Then you have to configure it, and once you have done that, you can send email like this:
echo "My message" | mail -s subject [email protected]
See the manual for more information.
As far as configuring postfix goes, there's plenty of articles on the internet on how to do it. Unless you're on a public server with a registered domain, you generally want to forward the email to a SMTP server that you can send email from.
For gmail, for example, follow http://rtcamp.com/tutorials/linux/ubuntu-postfix-gmail-smtp/ or any other similar tutorial.
$dw = date( "w", $timestamp);
Where $dw will be 0 (for Sunday) through 6 (for Saturday) as you can see here: http://www.php.net/manual/en/function.date.php
If you want to specifically animate the background color of an element, I believe you need to include jQueryUI framework. Then you can do:
$('#myElement').animate({backgroundColor: '#FF0000'}, 'slow');
jQueryUI has some built-in effects that may be useful to you as well.
There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
To shorten it up a little:
geocoder = new google.maps.Geocoder();
function codeAddress() {
//In this case it gets the address from an element on the page, but obviously you could just pass it to the method instead
var address = document.getElementById( 'address' ).value;
geocoder.geocode( { 'address' : address }, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
//In this case it creates a marker, but you can get the lat and lng from the location.LatLng
map.setCenter( results[0].geometry.location );
var marker = new google.maps.Marker( {
map : map,
position: results[0].geometry.location
} );
} else {
alert( 'Geocode was not successful for the following reason: ' + status );
}
} );
}
The following script removes quotation marks only from around the column value if table is called [Messages] and the column is called [Description].
-- If the content is in the form of "anything" (LIKE '"%"')
-- Then take the whole text without the first and last characters
-- (from the 2nd character and the LEN([Description]) - 2th character)
UPDATE [Messages]
SET [Description] = SUBSTRING([Description], 2, LEN([Description]) - 2)
WHERE [Description] LIKE '"%"'
You can use \n
for new line and \t
for tabs. Also, extra spaces/tabs are just copied the way you write them in Strings.xml
so just give a couple of spaces where ever you want them.
A better way to reach this would probably be using padding/margin in your view xml and splitting up your long text in different strings in your string.xml
Can I just ask to compare based on the year and month?
You can. Here's a simple example using the AdventureWorks sample database...
DECLARE @Year INT
DECLARE @Month INT
SET @Year = 2002
SET @Month = 6
SELECT
[pch].*
FROM
[Production].[ProductCostHistory] pch
WHERE
YEAR([pch].[ModifiedDate]) = @Year
AND MONTH([pch].[ModifiedDate]) = @Month
There is another way, take this as example
Dim sr As String
sr = "6:10"
Rows(sr).Select
All you need to do is to convert your variables iStartRow
, iEndRow
to a string.
Got it.
sort(mMyClassVector.begin(), mMyClassVector.end(),
[](const MyClass & a, const MyClass & b) -> bool
{
return a.mProperty > b.mProperty;
});
I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.
const url = 'data:image/png;base6....';
fetch(url)
.then(res => res.blob())
.then(blob => {
const file = new File([blob], "File name",{ type: "image/png" })
})
Base64 String -> Blob -> File.
$ ls -l /Library/Java/JavaVirtualMachines/
$ ln -s /Library/Java/JavaVirtualMachines/jdk1.8.0_261.jdk/Contents/Home/bin/javac /usr/local/bin/javac
$ ln -s /Library/Java/JavaVirtualMachines/jdk-11.0.7.jdk/Contents/Home/bin/javac /usr/local/bin/javac
Note that, despite what the message says, it appears that it means that it wants version 1.8, and throws this message if you have a later version.
What follows is my earlier attempts which lead me to the above answer, which then worked ... You might need to do something different depending on what's installed, so maybe these notes might help :
Set it to my jdk1.8 version
$ export PATH=/Library/Java/JavaVirtualMachines/jdk-11.0.7.jdk/Contents/Home/bin/javac:$PATH
Set it to my jdk11 version
$ export PATH=/Library/Java/JavaVirtualMachines/jdk1.8.0_261.jdk/Contents/Home/bin/javac:$PATH
... but actually that doesn't work because /usr/bin/javac
is still what runs first :
$ which javac
/usr/bin/javac
... to see what runs first on the path :
$ cat /etc/paths
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
That means I can override the /usr/bin/javac
... see the commands at the top of the answer ...
The command to set it to jdk1.8 using ln
, at the top of this answer, is what worked for me.
Whilst you certainly can use MySQL's IF()
control flow function as demonstrated by dbemerlin's answer, I suspect it might be a little clearer to the reader (i.e. yourself, and any future developers who might pick up your code in the future) to use a CASE
expression instead:
UPDATE Table
SET A = CASE
WHEN A > 0 AND A < 1 THEN 1
WHEN A > 1 AND A < 2 THEN 2
ELSE A
END
WHERE A IS NOT NULL
Of course, in this specific example it's a little wasteful to set A
to itself in the ELSE
clause—better entirely to filter such conditions from the UPDATE
, via the WHERE
clause:
UPDATE Table
SET A = CASE
WHEN A > 0 AND A < 1 THEN 1
WHEN A > 1 AND A < 2 THEN 2
END
WHERE (A > 0 AND A < 1) OR (A > 1 AND A < 2)
(The inequalities entail A IS NOT NULL
).
Or, if you want the intervals to be closed rather than open (note that this would set values of 0
to 1
—if that is undesirable, one could explicitly filter such cases in the WHERE
clause, or else add a higher precedence WHEN
condition):
UPDATE Table
SET A = CASE
WHEN A BETWEEN 0 AND 1 THEN 1
WHEN A BETWEEN 1 AND 2 THEN 2
END
WHERE A BETWEEN 0 AND 2
Though, as dbmerlin also pointed out, for this specific situation you could consider using CEIL()
instead:
UPDATE Table SET A = CEIL(A) WHERE A BETWEEN 0 AND 2
I quote VonC response, adding something.
Plus, there is Bug 206299 open to request using Ctrl+Tab for switching tabs instead of Ctrl+PgUp(PgDn).
If not satisfied, you can assign yourself the Key Binding, from Window > Preferences > General > Keys.
From the Jenkins wiki:
The JVM launch parameters of these Windows services are controlled by an XML file jenkins.xml and jenkins-slave.xml respectively. These files can be found in $JENKINS_HOME and in the slave root directory respectively, after you've install them as Windows services.
The file format should be self-explanatory. Tweak the arguments for example to give JVM a bigger memory.
https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+as+a+Windows+service
It seems that you want to use step parameter of range function. From documentation:
range(start, stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised). Example:
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) [0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) [0, 3, 6, 9]
>>> range(0, -10, -1) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0) []
>>> range(1, 0) []
In your case to get [0,2,4] you can use:
range(0,6,2)
OR in your case when is a var:
idx = None
for i in range(len(str1)):
if idx and i < idx:
continue
for j in range(len(str2)):
if str1[i+j] != str2[j]:
break
else:
idx = i+j
I've had the same error as you have and it turned out that there was nothing wrong with the code. The problem was that the webserver was sending the wrong Content-Type header.
Try wireshark or something similar to see what content-type the webserver is sending.
The solution to delete an Account/Property/View is still very similar to @Pranav ?'s answer. Google has just moved a few things around, so I thought I would update.
Click Admin Tab at the top of the page
Once you are on the Admin Page, You need to decide if you want to delete the Account, Property, or View. Make sure to select the desired Account, Property, or View from the Drop Down Menu.
In the following pictures, I will show you how to delete the Account, which removes all information including Properties and Views under that particular account.
Click Account Settings to remove Account, Property Settings to remove Property, and View Settings to remove View.
On Account Settings, you will notice a button 'Move to Trash Can'. You will click this to remove the Account, Property or View. You will have to verify Moving the Account to the Trash Can on the next page/picture.
When you have verified this is the account you want to delete, go ahead and select 'Trash Account'.
Note: When you Trash an Account it moves all the information to Admin/Account/Trash Can, where it can be recovered within 1 month. Keep in mind that every Account has its own Trash Can. Once that time has lapsed the Account, Property or View will be deleted FOREVER!
Hope this helps someone in the future, since I just struggled trying to figure it out even though its pretty simple now.
Just add the directory on the command line:
svn checkout svn://192.168.1.1/projectname/ target-directory/
SELECT name, GROUP_CONCAT( section )
FROM `tmp`
GROUP BY name
Png files can handle transparency.
So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png
file.
And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?
If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.
@Bean
public RestTemplate restTemplate()
throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
return restTemplate;
}
setRetaininstance
is only useful when your activity
is destroyed and recreated due to a configuration change because the instances are saved during a call to onRetainNonConfigurationInstance
. That is, if you rotate the device, the retained fragments will remain there(they're not destroyed and recreated.) but when the runtime kills the activity to reclaim resources, nothing is left. When you press back button and exit the activity, everything is destroyed.
Usually I use this function to saved orientation changing Time.Say I have download a bunch of Bitmaps from server and each one is 1MB, when the user accidentally rotate his device, I certainly don't want to do all the download work again.So I create a Fragment
holding my bitmaps and add it to the manager and call setRetainInstance
,all the Bitmaps are still there even if the screen orientation changes.
The DragListView lib does this really neat with very nice support for custom animations such as elevation animations. It is also still maintained and updated on a regular basis.
Here is how you use it:
1: Add the lib to gradle first
dependencies {
compile 'com.github.woxthebox:draglistview:1.2.1'
}
2: Add list from xml
<com.woxthebox.draglistview.DragListView
android:id="@+id/draglistview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
3: Set the drag listener
mDragListView.setDragListListener(new DragListView.DragListListener() {
@Override
public void onItemDragStarted(int position) {
}
@Override
public void onItemDragEnded(int fromPosition, int toPosition) {
}
});
4: Create an adapter overridden from DragItemAdapter
public class ItemAdapter extends DragItemAdapter<Pair<Long, String>, ItemAdapter.ViewHolder>
public ItemAdapter(ArrayList<Pair<Long, String>> list, int layoutId, int grabHandleId, boolean dragOnLongPress) {
super(dragOnLongPress);
mLayoutId = layoutId;
mGrabHandleId = grabHandleId;
setHasStableIds(true);
setItemList(list);
}
5: Implement a viewholder that extends from DragItemAdapter.ViewHolder
public class ViewHolder extends DragItemAdapter.ViewHolder {
public TextView mText;
public ViewHolder(final View itemView) {
super(itemView, mGrabHandleId);
mText = (TextView) itemView.findViewById(R.id.text);
}
@Override
public void onItemClicked(View view) {
}
@Override
public boolean onItemLongClicked(View view) {
return true;
}
}
For more detailed info go to https://github.com/woxblom/DragListView
If you only need to test a delay you can use this:
function delay(ms) {
ms += new Date().getTime();
while (new Date() < ms){}
}
And then if you want to delay for 2 second you do:
delay(2000);
Might not be the best for production though. More on that in the comments
clone: copying the remote server repository to your local machine.
pull: get new changes other have added to your local machine.
This is the difference.
Clone is generally used to get remote repo copy.
Pull is used to view other team mates added code, if you are working in teams.
The summary at Wikipedia (Software Framework) (first google hit btw) explains it quite well:
A software framework, in computer programming, is an abstraction in which common code providing generic functionality can be selectively overridden or specialized by user code providing specific functionality. Frameworks are a special case of software libraries in that they are reusable abstractions of code wrapped in a well-defined Application programming interface (API), yet they contain some key distinguishing features that separate them from normal libraries.
Software frameworks have these distinguishing features that separate them from libraries or normal user applications:
- inversion of control - In a framework, unlike in libraries or normal user applications, the overall program's flow of control is not dictated by the caller, but by the framework.[1]
- default behavior - A framework has a default behavior. This default behavior must actually be some useful behavior and not a series of no-ops.
- extensibility - A framework can be extended by the user usually by selective overriding or specialized by user code providing specific functionality.
- non-modifiable framework code - The framework code, in general, is not allowed to be modified. Users can extend the framework, but not modify its code.
You may "need" it because it may provide you with a great shortcut when developing applications, since it contains lots of already written and tested functionality. The reason is quite similar to the reason we use software libraries.
Its like a pipeline connecting
From---->To
In between u can add as many channels and pipes. The faucet can be of any type automatic or manual for flow of data and a route to channelize the flow.
It supports and have implementation for all types and kinds of processing. And for same processing many approaches because it has many components and each component can also provide the desired output using different methods under it.
For instance, File transfer can be done in camel with types file moved or copied and also from folder, server or queue.
-from-->To
- from-->process-->to
- from-->bean-->to
- from-->process-->bean-->to
-from-->marshal-->process-->unmarshal-->to
From/to----folder, direct, seda, vm can be anything
I think you need to include only these options in build.gradle:
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
}
p.s same answer from my post in : Error :: duplicate files during packaging of APK
I think this is what you are looking for
<?php include ('Scripts/Php/connection.php');
//The connection.php script is executed inside the current file ?>
The script file can also be in a .txt format, it should still work, it does for me
e.g.
<?php include ('Scripts/Php/connection.txt');
//The connection.txt script is executed inside the current file ?>
It seems that when this error appears it is an indication that the selenium-java plugin for maven is out-of-date.
Changing the version in the pom.xml should fix the problem
Atomic property can be accessed by only one thread at a time. It is thread safe. Default is atomic .Please note that there is no keyword atomic
Nonatomic means multiple thread can access the item .It is thread unsafe
So one should be very careful while using atomic .As it affect the performance of your code
set PATH=c:\Program Files\Java\jdk1.6.0_45\bin;%PATH%
this will work if you are working on command prompt
How to total up used memory by process name:
Sometimes even looking at the biggest single processes there is still a lot of used memory unaccounted for. To check if there are a lot of the same smaller processes using the memory you can use a command like the following which uses awk to sum up the total memory used by processes of the same name:
ps -e -orss=,args= |awk '{print $1 " " $2 }'| awk '{tot[$2]+=$1;count[$2]++} END {for (i in tot) {print tot[i],i,count[i]}}' | sort -n
e.g. output
9344 docker 1
9948 nginx: 4
22500 /usr/sbin/NetworkManager 1
24704 sleep 69
26436 /usr/sbin/sshd 15
34828 -bash 19
39268 sshd: 10
58384 /bin/su 28
59876 /bin/ksh 29
73408 /usr/bin/python 2
78176 /usr/bin/dockerd 1
134396 /bin/sh 84
5407132 bin/naughty_small_proc 1432
28061916 /usr/local/jdk/bin/java 7
Try this:- SELECT Case WHEN COLUMNNAME=0 THEN 'sex'
ELSE WHEN COLUMNNAME=1 THEN 'Female' END AS YOURGRIDCOLUMNNAME FROM YOURTABLENAME
in your query for only true or false column
If you don't like break
s and goto
s, you can use a "traditional" for loop instead the for-in, with an extra abort condition:
int a, b;
bool abort = false;
for (a = 0; a < 10 && !abort; a++) {
for (b = 0; b < 10 && !abort; b++) {
if (condition) {
doSomeThing();
abort = true;
}
}
}
Only use WOFF2, or if you need legacy support, WOFF. Do not use any other format
(svg
and eot
are dead formats, ttf
and otf
are full system fonts, and should not be used for web purposes)
In short, font-face is very old, but only recently has been supported by more than IE.
eot
is needed for Internet Explorers that are older than IE9 - they invented the spec, but eot was a proprietary solution.
ttf
and otf
are normal old fonts, so some people got annoyed that this meant anyone could download expensive-to-license fonts for free.
Time passes, SVG 1.1 adds a "fonts" chapter that explains how to model a font purely using SVG markup, and people start to use it. More time passes and it turns out that they are absolutely terrible compared to just a normal font format, and SVG 2 wisely removes the entire chapter again.
Then, woff
gets invented by people with quite a bit of domain knowledge, which makes it possible to host fonts in a way that throws away bits that are critically important for system installation, but irrelevant for the web (making people worried about piracy happy) and allows for internal compression to better suit the needs of the web (making users and hosts happy). This becomes the preferred format.
2019 edit A few years later, woff2
gets drafted and accepted, which improves the compression, leading to even smaller files, along with the ability to load a single font "in parts" so that a font that supports 20 scripts can be stored as "chunks" on disk instead, with browsers automatically able to load the font "in parts" as needed, rather than needing to transfer the entire font up front, further improving the typesetting experience.
If you don't want to support IE 8 and lower, and iOS 4 and lower, and android 4.3 or earlier, then you can just use WOFF (and WOFF2, a more highly compressed WOFF, for the newest browsers that support it.)
@font-face {
font-family: 'MyWebFont';
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff');
}
Support for woff
can be checked at http://caniuse.com/woff
Support for woff2
can be checked at http://caniuse.com/woff2
If you have pushed the commit to remote and then erroneously amended changes to that commit this will fix your problem. Issue a git log
to find the SHA before the commit. (this assumes remote is named origin). Now issue these command using that SHA.
git reset --soft <SHA BEFORE THE AMMEND>
#you now see all the changes in the commit and the amend undone
#save ALL the changes to the stash
git stash
git pull origin <your-branch> --ff-only
#if you issue git log you can see that you have the commit you didn't want to amend
git stash pop
#git status reveals only the changes you incorrectly amended
#now you can create your new unamended commit
another solution is catching onClick event and for aggregate data to js function you can
.hmtl.erb
<%= link_to "Action", 'javascript:;', class: 'my-class', data: { 'array' => %w(foo bar) } %>
.js
// handle my-class click
$('a.my-class').on('click', function () {
var link = $(this);
var array = link.data('array');
});
This is what I do for those situations:
I don't start the html element with class 'hide', but I put style="display: none".
This is because bootstrap jquery modifies the style attribute and not the classes to hide/unhide.
Example:
<button type="button" id="btn_cancel" class="btn default" style="display: none">Cancel</button>
or
<button type="button" id="btn_cancel" class="btn default display-hide">Cancel</button>
Later on, you can run all the following that will work:
$('#btn_cancel').toggle() // toggle between hide/unhide
$('#btn_cancel').hide()
$('#btn_cancel').show()
You can also uso the class of Twitter Bootstrap 'display-hide', which also works with the jQuery IU .toggle() method.
Close() - managed resource can be temporarily closed and can be opened once again.
Dispose() - permanently removes managed or not managed resource
Using javascript function it is easier to get all the attributes of an element in NamedArrayFormat.
$("#myTestDiv").click(function(){_x000D_
var attrs = document.getElementById("myTestDiv").attributes;_x000D_
$.each(attrs,function(i,elem){_x000D_
$("#attrs").html( $("#attrs").html()+"<br><b>"+elem.name+"</b>:<i>"+elem.value+"</i>");_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>_x000D_
<div id="myTestDiv" ekind="div" etype="text" name="stack">_x000D_
click This_x000D_
</div>_x000D_
<div id="attrs">Attributes are <div>
_x000D_
Try the cex
argument:
?par
cex
It sort of depends on what you mean by "convert".
If you have a series of characters that represents an integer, like "123456", then there are two typical ways to do that in C: Use a special-purpose conversion like atoi() or strtol(), or the general-purpose sscanf(). C++ (which is really a different language masquerading as an upgrade) adds a third, stringstreams.
If you mean you want the exact bit pattern in one of your int
variables to be treated as a char
, that's easier. In C the different integer types are really more of a state of mind than actual separate "types". Just start using it where char
s are asked for, and you should be OK. You might need an explicit conversion to make the compiler quit whining on occasion, but all that should do is drop any extra bits past 256.
It's a bug in Managed ODP.net - 'Bug 21113901 : MANAGED ODP.NET RAISE ORA-1008 USING SINGLE QUOTED CONST + BIND VAR IN SELECT' fixed in patch 23530387 superseded by patch 24591642
Untested / could be better:
<form action="page-you're-submitting-to.html" method="POST">
<a href="#" onclick="document.forms[0].submit();return false;"><img src="whatever.jpg" /></a>
</form>
MailSystem.NET contains all your need for IMAP4. It's free & open source.
(I'm involved in the project)
The download from java.com
which installs in /Library/Internet Plug-Ins
is only the JRE, for development you probably want to download the JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install that instead. This will install the JDK at /Library/Java/JavaVirtualMachines/jdk1.7.0_<something>.jdk/Contents/Home
which you can then add to Eclipse via Preferences -> Java -> Installed JREs.
There is an open source common resource grep tool crgrep which searches within PDF files but also other resources like content nested in archives, database tables, image meta-data, POM file dependencies and web resources - and combinations of these including recursive search.
The full description under the Files tab pretty much covers what the tool supports.
I developed crgrep as an opensource tool.
i used this, and it worked:
var cleanText = text.replace(/&nbsp;/g,"");
If you set the trunc flag.
#include<fstream>
using namespace std;
fstream ofs;
int main(){
ofs.open("test.txt", ios::out | ios::trunc);
ofs<<"Your content here";
ofs.close(); //Using microsoft incremental linker version 14
}
I tested this thouroughly for my own needs in a common programming situation I had. Definitely be sure to preform the ".close();" operation. If you don't do this there is no telling whether or not you you trunc or just app to the begging of the file. Depending on the file type you might just append over the file which depending on your needs may not fullfill its purpose. Be sure to call ".close();" explicity on the fstream you are trying to replace.
is
and ==
?==
and is
are different comparison! As others already said:
==
compares the values of the objects.is
compares the references of the objects.In Python names refer to objects, for example in this case value1
and value2
refer to an int
instance storing the value 1000
:
value1 = 1000
value2 = value1
Because value2
refers to the same object is
and ==
will give True
:
>>> value1 == value2
True
>>> value1 is value2
True
In the following example the names value1
and value2
refer to different int
instances, even if both store the same integer:
>>> value1 = 1000
>>> value2 = 1000
Because the same value (integer) is stored ==
will be True
, that's why it's often called "value comparison". However is
will return False
because these are different objects:
>>> value1 == value2
True
>>> value1 is value2
False
Generally is
is a much faster comparison. That's why CPython caches (or maybe reuses would be the better term) certain objects like small integers, some strings, etc. But this should be treated as implementation detail that could (even if unlikely) change at any point without warning.
You should only use is
if you:
want to check if two objects are really the same object (not just the same "value"). One example can be if you use a singleton object as constant.
want to compare a value to a Python constant. The constants in Python are:
None
True
1False
1NotImplemented
Ellipsis
__debug__
int is int
or int is float
)np.ma.masked
from the NumPy module)In every other case you should use ==
to check for equality.
There is some aspect to ==
that hasn't been mentioned already in the other answers: It's part of Pythons "Data model". That means its behavior can be customized using the __eq__
method. For example:
class MyClass(object):
def __init__(self, val):
self._value = val
def __eq__(self, other):
print('__eq__ method called')
try:
return self._value == other._value
except AttributeError:
raise TypeError('Cannot compare {0} to objects of type {1}'
.format(type(self), type(other)))
This is just an artificial example to illustrate that the method is really called:
>>> MyClass(10) == MyClass(10)
__eq__ method called
True
Note that by default (if no other implementation of __eq__
can be found in the class or the superclasses) __eq__
uses is
:
class AClass(object):
def __init__(self, value):
self._value = value
>>> a = AClass(10)
>>> b = AClass(10)
>>> a == b
False
>>> a == a
So it's actually important to implement __eq__
if you want "more" than just reference-comparison for custom classes!
On the other hand you cannot customize is
checks. It will always compare just if you have the same reference.
Because __eq__
can be re-implemented or overridden, it's not limited to return True
or False
. It could return anything (but in most cases it should return a boolean!).
For example with NumPy arrays the ==
will return an array:
>>> import numpy as np
>>> np.arange(10) == 2
array([False, False, True, False, False, False, False, False, False, False], dtype=bool)
But is
checks will always return True
or False
!
1 As Aaron Hall mentioned in the comments:
Generally you shouldn't do any is True
or is False
checks because one normally uses these "checks" in a context that implicitly converts the condition to a boolean (for example in an if
statement). So doing the is True
comparison and the implicit boolean cast is doing more work than just doing the boolean cast - and you limit yourself to booleans (which isn't considered pythonic).
Like PEP8 mentions:
Don't compare boolean values to
True
orFalse
using==
.Yes: if greeting: No: if greeting == True: Worse: if greeting is True:
You can even use a version range with pip install
command. Something like this:
pip install 'stevedore>=1.3.0,<1.4.0'
And if the package is already installed and you want to downgrade it add --force-reinstall
like this:
pip install 'stevedore>=1.3.0,<1.4.0' --force-reinstall
I would suspect that there can be as many as 2**32 -1
numbered match variables, on a 32-bit compiled Perl binary.
As the files in .gitignore are not being tracked, you can use the git clean command to recursively remove files that are not under version control.
Use git clean -xdn
to perform a dry run and see what will be removed.
Then use git clean -xdf
to execute it.
Basically, git clean -h
or man git-clean
(in unix) will give you help.
Be aware that this command will also remove new files that are not in the staging area.
Hope it helps.
Assuming you want to check that all characters in the string are digits, you could use the Enumerable.All Extension Method with the Char.IsDigit Method as follows:
bool allCharactersInStringAreDigits = myStringVariable.All(char.IsDigit);
This solution with few code. I think is better.
<?php echo wp_get_attachment_image( get_term_meta( get_queried_object_id(), 'thumbnail_id', 1 ), 'thumbnail' ); ?>
Restart the computer after has added new value to PATH.
I experienced a similar problem after some updates released from Microsoft (part of them where about .NET framework 4.5).
On the Internet I got the following link to the Microsoft knowledge base article:
Update for Microsoft Visual Studio 2012 (KB2781514)
It worked for me.
This query here will list the total size that a table takes up - clustered index, heap and all nonclustered indices:
SELECT
s.Name AS SchemaName,
t.NAME AS TableName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM
sys.tables t
INNER JOIN
sys.schemas s ON s.schema_id = t.schema_id
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
WHERE
t.NAME NOT LIKE 'dt%' -- filter out system tables for diagramming
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
s.Name, t.Name
If you want to separate table space from index space, you need to use AND i.index_id IN (0,1)
for the table space (index_id = 0
is the heap space, index_id = 1
is the size of the clustered index = data pages) and AND i.index_id > 1
for the index-only space
All other answers, and mainly about list comprehension, are great. But just to explain your error:
strip_list = []
for lengths in range(1,20):
strip_list.append(0) #longest word in the text file is 20 characters long
for a in lines:
strip_list.append(lines[a].strip())
a
is a member of your list, not an index. What you could write is this:
[...]
for a in lines:
strip_list.append(a.strip())
Another important comment: you can create an empty list this way:
strip_list = [0] * 20
But this is not so useful, as .append
appends stuff to your list. In your case, it's not useful to create a list with defaut values, as you'll build it item per item when appending stripped strings.
So your code should be like:
strip_list = []
for a in lines:
strip_list.append(a.strip())
But, for sure, the best one is this one, as this is exactly the same thing:
stripped = [line.strip() for line in lines]
In case you have something more complicated than just a .strip
, put this in a function, and do the same. That's the most readable way to work with lists.
Templates:
Pass function name and argument.
<a href="{{ url_for('get_blog_post',id = blog.id)}}">{{blog.title}}</a>
View,function
@app.route('/blog/post/<string:id>',methods=['GET'])
def get_blog_post(id):
return id
You're comparing apples to oranges here:
webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service
basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.
So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).
Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:
basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security
wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network
For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding
This will list Everything (including sub directories) from the directory you specify, in order, and with the attributes. I have spent days looking for something to do this, and I took parts from this entire discussion, and a little of my own, and put it together. ENJOY!!
#!/usr/bin/perl --
print qq~Content-type: text/html\n\n~;
print qq~<font face="arial" size="2">~;
use File::Find;
# find( \&wanted_tom, '/home/thomas/public_html'); # if you want just one website, uncomment this, and comment out the next line
find( \&wanted_tom, '/home');
exit;
sub wanted_tom {
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat ($_);
$mode = (stat($_))[2];
$mode = substr(sprintf("%03lo", $mode), -3);
if (-d $File::Find::name) {
print "<br><b>--DIR $File::Find::name --ATTR:$mode</b><br>";
} else {
print "$File::Find::name --ATTR:$mode<br>";
}
return;
}
I have had major issues with ajax + jQuery v3 getting both the response status code and data from JSON APIs. jQuery.ajax only decodes JSON data if the status is a successful one, and it also swaps around the ordering of the callback parameters depending on the status code. Ugghhh.
The best way to combat this is to call the .always
chain method and do a bit of cleaning up. Here is my code.
$.ajax({
...
}).always(function(data, textStatus, xhr) {
var responseCode = null;
if (textStatus === "error") {
// data variable is actually xhr
responseCode = data.status;
if (data.responseText) {
try {
data = JSON.parse(data.responseText);
} catch (e) {
// Ignore
}
}
} else {
responseCode = xhr.status;
}
console.log("Response code", responseCode);
console.log("JSON Data", data);
});
@SpringBootApplication @ComponentScan(basePackages = {"io.testapi"})
In the main class below springbootapplication annotation i have written componentscan and it worked for me.
public static bool RegistryValueExists(string hive_HKLM_or_HKCU, string registryRoot, string valueName)
{
RegistryKey root;
switch (hive_HKLM_or_HKCU.ToUpper())
{
case "HKLM":
root = Registry.LocalMachine.OpenSubKey(registryRoot, false);
break;
case "HKCU":
root = Registry.CurrentUser.OpenSubKey(registryRoot, false);
break;
default:
throw new System.InvalidOperationException("parameter registryRoot must be either \"HKLM\" or \"HKCU\"");
}
return root.GetValue(valueName) != null;
}
Just add throw
where needed, and try
block to the caller that handles the error. By convention you should only throw things that derive from std::exception
, so include <stdexcept>
first.
int compare(int a, int b) {
if (a < 0 || b < 0) {
throw std::invalid_argument("a or b negative");
}
}
void foo() {
try {
compare(-1, 0);
} catch (const std::invalid_argument& e) {
// ...
}
}
Also, look into Boost.Exception.
You have to wrap the entire url
statement in the bypassSecurityTrustStyle
:
<div class="header" *ngIf="image" [style.background-image]="image"></div>
And have
this.image = this.sanitization.bypassSecurityTrustStyle(`url(${element.image})`);
Otherwise it is not seen as a valid style property
for property, value in vars(theObject).items():
print(property, ":", value)
Be aware that in some rare cases there's a __slots__
property, such classes often have no __dict__
.
You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do
for (var i = myArray.length - 1; i >= 0; i--) { console.log(eval(myArray[i])); };
More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.
var result = {}; for (var i = myArray.length - 1; i >= 0; i--) { result[myArray[i]] = eval(myArray[i]); };
I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via
window['myVarName'] = 'namingCollisionsAreFun';
(per comment)
The df.plot()
function returns a matplotlib.axes.AxesSubplot
object. You can set the labels on that object.
ax = df2.plot(lw=2, colormap='jet', marker='.', markersize=10, title='Video streaming dropout by category')
ax.set_xlabel("x label")
ax.set_ylabel("y label")
Or, more succinctly: ax.set(xlabel="x label", ylabel="y label")
.
Alternatively, the index x-axis label is automatically set to the Index name, if it has one. so df2.index.name = 'x label'
would work too.
It'll have the same behavior as the underlying recv libc call see the man page for an official description of behavior (or read a more general description of the sockets api).
You can Change the speed by adding scrolldelay
<marquee style="font-family: lato; color: #FFFFFF" bgcolor="#00224f" scrolldelay="400">Now the Speed is Delay to 400 Milliseconds</marquee>
_x000D_
<a href="javascript:void(0)" class="aaf" id="users_id">add as a friend</a>
on jquery
$('.aaf').on("click",function(){
var usersid = $(this).attr("id");
//post code
})
//other method is to use the data attribute
<a href="javascript:void(0)" class="aaf" data-id="102" data-username="sample_username">add as a friend</a>
on jquery
$('.aaf').on("click",function(){
var usersid = $(this).data("id");
var username = $(this).data("username");
})
Wrap your column in this code.
ISNULL(Yourcolumn, 0)
Maybe check why you are getting nulls
Short version of (correct) tzaman answer will be (for fresh SVN)
svn switch ^/branches/v1p2p3
--relocate
switch is deprecated anyway, when it needed you'll have to use svn relocate
command
Instead of creating snapshot-branch (ReadOnly) you can use tags (conventional RO labels for history)
On Windows, the caret character (^
) must be escaped:
svn switch ^^/branches/v1p2p3
I think it's worth noting that all the style and CSS based solutions don't work when a page is running in compatibility mode. The compatibility mode renderer ignores the ::-ms-clear element, even though the browser shows the x.
If your page needs to run in compatibility mode, you may be stuck with the X showing.
In my case, I am working with some third party data bound controls, and our solution was to handle the "onchange" event and clear the backing store if the field is cleared with the x button.
For a somewhat more concise solution, consider the following:
def split_path(p):
a,b = os.path.split(p)
return (split_path(a) if len(a) and len(b) else []) + [b]
Before I go on, I have the latest version (v5.0.15) of OS X Server (yes, horrible, I know...however, the web server seems to work A-OK). I searched high and low for days trying to update (or at least get Apache to point to) a new version of PHP. My mcrypt
did not work, along with other extensions and I installed and reinstalled PHP countless times from http://php-osx.liip.ch/ and other tutorials until I finally noticed a tid-bit of information written in a comment in one of the many different .conf
files OS X Server keeps which was that OS X Server loads it's own custom .conf
file before it loads the Apache httpd.conf
(located at /etc/apache2/httpd.conf
). The server file is located:
/Library/Server/Web/Config/apache2/httpd_server_app.conf
When you open this file, you have to comment out this line like so:
#LoadModule php5_module libexec/apache2/libphp5.so
Then add in the correct path (which should already be installed if you have installed via the http://php-osx.liip.ch/ link):
LoadModule php5_module /usr/local/php5/libphp5.so
After this modification, my PHP finally loaded the correct PHP installation. That being said, if things go wonky, it may be because OS X is made to work off the native installation of PHP at the time of OS X installation. To revert, just undo the change above.
Anyway, hopefully this is helpful for anyone else spending countless hours on this.
You can try this command,
adb shell dumpsys activity recents
There you can find current activity name in activity stack.
To get most recent activity name:
adb shell dumpsys activity recents | find "Recent #0"
Yes. You can pass the numerical values to the constructor for the enum, like so:
enum Ids {
OPEN(100),
CLOSE(200);
private int value;
private Ids(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
See the Sun Java Language Guide for more information.
Try PHPMyAdmin which has some really nice visualisation and editing feature. I am pretty sure you can even export to exel from it.
The simplest way to insert a new line between echo
statements is to insert an echo
without arguments, for example:
echo Create the snapshots
echo
echo Snapshot created
That is, echo
without any arguments will print a blank line.
Another alternative to use a single echo
statement with the -e
flag and embedded newline characters \n
:
echo -e "Create the snapshots\n\nSnapshot created"
However, this is not portable, as the -e
flag doesn't work consistently in all systems. A better way if you really want to do this is using printf
:
printf "Create the snapshots\n\nSnapshot created\n"
This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \n
at the end, as printf
doesn't append a newline automatically as echo
does.
Alternatively, not to think about a newline or space somewhere in the file, you can buffer the output. Basically, you call ob_start()
at the very beginning of the file and ob_end_flush()
at the end. You can find more details at php.net ob-start function description.
Edit: If you use buffering, you can output HTML before and after header() function - buffering will then ignore the output and return only the redirection header.
I had same as issue. I use Git Totoise. Just Right Click ->TotoiseGit -> Clean Up . Now you can push to Github It worked fine with me :D