As you run the container, a directory on your host is created and mounted into the container. You can find out what directory this is with
$ docker inspect --format "{{ .Volumes }}" <ID>
map[/export:/var/lib/docker/vfs/dir/<VOLUME ID...>]
If you want to mount a directory from your host inside your container, you have to use the -v
parameter and specify the directory. In your case this would be:
docker run -v /export:/export data
SO you would use the hosts folder inside your container.
This should work:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Pinger {
private static String keyWordTolookFor = "average";
public Pinger() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
//Test the ping method on Windows.
System.out.println(ping("192.168.0.1")); }
public String ping(String IP) {
try {
String line;
Process p = Runtime.getRuntime().exec("ping -n 1 " + IP);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while (((line = input.readLine()) != null)) {
if (line.toLowerCase().indexOf(keyWordTolookFor.toLowerCase()) != -1) {
String delims = "[ ]+";
String[] tokens = line.split(delims);
return tokens[tokens.length - 1];
}
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
return "Offline";
}
}
Include the port number with the IP address.
For example:
http://19.18.20.101:5566
where 5566 is the port number.
Your primary question has been answered above. I just wanted to point out that the regex you're using has a bug. It will also succeed on foo-domain.com
which is not a subdomain of domain.com
What you really want is this:
/(^|\.)domain\.com$/
In the component where you need to access the parameters you can use
this.props.location.state.from.search
which will reveal the whole query string (everything after the ?
sign)
You can use Bootstrap 3.3.7. Update your CDN links to this
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
What you return from a program is just a convention.
No, I can't think of any circumstances where "EXIT_SUCCESS" wouldn't be "0".
Personally, I'd recommend "0".
IMHO...
Do you have access to a PC with Windows 7, or a PC with the SDK already installed?
If so, the easiest solution is to copy the C:\Program Files\Microsoft SDKs\Windows\v7.1
folder from the Windows 7 machine to the Windows 8 machine.
After searching a lot I found a solution:
Go to Build-> Build Apk(s).
After creating apk you will see a dialog as below.
Click on locate and install it in your phone
Enjoy
Another option is the Objects.equals
utility method.
Objects.equals( thisEnum , thatEnum )
Objects.equals
for null-safetyequals operator == instead of .equals()
Which operator is the one I should be using?
A third option is the static equals
method found on the Objects
utility class added to Java 7 and later.
Here’s an example using the Month
enum.
boolean areEqual = Objects.equals( Month.FEBRUARY , Month.JUNE ) ; // Returns `false`.
I find a couple benefits to this method:
true
false
NullPointerException
What is the logic used by Objects.equals
?
See for yourself, from the Java 10 source code of OpenJDK:
return (a == b) || (a != null && a.equals(b));
this could happen if you are trying to use your public key to create certificate instead of your private key. you should use private key
Convert them into Bitmaps and then either store them in a Collection(HashMap,List etc.) or you can write them on the SDcard.
When storing them in application space using the first approach, you might want to wrap them around a java.lang.ref.SoftReference specifically if their numbers is large (so that they are garbage collected during crisis). This could ensue a Reload though.
HashMap<String,SoftReference<Bitmap>> imageCache =
new HashMap<String,SoftReference<Bitmap>>();
writing them on SDcard will not require a Reload; just a user-permission.
@johnstock, we can also use JavaScript's prototyping concept to add method to objects to delete any passed key available in calling object.
Above answers are appreciated.
var myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
// 1st and direct way
delete myObject.regex; // delete myObject["regex"]
console.log(myObject); // { ircEvent: 'PRIVMSG', method: 'newURI' }
// 2 way - by using the concept of JavaScript's prototyping concept
Object.prototype.removeFromObjectByKey = function(key) {
// If key exists, remove it and return true
if (this[key] !== undefined) {
delete this[key]
return true;
}
// Else return false
return false;
}
var isRemoved = myObject.removeFromObjectByKey('method')
console.log(myObject) // { ircEvent: 'PRIVMSG' }
// More examples
var obj = {
a: 45,
b: 56,
c: 67
}
console.log(obj) // { a: 45, b: 56, c: 67 }
// Remove key 'a' from obj
isRemoved = obj.removeFromObjectByKey('a')
console.log(isRemoved); //true
console.log(obj); // { b: 56, c: 67 }
// Remove key 'd' from obj which doesn't exist
var isRemoved = obj.removeFromObjectByKey('d')
console.log(isRemoved); // false
console.log(obj); // { b: 56, c: 67 }
_x000D_
Old question but nowadays CSS3 makes vertical alignment really simple!
Just add to the <div>
this css:
display:flex;
align-items:center;
justify-content:center;
Live Example:
.img_thumb {_x000D_
float: left;_x000D_
height: 120px;_x000D_
margin-bottom: 5px;_x000D_
margin-left: 9px;_x000D_
position: relative;_x000D_
width: 147px;_x000D_
background-color: rgba(0, 0, 0, 0.5);_x000D_
border-radius: 3px;_x000D_
display:flex;_x000D_
align-items:center;_x000D_
justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
<a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
<img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
</a>_x000D_
</div>
_x000D_
You're not parsing a string, you're parsing an already-parsed object :)
var obj1 = JSON.parse('{"creditBalance":0,...,"starStatus":false}');
// ^ ^
// if you want to parse, the input should be a string
var obj2 = {"creditBalance":0,...,"starStatus":false};
// or just use it directly.
You can use this commands:
docker exec -it yournamecontainer psql -U postgres -c "CREATE DATABASE mydatabase ENCODING 'LATIN1' TEMPLATE template0 LC_COLLATE 'C' LC_CTYPE 'C';"
docker exec -it yournamecontainer psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE postgres TO postgres;"
From v0.11+, ... use df.iloc
.
In [7]: df.iloc[:,0]
Out[7]:
0 1
1 2
2 3
3 4
Name: x, dtype: int64
// this will give all the forms on the page.
$('form')
// If you know the name of form then.
$('form[name="myFormName"]')
// If you don't know know the name but the position (starts with 0)
$('form:eq(1)') // 2nd form will be fetched.
Eclipse is launching your application with whatever JRE you defined in your launch configuration. Since you're running the 32-bit Eclipse, you're running/debugging against its 32-bit SWT libraries, and you'll need to run a 32-bit JRE.
Your 64-bit JRE is, for whatever reason, your default Installed JRE.
To change this, first make sure you have a 32-bit JRE configured in the Installed JREs preference. Go to Window -> Preferences and navigate to Java -> Installed JREs:
You can click Add and navigate to your 32-bit JVM's JAVA_HOME
to add it.
Then in your Run Configuration, find your Eclipse Application and make sure the Runtime JRE is set to the 32-bit JRE you just configured:
(Note the combobox that is poorly highlighted.)
Don't try replacing SWT jars, that will likely end poorly.
The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.
You can change the level to OFF which should get rid of all logging. According to the log4j website, valid levels in order of importance are TRACE, DEBUG, INFO, WARN, ERROR, FATAL. There is one undocumented level called OFF which is a higher level than FATAL, and turns off all logging.
You can also create an extra root logger to log nothing (level OFF), so that you can switch root loggers easily. Here's a post to get you started on that.
You might also want to read the Log4J FAQ, because I think turning off all logging may not help. It will certainly not speed up your app that much, because logging code is executed anyway, up to the point where log4j decides that it doesn't need to log this entry.
User.hasMany(Post, {foreignKey: 'user_id'})
Post.belongsTo(User, {foreignKey: 'user_id'})
Post.find({ where: { ...}, include: [User]})
Which will give you
SELECT
`posts`.*,
`users`.`username` AS `users.username`, `users`.`email` AS `users.email`,
`users`.`password` AS `users.password`, `users`.`sex` AS `users.sex`,
`users`.`day_birth` AS `users.day_birth`,
`users`.`month_birth` AS `users.month_birth`,
`users`.`year_birth` AS `users.year_birth`, `users`.`id` AS `users.id`,
`users`.`createdAt` AS `users.createdAt`,
`users`.`updatedAt` AS `users.updatedAt`
FROM `posts`
LEFT OUTER JOIN `users` AS `users` ON `users`.`id` = `posts`.`user_id`;
The query above might look a bit complicated compared to what you posted, but what it does is basically just aliasing all columns of the users table to make sure they are placed into the correct model when returned and not mixed up with the posts model
Other than that you'll notice that it does a JOIN instead of selecting from two tables, but the result should be the same
Further reading:
Save the file in the editor. If it's Emacs: CTRLX CTRLS to save then CTRLX CTRLC to quit or if it's vi: :wq
Press esc
first to get out from editing. (in windows/vi)
# Hide grid lines
ax.grid(False)
# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
Note, you need matplotlib>=1.2 for set_zticks()
to work.
Just another thing... Instead of System.out.println("Error Message Here")
, use System.err.println("Error Message Here")
. This will allow you to distinguish the differences between errors and normal code functioning by displaying the errors(i.e. everything inside System.err.println()
) in red.
NOTE: It also works when used with System.err.print("Error Message Here")
Try converting your procedure in to an Inline Function which returns a table as follows:
CREATE FUNCTION MyProc()
RETURNS TABLE AS
RETURN (SELECT * FROM MyTable)
And then you can call it as
SELECT * FROM MyProc()
You also have the option of passing parameters to the function as follows:
CREATE FUNCTION FuncName (@para1 para1_type, @para2 para2_type , ... )
And call it
SELECT * FROM FuncName ( @para1 , @para2 )
androidx
will replace support library
after 28.0.0
. You should migrate your project to use it. androidx
uses Semantic Versioning
. Using AndroidX
will not be confused by version that is presented in library name and package name. Life becomes easier
Its a start, it can list:
models = Dir.new("#{RAILS_ROOT}/app/models").entries
Looking some more...
You can use a ComboBox
with its ComboBoxStyle
(appears as DropDownStyle
in later versions) set to DropDownList
. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx
I am shamelessly copying the excerpts from man page of top
VIRT -- Virtual Image (kb) The total amount of virtual memory used by the task. It includes all code, data and shared libraries plus pages that have been swapped out and pages that have been mapped but not used.
SWAP -- Swapped size (kb) Memory that is not resident but is present in a task. This is memory that has been swapped out but could include additional non- resident memory. This column is calculated by subtracting physical memory from virtual memory
I just experienced a similar message [ mine was "Permission denied (publickey)"] after connecting to a compute engine VM which I just created. After reading this post, I decided to try it again.
That time it worked. So i see 3 possible reasons for it working the second time,
I suspect the last is unlikely :)
$(this)
is a jQuery object that is wrapping the DOM element this
and jQuery objects don't have id
properties. You probably want just this.id
to get the id
attribute of the clicked element.
Coarse-grained and Fine-grained both think about optimizing a number of servicess. But the difference is in the level. I like to explain with an example, you will understand easily.
Fine-grained: For example, I have 100 services like findbyId, findbyCategry, findbyName...... so on. Instead of that many services why we can not provide find(id, category, name....so on). So this way we can reduce the services. This is just an example, but the goal is how to optimize the number of services.
Coarse-grained: For example, I have 100 clients, each client have their own set of 100 services. So I have to provide 100*100 total services. It is very much difficult. Instead of that what I do is, I identify all common services which apply to most of the clients as one service set and remaining separately. For example in 100 services 50 services are common. So I have to manage 100*50 + 50 only.
found this on Zurb's github
In case you want to do some more custom styling. Here's all the default CSS for webkit rendering of the date components.
input[type="date"] {
-webkit-align-items: center;
display: -webkit-inline-flex;
font-family: monospace;
overflow: hidden;
padding: 0;
-webkit-padding-start: 1px;
}
input::-webkit-datetime-edit {
-webkit-flex: 1;
-webkit-user-modify: read-only !important;
display: inline-block;
min-width: 0;
overflow: hidden;
}
input::-webkit-datetime-edit-fields-wrapper {
-webkit-user-modify: read-only !important;
display: inline-block;
padding: 1px 0;
white-space: pre;
}
Check the following
$ git status
$ git add .
$ bundle install
$ git add Gemfile.lock
$ git commit -am "Added Gemfile.lock"
$ git push heroku master
Your push should work
There's a setting in Safari under "Tabs" that labeled Open pages in tabs instead of windows:
with a drop down with a few options. I'm thinking yours may be set to Always
. Bottom line is you can't rely on a browser opening a new window.
opt
is new for ruby 1.9. The various options are documented in IO.new
: www.ruby-doc.org/core/IO.html
string alpha = "abcdefghijklmnopqrstuvwxyz";
string newAlpha = "";
for (int i = 5; i < alpha.Length; i += 6)
{
newAlpha = alpha.Insert(i, "-");
alpha = newAlpha;
}
You can't use a function to insert data into a base table. Functions return data. This is listed as the very first limitation in the documentation:
User-defined functions cannot be used to perform actions that modify the database state.
"Modify the database state" includes changing any data in the database (though a table variable is an obvious exception the OP wouldn't have cared about 3 years ago - this table variable only lives for the duration of the function call and does not affect the underlying tables in any way).
You should be using a stored procedure, not a function.
Small +1 to kshark27's answer to make it dynamic:
#include <QTime>
void delay( int millisecondsToWait )
{
QTime dieTime = QTime::currentTime().addMSecs( millisecondsToWait );
while( QTime::currentTime() < dieTime )
{
QCoreApplication::processEvents( QEventLoop::AllEvents, 100 );
}
}
It looks like {{ data.0 }}
. See Variables and lookups.
This error happens when you send 2 responses. For example :
if(condition A)
{
res.render('Profile', {client:client_});
}
if (condition B){
res.render('Profile', {client:client_});
}
}
Imagine if for some reason condition A and B are true so in the second render
you'll get that error
You can use std::set
instead of std::map
.
You can store both key and value in std::pair
and the type of container will look like this:
std::set< std::pair<int, std::string> > items;
std::set
will sort it's values both by original keys and values that were stored in std::map
.
class Foo:
def __eq__(self,other):
return True
foo=Foo()
print(foo==None)
# True
print(foo is None)
# False
I could NOT solve this. I had CORS enabled and working as long as the POST returned void (ASP.NET 4.0 - WEBAPI 1). When I tried to return a HttpResponseMessage, I started getting the HTTP 405 response.
Based on Llad's response above, I took a look at my own references.
I had the attribute [System.Web.Mvc.HttpPost] listed above my POST method.
I changed this to use:
[System.Web.Http.HttpPostAttribute]
[HttpOptions]
public HttpResponseMessage Post(object json)
{
...
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
This fixed my woes. I hope this helps someone else.
For the sake of completeness, I had the following in my web.config:
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, PATCH, DELETE" />
<add name="Access-Control-Allow-Headers" value="accept, authorization, Content-Type" />
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
A short demonstration of @gregmac's (excellent and detailed) answer, which essentially recommends $PSCommandPath
as the only reliable command to return the currently running script where Powershell 3.0 and above is used.
Here I show returning either the full path or just the file name.
Test.ps1:
'Direct:'
$PSCommandPath # Full Path
Split-Path -Path $PSCommandPath -Leaf # File Name only
function main () {
''
'Within a function:'
$PSCommandPath
Split-Path -Path $PSCommandPath -Leaf
}
main
Output:
PS> .\Test.ps1
Direct:
C:\Users\John\Documents\Sda\Code\Windows\PowerShell\Apps\xBankStatementRename\Test.ps1
Test.ps1
Within a function:
C:\Users\John\Documents\Sda\Code\Windows\PowerShell\Apps\xBankStatementRename\Test.ps1
Test.ps1
The a == b
expression invokes A.__eq__
, since it exists. Its code includes self.value == other
. Since int's don't know how to compare themselves to B's, Python tries invoking B.__eq__
to see if it knows how to compare itself to an int.
If you amend your code to show what values are being compared:
class A(object):
def __eq__(self, other):
print("A __eq__ called: %r == %r ?" % (self, other))
return self.value == other
class B(object):
def __eq__(self, other):
print("B __eq__ called: %r == %r ?" % (self, other))
return self.value == other
a = A()
a.value = 3
b = B()
b.value = 4
a == b
it will print:
A __eq__ called: <__main__.A object at 0x013BA070> == <__main__.B object at 0x013BA090> ?
B __eq__ called: <__main__.B object at 0x013BA090> == 3 ?
Two conditional functions are needed: one for Google Chrome, and a second for the remaining browsers.
$scope.printDiv = function (divName) {
var printContents = document.getElementById(divName).innerHTML;
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
popupWin.window.focus();
popupWin.document.write('<!DOCTYPE html><html><head>' +
'<link rel="stylesheet" type="text/css" href="style.css" />' +
'</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div></body></html>');
popupWin.onbeforeunload = function (event) {
popupWin.close();
return '.\n';
};
popupWin.onabort = function (event) {
popupWin.document.close();
popupWin.close();
}
} else {
var popupWin = window.open('', '_blank', 'width=800,height=600');
popupWin.document.open();
popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
popupWin.document.close();
}
popupWin.document.close();
return true;
}
For Tomcat 8:
Linux :
Create setenv.sh and update it with following:
export SPRING_PROFILES_ACTIVE=dev
Windows:
Create setenv.bat and update it with following:
set SPRING_PROFILES_ACTIVE=dev
var app = angular.module("app", []);
app.filter('capitalize', function() {
return function(str) {
if (str === undefined) return; // avoid undefined
str = str.toLowerCase().split(" ");
var c = '';
for (var i = 0; i <= (str.length - 1); i++) {
var word = ' ';
for (var j = 0; j < str[i].length; j++) {
c = str[i][j];
if (j === 0) {
c = c.toUpperCase();
}
word += c;
}
str[i] = word;
}
str = str.join('');
return str;
}
});
None of this worked for me in ios 7. Here is what I ended up doing. I put this in my custom cell class and call the method in my heightForCellAtIndexPath method.
My cell looks similar to the description cell when viewing an app in the app store.
First in the storyboard, set your label to 'attributedText', set the number of lines to 0 (which will resize the label automatically (ios 6+ only)) and set it to word wrap.
Then i just add up all the heights of the content of the cell in my custom Cell Class. In my case I have a Label at the top that always says "Description" (_descriptionHeadingLabel), a smaller label that is variable in size that contains the actual description (_descriptionLabel) a constraint from the top of the cell to the heading (_descriptionHeadingLabelTopConstraint). I also added 3 to space out the bottom a little bit (about the same amount apple places on the subtitle type cell.)
- (CGFloat)calculateHeight
{
CGFloat width = _descriptionLabel.frame.size.width;
NSAttributedString *attributedText = _descriptionLabel.attributedText;
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX} options: NSStringDrawingUsesLineFragmentOrigin context:nil];
return rect.size.height + _descriptionHeadingLabel.frame.size.height + _descriptionHeadingLabelTopConstraint.constant + 3;
}
And in my Table View delegate:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
if (indexPath.row == 0) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"descriptionCell"];
DescriptionCell *descriptionCell = (DescriptionCell *)cell;
NSString *text = [_event objectForKey:@"description"];
descriptionCell.descriptionLabel.text = text;
return [descriptionCell calculateHeight];
}
return 44.0f;
}
You can change the if statement to be a little 'smarter' and actually get the cell identifier from some sort of data source. In my case the cells are going to be hard coded since there will be fixed amount of them in a specific order.
Easier still you can just do
for i in {00001..99999}; do
echo $i
done
One nice feature of out
parameters is that they can be used to return data even when a function throws an exception. I think the closest equivalent to doing this with an async
method would be using a new object to hold the data that both the async
method and caller can refer to. Another way would be to pass a delegate as suggested in another answer.
Note that neither of these techniques will have any of the sort of enforcement from the compiler that out
has. I.e., the compiler won’t require you to set the value on the shared object or call a passed in delegate.
Here’s an example implementation using a shared object to imitate ref
and out
for use with async
methods and other various scenarios where ref
and out
aren’t available:
class Ref<T>
{
// Field rather than a property to support passing to functions
// accepting `ref T` or `out T`.
public T Value;
}
async Task OperationExampleAsync(Ref<int> successfulLoopsRef)
{
var things = new[] { 0, 1, 2, };
var i = 0;
while (true)
{
// Fourth iteration will throw an exception, but we will still have
// communicated data back to the caller via successfulLoopsRef.
things[i] += i;
successfulLoopsRef.Value++;
i++;
}
}
async Task UsageExample()
{
var successCounterRef = new Ref<int>();
// Note that it does not make sense to access successCounterRef
// until OperationExampleAsync completes (either fails or succeeds)
// because there’s no synchronization. Here, I think of passing
// the variable as “temporarily giving ownership” of the referenced
// object to OperationExampleAsync. Deciding on conventions is up to
// you and belongs in documentation ^^.
try
{
await OperationExampleAsync(successCounterRef);
}
finally
{
Console.WriteLine($"Had {successCounterRef.Value} successful loops.");
}
}
Here is short Scala solution:
def bfs(nodes: List[Node]): List[Node] = {
if (nodes.nonEmpty) {
nodes ++ bfs(nodes.flatMap(_.children))
} else {
List.empty
}
}
Idea of using return value as accumulator is well suited. Can be implemented in other languages in similar way, just make sure that your recursive function process list of nodes.
Test code listing (using @marco test tree):
import org.scalatest.FlatSpec
import scala.collection.mutable
class Node(val value: Int) {
private val _children: mutable.ArrayBuffer[Node] = mutable.ArrayBuffer.empty
def add(child: Node): Unit = _children += child
def children = _children.toList
override def toString: String = s"$value"
}
class BfsTestScala extends FlatSpec {
// 1
// / | \
// 2 3 4
// / | | \
// 5 6 7 8
// / | | \
// 9 10 11 12
def tree(): Node = {
val root = new Node(1)
root.add(new Node(2))
root.add(new Node(3))
root.add(new Node(4))
root.children(0).add(new Node(5))
root.children(0).add(new Node(6))
root.children(2).add(new Node(7))
root.children(2).add(new Node(8))
root.children(0).children(0).add(new Node(9))
root.children(0).children(0).add(new Node(10))
root.children(2).children(0).add(new Node(11))
root.children(2).children(0).add(new Node(12))
root
}
def bfs(nodes: List[Node]): List[Node] = {
if (nodes.nonEmpty) {
nodes ++ bfs(nodes.flatMap(_.children))
} else {
List.empty
}
}
"BFS" should "work" in {
println(bfs(List(tree())))
}
}
Output:
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" )
. After the required positional arguments, you can specify specific optional arguments by name.
If you are able to write Perl code, then you should consider using Net::OpenSSH::Parallel.
You would be able to describe the actions that have to be run in every host in a declarative manner and the module will take care of all the scary details. Running commands through sudo
is also supported.
Android API Version for application and device should match. Check if minSdkVersion
and targetSdkVersion
in Gradle Scripts - build.gradle (Module: app)
correspond device API.
Also low versions (e.g. API 15) result in ide-emulator link failure, inspite of applicatrion and device versions match.
As pointed out by @Jason, for most shared hosting environments, having a copy of php.ini file in your public_html directory works to override the system default settings. A great way to do this is by copying the hosting company's copy. Put this in a file, say copyini.php
<?php
system("cp /path/to/php/conf/file/php.ini /home/yourusername/public_html/php.ini");
?>
Get /path/to/php/conf/file/php.ini from the output of phpinfo(); in a file. Then in your ini file, make your amendments Delete all files created during this process (Apart from php.ini of course :-) )
The shortest and simpliest way here is to use
df.eval('e = a + b + d')
SELECT Top 1 sysobjects.[name], max(sysindexes.[rows]) AS TableRows,
CAST(
CASE max(sysindexes.[rows])
WHEN 0 THEN -0
ELSE LOG10(max(sysindexes.[rows]))
END
AS NUMERIC(5,2))
AS L10_TableRows
FROM sysindexes INNER JOIN sysobjects ON sysindexes.[id] = sysobjects.[id]
WHERE sysobjects.xtype = 'U'
GROUP BY sysobjects.[name]
ORDER BY max(rows) DESC
It is important to keep in mind that let is lazy evaluated and not putting side-effect methods in it otherwise you would not be able to change from let to before(:each) easily. You can use let! instead of let so that it is evaluated before each scenario.
If you don't want to map ports from your host to the container you can access directly to the docker range ip for the container. This range is by default only accessed from your host. You can check your container network data doing:
docker inspect <containerNameOrId>
Probably is better to filter:
docker inspect <containerNameOrId> | grep '"IPAddress"' | head -n 1
Usually, the default docker ip range is 172.17.0.0/16
. Your host should be 172.17.0.1
and your first container should be 172.17.0.2
if everything is normal and you didn't specify any special network options.
EDIT Another more elegant way using docker features instead of "bash tricking":
docker inspect -f "{{ .NetworkSettings.IPAddress }}" <containerNameOrId>
for (i = 0; i < 16; i++)
{
fscanf(myFile, "%d", &numberArray[i]);
}
This is attempting to read the whole string, "5623125698541159"
into &numArray[0]
. You need spaces between the numbers:
5 6 2 3 ...
I have the same problem and I solved it and the explanation is as follow:
If the Seaborn package is not installed in anaconda, you will not be able to update it, namely, if in the Terminal we type: conda update seaborn
it will fail showing: "PackageNotFoundError: Package not found: 'seaborn' Package 'seaborn' is not installed in /Users/yifan/anaconda"
Thus we need to install seaborn in anaconda first by typing in Terminal: conda install -c https://conda.anaconda.org/anaconda seaborn
Then the seaborn will be fetched and installed in the environment of anaconda, namely in my case, /Users/yifan/anaconda
Once this installation is done, we will be able to import seaborn in python.
Side note, to check and list all discoverable environments where python is installed in anaconda, type in Terminal: conda info --envs
Try this, at the end of the each loop, ids array will contain all the hexcodes.
var ids = [];
$(document).ready(function($) {
var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
$(".color_cell").each(function() {
code = $(this).attr('id');
ids.push(code);
$div.append(code + "<br />");
});
});
I think you can use the overload of Regex.Replace to specify the maximum number of times to replace...
var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);
The only way I can think of doing it is by invoking a command line application that does the job for you and then screenscraping the output (like Linux's ps and Window's tasklist).
Unfortunately, that'll mean you'll have to write some parsing routines to read the data from both.
Process proc = Runtime.getRuntime().exec ("tasklist.exe");
InputStream procOutput = proc.getInputStream ();
if (0 == proc.waitFor ()) {
// TODO scan the procOutput for your data
}
Sometimes you can use simple .split("REGEXP") method available in java.lang.String. For example:
String input = "first,second,third";
//To retrieve 'first'
input.split(",")[0]
//second
input.split(",")[1]
//third
input.split(",")[2]
As per Miller's Recursive Make Considered Harmful you should avoid calling $(MAKE)
! In the case you show, it's harmless, because this isn't really a makefile, just a wrapper script, that might just as well have been written in Shell. But you say you continue like that at deeper recursion levels, so you've probably encountered the problems shown in that eye-opening essay.
Of course with GNU make it's cumbersome to avoid. And even though they are aware of this problem, it's their documented way of doing things.
OTOH, makepp was created as a solution for this problem. You can write your makefiles on a per directory level, yet they all get drawn together into a full view of your project.
But legacy makefiles are written recursively. So there's a workaround where $(MAKE)
does nothing but channel the subrequests back to the main makepp process. Only if you do redundant or, worse, contradictory things between your submakes, you must request --traditional-recursive-make
(which of course breaks this advantage of makepp). I don't know your other makefiles, but if they're cleanly written, with makepp necessary rebuilds should happen automatically, without the need for any hacks suggested here by others.
You can call dispose()
on the current window and setVisible(true)
on the one you want to display.
Also, from API level 21 this is possible:
int random = ThreadLocalRandom.current().nextInt(min, max);
If you use Hadoop version 2.6.1 above, while the command works, it complains that its depreciated. I actually could not use the hadoop dfsadmin -safemode leave
because I was running Hadoop in a Docker container and that command magically fails when run in the container, so what I did was this. I checked doc and found dfs.safemode.threshold.pct
in documentation that says
Specifies the percentage of blocks that should satisfy the minimal replication requirement defined by dfs.replication.min. Values less than or equal to 0 mean not to wait for any particular percentage of blocks before exiting safemode. Values greater than 1 will make safe mode permanent.
so I changed the hdfs-site.xml
into the following (In older Hadoop versions, apparently you need to do it in hdfs-default.xml
:
<configuration>
<property>
<name>dfs.safemode.threshold.pct</name>
<value>0</value>
</property>
</configuration>
android developers documentation says : "Updated the AppCompatActivity as the base class for activities that use the support library action bar features. This class replaces the deprecated ActionBarActivity."
checkout changes for Android Support Library, revision 22.1.0 (April 2015)
IF the table is alias t
SELECT t.Present , t.previous, t.previous- t.Present AS Difference
FROM temp1 as t
The JSON.stringify
method supported by many modern browsers (including IE8) can output a beautified JSON string:
JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4); // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/
This method is also included with json2.js, for supporting older browsers.
If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.
Casting int
to char
involves losing data and the compiler will probably warn you.
Extracting a particular byte from an int
sounds more reasonable and can be done like this:
number & 0x000000ff; /* first byte */
(number & 0x0000ff00) >> 8; /* second byte */
(number & 0x00ff0000) >> 16; /* third byte */
(number & 0xff000000) >> 24; /* fourth byte */
$new_input = array('type' => 'text', 'label' => 'First name', 'show' => true, 'required' => true);
$options['inputs']['name'] = $new_input;
Finally i thought my way is better since when number of return types go higher this kind of a implementation do that in best way.
public static ReturningValues myMethod() {
ReturningValues rv = new ReturningValues();
rv.setValue("value");
rv.setIndex(12);
return rv;
}
If the size of the list if fixed, then you can use an AtomicReferenceArray. This would allow you to perform indexed updates to a slot. You could write a List view if needed.
I would go this way:
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
// View
public partial class TestCloseWindow : Window
{
public TestCloseWindow() {
InitializeComponent();
Messenger.Default.Register<CloseWindowMsg>(this, (msg) => Close());
}
}
// View Model
public class MainViewModel: ViewModelBase
{
ICommand _closeChildWindowCommand;
public ICommand CloseChildWindowCommand {
get {
return _closeChildWindowCommand?? (_closeChildWindowCommand = new RelayCommand(() => {
Messenger.Default.Send(new CloseWindowMsg());
}));
}
}
}
public class CloseWindowMsg
{
}
If by "list" you mean a List<T>
, then the Clear method is what you want:
List<string> list = ...;
...
list.Clear();
You should get into the habit of searching the MSDN documentation on these things.
Here's how to quickly search for documentation on various bits of that type:
List<T>
class itself (this is where you should've started)All of these Google queries lists a bundle of links, but typically you want the first one that google gives you in each case.
Just for the sake of completeness, we can use the operators [
and [[
:
set.seed(1)
df <- data.frame(v1 = runif(10), v2 = letters[1:10])
Several options
df[df[1] < 0.5 | df[2] == "g", ]
df[df[[1]] < 0.5 | df[[2]] == "g", ]
df[df["v1"] < 0.5 | df["v2"] == "g", ]
df$name is equivalent to df[["name", exact = FALSE]]
Using dplyr
:
library(dplyr)
filter(df, v1 < 0.5 | v2 == "g")
Using sqldf
:
library(sqldf)
sqldf('SELECT *
FROM df
WHERE v1 < 0.5 OR v2 = "g"')
Output for the above options:
v1 v2
1 0.26550866 a
2 0.37212390 b
3 0.20168193 e
4 0.94467527 g
5 0.06178627 j
The problem is described (among other) in this article.
#box
is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".
Page flow means that the positioning of an element effects other elements in the flow.
In other words, as #box
now sees the dom, .a and .b are no longer "inside" #box
.
To fix this, you would want to make everything relative, or everything absolute.
One way would be:
.a {
position:relative;
margin-top:10px;
margin-left:10px;
background-color:red;
width:210px;
padding: 5px;
}
I have created a custom regex to deal with names:
I have tried these types of names and found working perfect
My RegEx looks like this:
^([a-zA-Z]{2,}\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\s?([a-zA-Z]{1,})?)
MVC4 Model:
[RegularExpression("^([a-zA-Z]{2,}\\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\\s?([a-zA-Z]{1,})?)", ErrorMessage = "Valid Charactors include (A-Z) (a-z) (' space -)") ]
Please note the double \\
for escape characters
For those of you that are new to RegEx I thought I'd include a explanation.
^ // start of line
[a-zA-Z]{2,} // will except a name with at least two characters
\s // will look for white space between name and surname
[a-zA-Z]{1,} // needs at least 1 Character
\'?-? // possibility of **'** or **-** for double barreled and hyphenated surnames
[a-zA-Z]{2,} // will except a name with at least two characters
\s? // possibility of another whitespace
([a-zA-Z]{1,})? // possibility of a second surname
<audio autoplay>
<source src="file.mp3" type="audio/mpeg">
</audio>
It removes the auto play bar but still plays the music. Invisible sounds!
The other answers detail the reason for the error. A possible cause (to check) may be your class has a variable and method with the same name, which you then call. Python accesses the variable as a callable - with ()
.
e.g. Class A defines self.a
and self.a()
:
>>> class A:
... def __init__(self, val):
... self.a = val
... def a(self):
... return self.a
...
>>> my_a = A(12)
>>> val = my_a.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>>
this code worked for me:
window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId');
Obviously, the syntax are completely different (Groovy is closest to Java), but I suppose that is not what you are asking for.
If you are interested in using them to script a Java application, Scala is probably not a good choice, as there is no easy way to evaluate it from Java, whereas Groovy is especially suited for that purpose.
Use bytearray
:
with open("img.png", "rb") as image:
f = image.read()
b = bytearray(f)
print b[0]
You can also have a look at struct which can do many conversions of that kind.
Try to create an AVD with the monitor.bat
in the tools-folder
, that worked out for me!
According to Wikipedia:
5222 TCP XMPP client connection (RFC 6120) Official 5223 TCP XMPP client connection over SSL Unofficial 5269 TCP XMPP server connection (RFC 6120) Official 5298 TCP UDP XMPP JEP-0174: Link-Local Messaging / Official XEP-0174: Serverless Messaging 8010 TCP XMPP File transfers Unofficial
The port numbers are defined in RFC 6120 § 14.7.
This example should work fine. I have added streamhandler for console. Console log and file handler data should be similar.
# MUTHUKUMAR_TIME_DATE.py #>>>>>>>> file name(module)
import sys
import logging
import logging.config
# ================== Logger ================================
def Logger(file_name):
formatter = logging.Formatter(fmt='%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s',
datefmt='%Y/%m/%d %H:%M:%S') # %I:%M:%S %p AM|PM format
logging.basicConfig(filename = '%s.log' %(file_name),format= '%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s',
datefmt='%Y/%m/%d %H:%M:%S', filemode = 'w', level = logging.INFO)
log_obj = logging.getLogger()
log_obj.setLevel(logging.DEBUG)
# log_obj = logging.getLogger().addHandler(logging.StreamHandler())
# console printer
screen_handler = logging.StreamHandler(stream=sys.stdout) #stream=sys.stdout is similar to normal print
screen_handler.setFormatter(formatter)
logging.getLogger().addHandler(screen_handler)
log_obj.info("Logger object created successfully..")
return log_obj
# =======================================================
MUTHUKUMAR_LOGGING_CHECK.py #>>>>>>>>>>> file name
# calling **Logger** function
file_name = 'muthu'
log_obj =Logger(file_name)
log_obj.info("yes hfghghg ghgfh".format())
log_obj.critical("CRIC".format())
log_obj.error("ERR".format())
log_obj.warning("WARN".format())
log_obj.debug("debug".format())
log_obj.info("qwerty".format())
log_obj.info("asdfghjkl".format())
log_obj.info("zxcvbnm".format())
# closing file
log_obj.handlers.clear()
OUTPUT:
2019/07/13 23:54:40 MUTHUKUMAR_TIME_DATE,line: 17 INFO | Logger object created successfully..
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 8 INFO | yes hfghghg ghgfh
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 9 CRITICAL | CRIC
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 10 ERROR | ERR
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 11 WARNING | WARN
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 12 DEBUG | debug
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 13 INFO | qwerty
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 14 INFO | asdfghjkl
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 15 INFO | zxcvbnm
Thanks,
The old way:
xcopy [source] [destination] /E
xcopy is deprecated. Robocopy replaces Xcopy. It comes with Windows 8, 8.1 and 10.
robocopy [source] [destination] /E
robocopy has several advantages:
More details here.
I was looking into this just now, and wasn't happy with the readability of the current solution. If you're writing code informally or on a small project, you can just add another item to the end of your enum called "Length". This way, you only need to type:
var namesCount = (int)MyEnum.Length;
Of course if others are going to use your code - or I'm sure under many other circumstances that didn't apply to me in this case - this solution may be anywhere from ill advised to terrible.
Travis-ci and Jenkins, while both are tools for continuous integration are very different.
Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.
Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml
which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.
You can have a similar feature with Jenkins if you use one of the following plugins:
.jervis.yml
file found at the root of project code. If .jervis.yml
does not exist, it will fall back to using .travis.yml
file instead.There are other hosted services you might also consider for continuous integration (non exhaustive list):
You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)
Depending on where your code repository is hosted I would make the following choices:
To setup Travis-CI on a github project, all you have to do is:
The features you get are:
$(this.parentNode).addClass('newClass');
Here's an extension that will do it all, on as many elements in as many ways...
Example usage:
keep existing class and attributes:
$('div#change').replaceTag('<span>', true);
or
Discard existing class and attributes:
$('div#change').replaceTag('<span class=newclass>', false);
or even
replace all divs with spans, copy classes and attributes, add extra class name
$('div').replaceTag($('<span>').addClass('wasDiv'), true);
Plugin Source:
$.extend({
replaceTag: function (currentElem, newTagObj, keepProps) {
var $currentElem = $(currentElem);
var i, $newTag = $(newTagObj).clone();
if (keepProps) {//{{{
newTag = $newTag[0];
newTag.className = currentElem.className;
$.extend(newTag.classList, currentElem.classList);
$.extend(newTag.attributes, currentElem.attributes);
}//}}}
$currentElem.wrapAll($newTag);
$currentElem.contents().unwrap();
// return node; (Error spotted by Frank van Luijn)
return this; // Suggested by ColeLawrence
}
});
$.fn.extend({
replaceTag: function (newTagObj, keepProps) {
// "return" suggested by ColeLawrence
return this.each(function() {
jQuery.replaceTag(this, newTagObj, keepProps);
});
}
});
You can use the datetime
module for working with dates and times in Python. The strftime
method allows you to produce string representation of dates and times with a format you specify.
>>> import datetime
>>> datetime.date.today().strftime("%B %d, %Y")
'July 23, 2010'
>>> datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
'10:36AM on July 23, 2010'
For large data l recommend you use the library "dask"
e.g:
# Dataframes implement the Pandas API
import dask.dataframe as dd
df = dd.read_csv('s3://.../2018-*-*.csv')
You can read more from the documentation here.
Another great alternative would be to use modin because all the functionality is identical to pandas yet it leverages on distributed dataframe libraries such as dask.
It's also important to realize that simply moving the program break pointer around with brk
and sbrk
doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.
The easiest way to do this is:
list.sort(key = lambda x:len(x))
Just for the sake of completeness, here is a solution with lambda and method reference:
Description: The following method
String
with the pattern yyyy-MM-dd
into a Timestamp
, if a valid input is given,null
, if a null
value is given,DateTimeParseException
, if an invalid input is givenCode:
static Timestamp convertStringToTimestamp(String strDate) {
return Optional.ofNullable(strDate) // wrap the String into an Optional
.map(str -> LocalDate.parse(str).atStartOfDay()) // convert into a LocalDate and fix the hour:minute:sec to 00:00:00
.map(Timestamp::valueOf) // convert to Timestamp
.orElse(null); // if no value is present, return null
}
Validation:
This method can be tested with those unit tests:
(with Junit5 and Hamcrest)
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenValidInput() {
// given
String strDate = "2020-01-30";
// when
final Timestamp result = convertStringToTimestamp(strDate);
// then
final LocalDateTime dateTime = LocalDateTime.ofInstant(result.toInstant(), ZoneId.systemDefault());
assertThat(dateTime.getYear(), is(2020));
assertThat(dateTime.getMonthValue(), is(1));
assertThat(dateTime.getDayOfMonth(), is(30));
}
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenInvalidInput() {
// given
String strDate = "7770-91-30";
// when, then
assertThrows(DateTimeParseException.class, () -> convertStringToTimestamp(strDate));
}
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenNullInput() {
// when
final Timestamp result = convertStringToTimestamp(null);
// then
assertThat(result, is(nullValue()));
}
Usually, the string to parse comes with another format. A way to deal with it is to use a formatter to convert it to another format. Here is an example:
Input: 20200130 11:30
Pattern: yyyyMMdd HH:mm
Output: Timestamp of this input
Code:
static Timestamp convertStringToTimestamp(String strDate) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm");
return Optional.ofNullable(strDate) //
.map(str -> LocalDateTime.parse(str, formatter))
.map(Timestamp::valueOf) //
.orElse(null);
}
Test:
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenValidInput() {
// given
String strDate = "20200130 11:30";
// when
final Timestamp result = convertStringToTimestamp(strDate);
// then
final LocalDateTime dateTime = LocalDateTime.ofInstant(result.toInstant(), ZoneId.systemDefault());
assertThat(dateTime.getYear(), is(2020));
assertThat(dateTime.getMonthValue(), is(1));
assertThat(dateTime.getDayOfMonth(), is(30));
assertThat(dateTime.getHour(), is(11));
assertThat(dateTime.getMinute(), is(30));
}
Let's assume you want to overwrite the same file:
import json
with open('data.json', 'r') as data_file:
data = json.load(data_file)
for element in data:
element.pop('hours', None)
with open('data.json', 'w') as data_file:
data = json.dump(data, data_file)
dict.pop(<key>, not_found=None)
is probably what you where looking for, if I understood your requirements. Because it will remove the hours
key if present and will not fail if not present.
However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?
Now, if you really want to use del
instead of pop
, here is how you could make your code work:
import json
with open('data.json') as data_file:
data = json.load(data_file)
for element in data:
if 'hours' in element:
del element['hours']
with open('data.json', 'w') as data_file:
data = json.dump(data, data_file)
EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.
I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.
with
is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with
block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.
Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.
I hope it's clear enough...
SECOND EDIT
This time, it seems clear that you need to do this:
with open('dest_file.json', 'w') as dest_file:
with open('source_file.json', 'r') as source_file:
for line in source_file:
element = json.loads(line.strip())
if 'hours' in element:
del element['hours']
dest_file.write(json.dumps(element))
It's ok to use mysql_insert_id()
,
but there is one specific note about using it, you must call it after executed INSERT query, means in the same script session.
If you use it otherwise it wouldn't work correctly.
If you'd like to see this feature added natively, along with all of the advanced functionality, I'd suggest upvoting the open GitHub issue here.
As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.
Generally speaking, if you need to generate numbers from min
to max
(including both), you write
random.nextInt(max - min + 1) + min
This problem also occurs when you have 2 resources with the same file name; say "configurations.properties" within 2 different jar or directory path configured within the classpath. For example:
You have your "configurations.properties" in your process or web application (jar, war or ear). But another dependency (jar) have the same file "configurations.properties" in the same path. Then I suppose that Spring have no idea (@_@?) where to get the property and just sends the property name declared within the @Value annotation.
I would simply make the assignment happen in the ng-mouseover and ng-mouseleave; no need to bother js file :)
<ul ng-repeat="task in tasks">
<li ng-mouseover="hoverEdit = true" ng-mouseleave="hoverEdit = false">{{task.name}}</li>
<span ng-show="hoverEdit"><a>Edit</a></span>
</ul>
<run your last command on this line>
a=${?}
if [ ${a} -ne 0 ]; then echo "do something"; fi
use whatever command you want to use instead of the echo "do something"
command
Just give them the same name throughout the form you are using.
<form><input type="radio" name="selection">
<input type="radio" name="selection">
..
..
</form>
(fiddle: https://jsfiddle.net/ya3ya6/7hfkdnrg/2/ )
Html:
<textarea id='tbMain' ></textarea>
<a id='btnOpen' href='#' >Open</a>
Js:
document.getElementById('btnOpen').onclick = function(){
openFile(function(txt){
document.getElementById('tbMain').value = txt;
});
}
function openFile(callBack){
var element = document.createElement('input');
element.setAttribute('type', "file");
element.setAttribute('id', "btnOpenFile");
element.onchange = function(){
readText(this,callBack);
document.body.removeChild(this);
}
element.style.display = 'none';
document.body.appendChild(element);
element.click();
}
function readText(filePath,callBack) {
var reader;
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
callBack(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
All the other answers don't seem to explain the use of random.seed(). Here is a simple example (source):
import random
random.seed( 3 )
print "Random number with seed 3 : ", random.random() #will generate a random number
#if you want to use the same random number once again in your program
random.seed( 3 )
random.random() # same random number as before
I needed to find a way to do this too, using numbers from different places and not in a collection. I was sure there was a method to do this in c#...though by the looks of it I'm muddling my languages...
Anyway, I ended up writing a couple of generic methods to do it...
static T Max<T>(params T[] numberItems)
{
return numberItems.Max();
}
static T Min<T>(params T[] numberItems)
{
return numberItems.Min();
}
...call them this way...
int intTest = Max(1, 2, 3, 4);
float floatTest = Min(0f, 255.3f, 12f, -1.2f);
I had a similar problem. Using size_t was not working. I tried the other one which worked for me. (as below)
for(int i = things.size()-1;i>=0;i--)
{
//...
}
The below example shows how to read the text in the question, represented as the "jsonText" variable. This solution uses the Java EE7 javax.json API (which is mentioned in some of the other answers). The reason I've added it as a separate answer is that the following code shows how to actually access some of the values shown in the question. An implementation of the javax.json API would be required to make this code run. The full package for each of the classes required was included as I didn't want to declare "import" statements.
javax.json.JsonReader jr =
javax.json.Json.createReader(new StringReader(jsonText));
javax.json.JsonObject jo = jr.readObject();
//Read the page info.
javax.json.JsonObject pageInfo = jo.getJsonObject("pageInfo");
System.out.println(pageInfo.getString("pageName"));
//Read the posts.
javax.json.JsonArray posts = jo.getJsonArray("posts");
//Read the first post.
javax.json.JsonObject post = posts.getJsonObject(0);
//Read the post_id field.
String postId = post.getString("post_id");
Now, before anyone goes and downvotes this answer because it doesn't use GSON, org.json, Jackson, or any of the other 3rd party frameworks available, it's an example of "required code" per the question to parse the provided text. I am well aware that adherence to the current standard JSR 353 was not being considered for JDK 9 and as such the JSR 353 spec should be treated the same as any other 3rd party JSON handling implementation.
CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.
You need to define the animation keyframes and apply it to the element:
@keyframes changewidth {
from {
width: 100px;
}
to {
width: 300px;
}
}
div {
animation-duration: 0.1s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.
I resolved this, oddly enough, by installing System.Data.SQLite via the Nuget GUI application, as opposed to the package manager console.
Installing via the console didn't include the dependencies this library needs to run.
In java8, I would use the Instant
class which is already in UTC and is convenient to work with.
import java.time.Instant;
Instant ins = Instant.now();
long ts = ins.toEpochMilli();
Instant ins2 = Instant.ofEpochMilli(ts)
Alternatively, you can use the following:
import java.time.*;
Instant ins = Instant.now();
OffsetDateTime odt = ins.atOffset(ZoneOffset.UTC);
ZonedDateTime zdt = ins.atZone(ZoneId.of("UTC"));
Back to Instant
Instant ins4 = Instant.from(odt);
sysdate-(2/11)
A day consists of 24 hours
. So, to subtract 2 hours
from a day you need to divide it by 24
:
DATE_value - 2/24
Using interval
for the same:
DATE_value - interval '2' hour
This works fine for me.
final R.drawable drawableResources = new R.drawable();
final Class<R.drawable> c = R.drawable.class;
final Field[] fields = c.getDeclaredFields();
for (int i=0; i < fields.length;i++)
{
resourceId[i] = fields[i].getInt(drawableResources);
/* till here you get all the images into the int array resourceId.*/
}
imageview= (ImageView)findViewById(R.id.imageView);
if(your condition)
{
imageview.setImageResource(resourceId[any]);
}
If you are looking for an specific hex character in the middle of the string, you can use "\xhh" where hh is the character in hexadecimal. I've tried and it works. I use framework for C++ Qt but it can solve problems in other cases, depends on the flavor you need to use (php, javascript, python , golang, etc.).
This answer was taken from:http://ult-tex.net/info/perl/
In IPython, I first use
In [2]: %hist
to view my past code. I select the chunk I want to save and then paste it into file my_file.py
using the %%file
magic (short for %%writefile
)
In [3]: %%file my_file.py
...: # paste code here
...:
...:
hitting return two times in the end.
To append to file use the option -a
: %%file -a my_file.py
.
If needed, I can list, edit, etc. the file in the underlying command line using the exclamation mark
In [5]: !ls -l my_file.py
In [6]: !vi my_file.py
You need to enable SSL in your PHP config. Load up php.ini
and find a line with the following:
;extension=php_openssl.dll
Uncomment it. :D
(by removing the semicolon from the statement)
extension=php_openssl.dll
Also note that Scala extends String with a number of methods (via implicit conversion to a WrappedString brought in by Predef) so you could also do the following:
val formattedString = "Hello %s, isn't %s cool?".format("Ivan", "Scala")
Try
import pandas as pd
pd.read_csv("../data_folder/data.csv")
Referring to Alexey Mezenin
answer:
While using his answer, I had to add something directly to the Request Object and used:
$request->request->add(['variable', 'value']);
Using this it adds two variables :
$request[0] = 'variable', $request[1] = 'value'
If you are a newbie like me and you needed an associate array the correct way to do is
$request->request->add(['variable' => 'value']);
Hope I saved your some time
PS: Thank you @Alexey
, you really helped me out with your answer
You can use $_SERVER['REQUEST_URI']
to get requested path. Then, you'll need to remove the parameters...
$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
Then, add in the hostname and protocol.
echo 'http://' . $_SERVER['HTTP_HOST'] . $uri_parts[0];
You'll have to detect protocol as well, if you mix http:
and https://
. That I leave as an exercise for you. $_SERVER['REQUEST_SCHEME']
returns the protocol.
Putting it all together:
echo $_SERVER['REQUEST_SCHEME'] .'://'. $_SERVER['HTTP_HOST'] . explode('?', $_SERVER['REQUEST_URI'], 2)[0];
...returns, for example:
http://example.com/directory/file.php
You typically have to do this in a single syscall, or else you will get a race condition.
This will open for reading and writing, creating the file if necessary.
FILE *fp = fopen("scores.dat", "ab+");
If you want to read it and then write a new version from scratch, then do it as two steps.
FILE *fp = fopen("scores.dat", "rb");
if (fp) {
read_scores(fp);
}
// Later...
// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
error();
write_scores(fp);
I use the reflections in the toString() implementation of my preference class to see the class members and values (simple and quick debugging).
The simplified code I'm using:
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Class<?> thisClass = null;
try {
thisClass = Class.forName(this.getClass().getName());
Field[] aClassFields = thisClass.getDeclaredFields();
sb.append(this.getClass().getSimpleName() + " [ ");
for(Field f : aClassFields){
String fName = f.getName();
sb.append("(" + f.getType() + ") " + fName + " = " + f.get(this) + ", ");
}
sb.append("]");
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
I hope that it will help someone, because I also have searched.
I don't know if this helps:
suppose you want to run a sql script (test.sql) from the command line:
mysql < test.sql
and the contents of test.sql is something like:
SELECT * FROM information_schema.SCHEMATA;
\! echo "I like to party...";
The console will show something like:
CATALOG_NAME SCHEMA_NAME DEFAULT_CHARACTER_SET_NAME
def information_schema utf8
def mysql utf8
def performance_schema utf8
def sys utf8
I like to party...
So you can execute terminal commands inside an sql statement by just using \!
, provided the script is run via a command line.
\! #terminal_commands
This will return the first element
set.iterator().next();
That turned out to be pretty simple. I've got it occasionally. To paste a text you simply need to right mouse button click anywhere in terminal window.
Best way for me is:
Or you can push newly created branch on remote and merge there (if you do it this way, at the end you need to pull from remote master)
There are different ways to close the app, depending on:
if (navigator.app) {
navigator.app.exitApp();
} else if (navigator.device) {
navigator.device.exitApp();
} else {
window.close();
}
typeperf
gives me issues when it randomly doesn't work on some computers (Error: No valid counters.
) or if the account has insufficient rights. Otherwise, here is a way to extract just the value from its output. It still needs rounding though:
@for /f "delims=, tokens=2" %p in ('typeperf "\Processor(_Total)\% Processor Time" -sc 3 ^| find ":"') do @echo %~p%
Powershell has two cmdlets to get the percent utilization for all CPUs: Get-Counter
(preferred) or Get-WmiObject
:
Powershell "Get-Counter '\Processor(*)\% Processor Time' | Select -Expand Countersamples | Select InstanceName, CookedValue"
Or,
Powershell "Get-WmiObject Win32_PerfFormattedData_PerfOS_Processor | Select Name, PercentProcessorTime"
To get the overall CPU load with formatted output exactly like the question:
Powershell "[string][int](Get-Counter '\Processor(*)\% Processor Time').Countersamples[0].CookedValue + '%'"
Or,
Powershell "gwmi Win32_PerfFormattedData_PerfOS_Processor | Select -First 1 | %{'{0}%' -f $_.PercentProcessorTime}"
Suppose you have following lines of code
MyUrl = "www.google.com" #Your url goes here
urllib.urlretrieve(MyUrl)
If you are receiving following error message
AttributeError: module 'urllib' has no attribute 'urlretrieve'
Then you should try following code to fix the issue:
import urllib.request
MyUrl = "www.google.com" #Your url goes here
urllib.request.urlretrieve(MyUrl)
I managed to find a solution, but not a great one as it requires using AsEnumerable() which is going to return all results from the DB, fortunately I only have 1k records in the table so it isn't really noticable, but here goes.
var users = from u in (from u in ctx.Users
where u.Mod_Status != "D"
select u).AsEnumerable()
where ar.All(n => u.FullName.IndexOf(n,
StringComparison.InvariantCultureIgnoreCase) >= 0)
select u;
My original post follows:
How do you do the reverse? I want to do something like the following in entity framework.
string[] search = new string[] { "John", "Doe" }; var users = from u in ctx.Users from s in search where u.FullName.Contains(s) select u;
What I want is to find all users where their FullName contains all of the elements in `search'. I've tried a number of different ways, all of which haven't been working for me.
I've also tried
var users = from u in ctx.Users select u; foreach (string s in search) { users = users.Where(u => u.FullName.Contains(s)); }
This version only finds those that contain the last element in the search array.
I have fixed the by this way:
Create a folder in your resource directory name "drawable-nodpi"
and then move yours all resources in this directory from others drawable directory.
Now clean your project and then rebuilt. Run again hopefully it will work this time without any resource not found exception.
You could try using below command-
pip install opencv-contrib-python
It will basically download the compatible version. If this command fails, you could upgrade you pip using below command-
python -m pip install –upgrade pip
If you need a pictorial guide, head over to Simple Steps to Install OpenCV in Windows
You can also try installing OpenCV from prebuilt binaries from the official OpenCV site.
Not the answer for the above problem but on the similar lines.
Program to print the elements of the array sequentially but use two different threads to print the adjacent elements
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author ntv
*/
public class PrintLAternateNumber {
public static void main(String[] args) {
int [] num = {1,2,3,4,5,6};
Printer p = new Printer();
Thread t1 = new Thread(new Thread1(num, p), "Thread1");
Thread t2 = new Thread(new Thread2(num, p), "Thread2");
t1.start();
t2.start();
}
}
class Thread1 implements Runnable {
int [] num;
Printer p ;
public Thread1(int[] num, Printer p) {
this.num = num;
this.p = p;
}
public void run() {
try {
print();
} catch (InterruptedException ex) {
Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void print() throws InterruptedException {
int i = 1;
while(i < num.length) {
synchronized(num) {
while (p.evenPrinted) {
num.wait();
}
}
synchronized(num) {
p.printEven(Thread.currentThread().getName(), num[i]);
i= i + 2;
num.notifyAll();
}
}
}
}
class Thread2 implements Runnable {
int [] num;
Printer p ;
public Thread2(int[] num, Printer p) {
this.num = num;
this.p = p;
}
public void run() {
try {
print();
} catch (InterruptedException ex) {
Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void print() throws InterruptedException {
int i = 0;
while(i < num.length) {
synchronized(num) {
while (!p.evenPrinted) {
num.wait();
}
}
synchronized(num) {
p.printOdd(Thread.currentThread().getName(), num[i]);
i = i + 2;
num.notifyAll();
}
}
}
}
class Printer {
boolean evenPrinted = true;
void printEven(String threadName , int i) {
System.out.println(threadName + "," + i);
evenPrinted = true;
}
void printOdd(String threadName , int i) {
System.out.println(threadName + "," + i);
evenPrinted = false;
}
}
hg strip
is what you are looking for. It's analogous of git reset
if you familiar with git.
Use console:
You need to know the revision number. hg log -l 10
. This command shows the last 10 commits. Find commit you are looking for. You need 4 digit number from changeset line changeset: 5888:ba6205914681
Then hg strip -r 5888 --keep
. This removes the record of the commit but keeps all files modified and then you could recommit them.
(if you want to delete files to just remove --keep hg strip -r 5888
Dudes, I think there are a lot of shots in the dark here. In some cases Clean and Sync Project will help only after you fixed the problem.
Step1:
So go and look at the top of each file where the package is specified as follows pakage="YourURL.YourProject";
and insure that the correct package (Your Own Project) is specified.
You will find this in java files and AndroidManifest.xml and it is critical for the java files to reference the correct package, as that package contains the resources ("R") you are pointing to. Should they not match up the error cannot resolve Symbol R occurs.
Step2: Clean, Sync, whatever. Done
So why does this occur randomly or what did I do wrong??
If you copy and paste code, you should pay close attention to the "package=" as explained above. More importantly, when you paste code, it immediately runs through a sort of debugger (Excuse my bad tech term) to show you "presumed errors", which immediately takes in consideration the "Wrong Package", and you get all the errors. Therefore, even though you immediately corrected the notation after pasting, the debugger has already refreshed. Which is why "Clean, Sync, Whatever" works SOMETIMES
Please remember to "make it work first before you make it work fast".
Very few percent of any program are usually relevant for its speed.
You can always kick out or simplify an assert
if it ever proves to
be a performance problem -- and most of them never will.
Be pragmatic:
Assume you have a method that processes a non-empty list of tuples and the program logic will break if those tuples are not immutable. You should write:
def mymethod(listOfTuples):
assert(all(type(tp)==tuple for tp in listOfTuples))
This is probably fine if your lists tend to be ten entries long, but it can become a problem if they have a million entries. But rather than discarding this valuable check entirely you could simply downgrade it to
def mymethod(listOfTuples):
assert(type(listOfTuples[0])==tuple) # in fact _all_ must be tuples!
which is cheap but will likely catch most of the actual program errors anyway.
I'd try something like:
#!/usr/bin/python
from __future__ import print_function
import shlex
from subprocess import Popen, PIPE
def shlep(cmd):
'''shlex split and popen
'''
parsed_cmd = shlex.split(cmd)
## if parsed_cmd[0] not in approved_commands:
## raise ValueError, "Bad User! No output for you!"
proc = Popen(parsed_command, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
return (proc.returncode, out, err)
... In other words let shlex.split() do most of the work. I would NOT attempt to parse the shell's command line, find pipe operators and set up your own pipeline. If you're going to do that then you'll basically have to write a complete shell syntax parser and you'll end up doing an awful lot of plumbing.
Of course this raises the question, why not just use Popen with the shell=True (keyword) option? This will let you pass a string (no splitting nor parsing) to the shell and still gather up the results to handle as you wish. My example here won't process any pipelines, backticks, file descriptor redirection, etc that might be in the command, they'll all appear as literal arguments to the command. Thus it is still safer then running with shell=True ... I've given a silly example of checking the command against some sort of "approved command" dictionary or set --- through it would make more sense to normalize that into an absolute path unless you intend to require that the arguments be normalized prior to passing the command string to this function.
Just wrote this for generic full outer cross ref
create table #XRefDBs(xtype varchar(2),SourceDB varchar(100), Object varchar(100), RefDB varchar(100))
declare @sourcedbname varchar(100),
@searchfordbname varchar(100),
@sql nvarchar(4000)
declare curs cursor for
select name
from sysdatabases
where dbid>4
open curs
fetch next from curs into @sourcedbname
while @@fetch_status=0
begin
print @sourcedbname
declare curs2 cursor for
select name
from sysdatabases
where dbid>4
and name <> @sourcedbname
open curs2
fetch next from curs2 into @searchfordbname
while @@fetch_status=0
begin
print @searchfordbname
set @sql =
'INSERT INTO #XRefDBs (xtype,SourceDB,Object, RefDB)
select DISTINCT o.xtype,'''+@sourcedbname+''', o.name,'''+@searchfordbname+'''
from '+@sourcedbname+'.dbo.syscomments c
join '+@sourcedbname+'.dbo.sysobjects o on c.id=o.id
where o.xtype in (''V'',''P'',''FN'',''TR'')
and (text like ''%'+@searchfordbname+'.%''
or text like ''%'+@searchfordbname+'].%'')'
print @sql
exec sp_executesql @sql
fetch next from curs2 into @searchfordbname
end
close curs2
deallocate curs2
fetch next from curs into @sourcedbname
end
close curs
deallocate curs
select * from #XRefDBs
public string HtmlAgi(string url, string key)
{
var Webget = new HtmlWeb();
var doc = Webget.Load(url);
HtmlNode ourNode = doc.DocumentNode.SelectSingleNode(string.Format("//meta[@name='{0}']", key));
if (ourNode != null)
{
return ourNode.GetAttributeValue("content", "");
}
else
{
return "not fount";
}
}
You need to tell Eclipse which JDK/JRE's you have installed and where they are located.
This is somewhat burried in the Eclipse preferences: In the Window-Menu select "Preferences". In the Preferences Tree, open the Node "Java" and select "Installed JRE's". Then click on the "Add"-Button in the Panel and select "Standard VM", "Next" and for "JRE Home" click on the "Directory"-Button and select the top level folder of the JDK you want to add.
Its easier than the description may make it look.
If the view is embedded at all in a UIScrollView
then you can use the following:
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
The former will animate the keyboard off screen when the table view is scrolled and the later will hide the keyboard like the stock Messages app.
Note that these are are available on iOS 7.0 or above.
If your arguments are the same type you could use varargs:
public int something(int... args) {
int a = 0;
int b = 0;
if (args.length > 0) {
a = args[0];
}
if (args.length > 1) {
b = args[1];
}
return a + b
}
but this way you lose the semantics of the individual arguments, or
have a method overloaded which relays the call to the parametered version
public int something() {
return something(1, 2);
}
or if the method is part of some kind of initialization procedure, you could use the builder pattern instead:
class FoodBuilder {
int saltAmount;
int meatAmount;
FoodBuilder setSaltAmount(int saltAmount) {
this.saltAmount = saltAmount;
return this;
}
FoodBuilder setMeatAmount(int meatAmount) {
this.meatAmount = meatAmount;
return this;
}
Food build() {
return new Food(saltAmount, meatAmount);
}
}
Food f = new FoodBuilder().setSaltAmount(10).build();
Food f2 = new FoodBuilder().setSaltAmount(10).setMeatAmount(5).build();
Then work with the Food object
int doSomething(Food f) {
return f.getSaltAmount() + f.getMeatAmount();
}
The builder pattern allows you to add/remove parameters later on and you don't need to create new overloaded methods for them.
Use changelists. The advantage over specifying files is that you can visualize and confirm everything you wanted is actually included before you commit.
$ svn changelist fix-issue-237 foo.c
Path 'foo.c' is now a member of changelist 'fix-issue-237'.
That done, svn now keeps things separate for you. This helps when you're juggling multiple changes
$ svn status
A bar.c
A baz.c
--- Changelist 'fix-issue-237':
A foo.c
Finally, tell it to commit what you wanted changed.
$ svn commit --changelist fix-issue-237 -m "Issue 237"
This warning comes because your dataframe x
is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.
You can either create a proper dataframe
out of x by doing
x = x.copy()
This will remove the warning, but it is not the proper way
You should be using the DataFrame.loc
method, as the warning suggests, like this:
x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)
You can also use
cd %localhost%
to set the directory to the folder the batch file was opened from. Your script would look like this:
@echo off
cd %localhost%
echo .> dblank.txt
Make sure you set the directory before you use the command to create the text file.
Try:
var selectedVal;
for( i = 0; i < document.form_name.gender.length; i++ )
{
if(document.form_name.gender[i].checked)
selectedVal = document.form_name.gender[i].value; //male or female
break;
}
}
your_field DATETIME NULL DEFAULT NULL
INSERT INTO x(your_field)VALUES(NULL)
Answers here seem outdated. Pandas now has a factorize()
function and you can create categories as:
df.col.factorize()
Function signature:
pandas.factorize(values, sort=False, na_sentinel=- 1, size_hint=None)
The file extension .command is assigned to Terminal.app. Double-clicking on any .command file will execute it.
Use this cmd to display the packages in your device (for windows users)
adb shell pm list packages
then you can delete completely the package with the following cmd
adb uninstall com.example.myapp
Short answer: No, the statement in the currently accepted answer is NOT accurate: "The general consensus is that you do not (should not) need to dispose of HttpClient".
Long answer: BOTH of the following statements are true and achieveable at the same time:
IDisposable
object is supposed/recommended to be disposed.And they DO NOT NECESSARILY CONFLICT with each other. It is just a matter of how you organize your code to reuse an HttpClient
AND still dispose it properly.
An even longer answer quoted from my another answer:
It is not a coincidence to see people
in some blog posts blaming how HttpClient
's IDisposable
interface
makes them tend to use the using (var client = new HttpClient()) {...}
pattern
and then lead to exhausted socket handler problem.
I believe that comes down to an unspoken (mis?)conception: "an IDisposable object is expected to be short-lived".
HOWEVER, while it certainly looks like a short-lived thing when we write code in this style:
using (var foo = new SomeDisposableObject())
{
...
}
the official documentation on IDisposable
never mentions IDisposable
objects have to be short-lived.
By definition, IDisposable is merely a mechanism to allow you to release unmanaged resources.
Nothing more. In that sense, you are EXPECTED to eventually trigger the disposal,
but it does not require you to do so in a short-lived fashion.
It is therefore your job to properly choose when to trigger the disposal, base on your real object's life cycle requirement. There is nothing stopping you from using an IDisposable in a long-lived way:
using System;
namespace HelloWorld
{
class Hello
{
static void Main()
{
Console.WriteLine("Hello World!");
using (var client = new HttpClient())
{
for (...) { ... } // A really long loop
// Or you may even somehow start a daemon here
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
With this new understanding, now we revisit that blog post,
we can clearly notice that the "fix" initializes HttpClient
once but never dispose it,
that is why we can see from its netstat output that,
the connection remains at ESTABLISHED state which means it has NOT been properly closed.
If it were closed, its state would be in TIME_WAIT instead.
In practice, it is not a big deal to leak only one connection open after your entire program ends,
and the blog poster still see a performance gain after the fix;
but still, it is conceptually incorrect to blame IDisposable and choose to NOT dispose it.
The code of Ellbar works! You need only add using.
1 - using Microsoft.AspNet.Identity;
And... the code of Ellbar:
2 - string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
With this code (in currentUser
), you work the general data of the connected user, if you want extra data... see this link
SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm:ss a");
h is used for AM/PM times (1-12).
H is used for 24 hour times (1-24).
a is the AM/PM marker
m is minute in hour
Note: Two h's will print a leading zero: 01:13 PM. One h will print without the leading zero: 1:13 PM.
Looks like basically everyone beat me to it already, but I digress
The same thing happened to me with the '–' character (long minus sign).
I used this simple replace so resolve it:
htmlText = htmlText.Replace('–', '-');
Try this:
@Override
public void onBackPressed() {
finish();
}
AssemblyVersion
Where other assemblies that reference your assembly will look. If this number changes, other assemblies have to update their references to your assembly! Only update this version, if it breaks backward compatibility. The AssemblyVersion
is required.
I use the format: major.minor. This would result in:
[assembly: AssemblyVersion("1.0")]
If you're following SemVer strictly then this means you only update when the major changes, so 1.0, 2.0, 3.0, etc.
AssemblyFileVersion
Used for deployment. You can increase this number for every deployment. It is used by setup programs. Use it to mark assemblies that have the same AssemblyVersion
, but are generated from different builds.
In Windows, it can be viewed in the file properties.
The AssemblyFileVersion is optional. If not given, the AssemblyVersion is used.
I use the format: major.minor.patch.build, where I follow SemVer for the first three parts and use the buildnumber of the buildserver for the last part (0 for local build). This would result in:
[assembly: AssemblyFileVersion("1.3.2.254")]
Be aware that System.Version names these parts as major.minor.build.revision
!
AssemblyInformationalVersion
The Product version of the assembly. This is the version you would use when talking to customers or for display on your website. This version can be a string, like '1.0 Release Candidate'.
The AssemblyInformationalVersion
is optional. If not given, the AssemblyFileVersion is used.
I use the format: major.minor[.patch] [revision as string]. This would result in:
[assembly: AssemblyInformationalVersion("1.0 RC1")]
1 - @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
<input type="date" "myDate">
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
var today = new Date();
$('#myDate').val(today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2));
2 - @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
<input type="datatime-local" id="myLocalDataTime" step="1">
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
var today = new Date();
$('#myLocalDataTime').val(today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2)+'T'+today.getHours()+':'+today.getMinutes());
Frames were not deprecated in HTML5, but were deprecated in XHTML 1.1 Strict and 2.0, but remained in XHTML Transitional and returned in HTML5. Also here is an interesting article on using CSS to mimic frames without frames. I just tested it in IE 8, FF 3, Opera 11, Safari 5, Chrome 8. I love frames, but they do have their problems, particularly with search engines, bookmarks and printing and with CSS you can create print or display only content. I'm hoping to upgrade Alex's XHTML/CSS frame without frames solution to HTML5/CSS3.
Renaming .bashrc
to .profile
(or soft-linking the latter to the former) should also do the trick. See here.
As well as using Package manager console to get nuget to update the project with Install-Package Microsoft.AspNet.WebApi.WebHost for missing GlobalConfiguration,
I needed Install-Package Microsoft.AspNet.WebApi.SelfHost for missing using System.Web.Http;
public string BuildAbsolute(PathString path, QueryString query = default(QueryString), FragmentString fragment = default(FragmentString))
{
var rq = httpContext.Request;
return Microsoft.AspNetCore.Http.Extensions.UriHelper.BuildAbsolute(rq.Scheme, rq.Host, rq.PathBase, path, query, fragment);
}
Correctly written Windows apps that want to save their location from run to run will save the results of GetWindowPlacement()
before shutting down, then use SetWindowPlacement()
on startup to restore their position.
Frequently, apps will store the results of GetWindowPlacement()
in the registry as a REG_BINARY
for easy use.
The WINDOWPLACEMENT
route has many advantages over other methods:
SetWindowPlacement()
will automatically ensure that the window is not entirely offscreenFinally, programs that handle window restoration properly will take into account the nCmdShow
parameter passed in from the shell. This parameter is set in the shortcut that launches the application (Normal, Minimized, Maximize):
if(nCmdShow != SW_SHOWNORMAL)
placement.showCmd = nCmdShow; //allow shortcut to override
For non-Win32 applications, it's important to be sure that the method you're using to save/restore window position eventually uses the same underlying call, otherwise (like Java Swing's setBounds()
/getBounds()
problem) you'll end up writing a lot of extra code to re-implement functionality that's already there in the WINDOWPLACEMENT
functions.
Just a few (others have suggested some of these)
Method 1:
''.join(i for i in myStr if not i.isdigit())
Method 2:
def removeDigits(s):
answer = []
for char in s:
if not char.isdigit():
answer.append(char)
return ''.join(char)
Method 3:
''.join(filter(lambda x: not x.isdigit(), mystr))
Method 4:
nums = set(map(int, range(10)))
''.join(i for i in mystr if i not in nums)
Method 5:
''.join(i for i in mystr if ord(i) not in range(48, 58))
Try using an AppSettingsSection
instead of a NameValueCollection
. Something like this:
var section = (AppSettingsSection)config.GetSection(sectionName);
string results = section.Settings[key].Value;
public class TryReverse {
public static void main(String[] args) {
int [] array = {2,3,4,5,6,7,8,9};
reverse(array);
for(int i=0; i<array.length; ++i)
System.out.print(array[i] + " ");
}
public static void reverse (int [] array){
for(int start=0, end=array.length-1; start<=end; start++, end--){
int aux = array[start];
array[start]=array[end];
array[end]=aux;
}
}
}
From Oracle documentation page on ScheduledThreadPoolExecutor
A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required.
ExecutorService/ThreadPoolExecutor
or ScheduledThreadPoolExecutor
is obvious choice when you have multiple worker threads.
Pros of ExecutorService
over Timer
Timer
can't take advantage of available CPU cores unlike ExecutorService
especially with multiple tasks using flavours of ExecutorService
like ForkJoinPoolExecutorService
provides collaborative API if you need coordination between multiple tasks. Assume that you have to submit N number of worker tasks and wait for completion of all of them. You can easily achieve it with invokeAll API. If you want to achieve the same with multiple Timer
tasks, it would be not simple. ThreadPoolExecutor provides better API for management of Thread life cycle.
Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks
Few advantages:
a. You can create/manage/control life cycle of Threads & optimize thread creation cost overheads
b. You can control processing of tasks ( Work Stealing, ForkJoinPool, invokeAll) etc.
c. You can monitor the progress and health of threads
d. Provides better exception handling mechanism
<?php echo substr($string, 0, strlen($string) - 3); ?>
Use [[:digit:]]
(note the double brackets) as the pattern:
$ hello=ho02123ware38384you443d34o3434ingtod38384day
$ echo ${hello//[[:digit:]]/}
howareyoudoingtodday
Just wanted to summarize the answers (especially @nickl-'s https://stackoverflow.com/a/22261334/2916086).
SELECT username FROM all_users ORDER BY username;
If you have content with height unknown but you know the height the of container. The following solution works extremely well.
HTML
<div class="center-test">
<span></span><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Nesciunt obcaecati maiores nulla praesentium amet explicabo ex iste asperiores
nisi porro sequi eaque rerum necessitatibus molestias architecto eum velit
recusandae ratione.</p>
</div>
CSS
.center-test {
width: 300px;
height: 300px;
text-align:
center;
background-color: #333;
}
.center-test span {
height: 300px;
display: inline-block;
zoom: 1;
*display: inline;
vertical-align: middle;
}
.center-test p {
display: inline-block;
zoom: 1;
*display: inline;
vertical-align: middle;
color: #fff;
}
EXAMPLE http://jsfiddle.net/thenewconfection/eYtVN/
One gotcha for newby's to display: inline-block; [span] and [p] have no html white space so that the span then doesn't take up any space. Also I've added in the CSS hack for display inline-block for IE. Hope this helps someone!
If you want to append this css
file to header
you can do it using mounted()
function of the vue file. See the example.
Note: Assume you can access the css
file as http://www.yoursite/assets/styles/vendor.css
in the browser.
mounted() {
let style = document.createElement('link');
style.type = "text/css";
style.rel = "stylesheet";
style.href = '/assets/styles/vendor.css';
document.head.appendChild(style);
}
@Entity
@NamedQuery(name = "Customer.listUniqueNames",
query = "SELECT DISTINCT c.name FROM Customer c")
public class Customer {
...
private String name;
public static List<String> listUniqueNames() {
return = getEntityManager().createNamedQuery(
"Customer.listUniqueNames", String.class)
.getResultList();
}
}
I use this method in writing batch files for testing.
echo %userdomain%\%username%
Since you must include the password in plain text if authentication is required, I will only use it in a completely private environment where other users cannot view it or if a user seeing the password would bear no consequences.
Hope this helps someone out.
I think we can do this with one line simple command
for i in `grep -rl eth0 . 2> /dev/null`; do sed -i ‘s/eth0/eth1/’ $i; done
Refer to this page.
If you're connecting to a named instance and UDP is not available when connecting to it, then you may need to specify the protocol as well.
Example: tcp:192.168.1.21\SQL2K5,1443
My Suggestion best way use comments in JSP page <%-- Comment --%>
. Because It will not displayed (will not rendered in HTML pages) in client browsers.
an even better way would be to catch the input event on the input itself rather than on the whole form (performance wise) :
<input type="range" id="rangeInput" name="rangeInput" min="0" max="20" value="0"
oninput="amount.value=rangeInput.value">
<output id="amount" name="amount" for="rangeInput">0</output>
Here's a fiddle (with the id
added as per Ryan's comment).
The easiest way is to redirect the output of the echo
by >>
:
echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile
Where is your gcc
?
My gcc
is in "C:\Program Files\CodeBlocks\MinGW\bin\".
"C:\Program Files\CodeBlocks\MinGW\bin\gcc" -c "foo.c"
"C:\Program Files\CodeBlocks\MinGW\bin\gcc" "foo.o" -o "foo 01.exe"
For checkbox with an id
<input id="id_input_checkbox13" type="checkbox"></input>
you can simply do
$("#id_input_checkbox13").prop('checked')
you will get true
or false
as return value for above syntax. You can use it in if clause as normal boolean expression.
Similar to what binnyb suggested, you might consider using the newer Calendar > GregorianCalendar method. See these more recent docs:
http://download.oracle.com/javase/6/docs/api/java/util/GregorianCalendar.html
Just for reference's sake. This is how to do it with JQuery (useful for instance when you cannot query by element id):
$('#iframe').get(0).contentWindow.document.body.innerHTML
<asp:TemplateField HeaderText="ExEmp" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
FooterStyle-BackColor="BurlyWood" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:TextBox ID="txtNoOfExEmp" runat="server" CssClass="form-control input-sm m-bot15"
Font-Bold="true" onkeypress="return isNumberKey(event)" Text='<%#Bind("ExEmp") %>'></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" Width="50px" />
<FooterTemplate>
<asp:Label ID="lblTotNoOfExEmp" Font-Bold="true" runat="server" Text="0" CssClass="form-label"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
private void TotalExEmpOFMonth()
{
Label lbl_TotNoOfExEmp = (Label)GrdPFRecord.FooterRow.FindControl("lblTotNoOfExEmp");
/*Sum of the Total Amount Of month*/
foreach (GridViewRow gvr in GrdPFRecord.Rows)
{
TextBox txt_NoOfExEmp = (TextBox)gvr.FindControl("txtNoOfExEmp");
lbl_TotNoOfExEmp.Text = (Convert.ToDouble(txt_NoOfExEmp.Text) + Convert.ToDouble(lbl_TotNoOfExEmp.Text)).ToString();
lbl_TotNoOfExEmp.Text = string.Format("{0:F0}", Decimal.Parse(lbl_TotNoOfExEmp.Text));
}
}
I know that is a old question, but...
You can also use this in your class:
@Autowired
private HttpServletRequest context;
And this will provide the current instance of HttpServletRequest
for you use on your method.
"AND" does not work in my PHP code.
Server's version maybe?
"&&" works fine.
Most of the answers here are either 'UnSafe" or not LittleEndian safe. BitConverter is not LittleEndian safe. So building on an example in here (see the post by PZahra) I made a LittleEndian safe version simply by reading the byte array in reverse when BitConverter.IsLittleEndian == true
void Main(){
Console.WriteLine(BitConverter.IsLittleEndian);
byte[] bytes = BitConverter.GetBytes(0xdcbaabcdfffe1608);
//Console.WriteLine(bytes);
string hexStr = ByteArrayToHex(bytes);
Console.WriteLine(hexStr);
}
public static string ByteArrayToHex(byte[] data)
{
char[] c = new char[data.Length * 2];
byte b;
if(BitConverter.IsLittleEndian)
{
//read the byte array in reverse
for (int y = data.Length -1, x = 0; y >= 0; --y, ++x)
{
b = ((byte)(data[y] >> 4));
c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(data[y] & 0xF));
c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
}
else
{
for (int y = 0, x = 0; y < data.Length; ++y, ++x)
{
b = ((byte)(data[y] >> 4));
c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(data[y] & 0xF));
c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
}
return String.Concat("0x",new string(c));
}
It returns this:
True
0xDCBAABCDFFFE1608
which is the exact hex that went into the byte array.
Honestly the easiest way was to add file hosting to the server.
Open IIS
Add a Virtual Directory under Default Web Site
Add the appropriate permissions to the folder on the C: drive for "NETWORK SERVICE" and "IIS AppPool\DefaultAppPool"
Refresh Default Web Site
And you're done. You can now browse to any image in that folder by navigating to http://yourServerName/whateverYourFolderNameIs/yourImage.jpg and use that url in your img src
Hope this helps someone
According to the matplotlib legend documentation:
The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).
Thus, one could use:
plt.legend(loc=(x, y))
to set the legend's lower left corner to the specified (x, y)
position.
After hours of searching I think my problem was that command yum install php-soap
installs the latest version of soap for the latest php version.
My php version was 7.027
, but latest php version is 7.2
so I had to search for the right soap version and finaly found it HERE!
yum install rh-php70-php-soap
Now php -m | grep -i soap
works, Output: soap
Do not forget to restart httpd
service.
Came across this looking for something else.
While the post looks fairly old, the easiest solution in bash is illustrated below (at least bash 4) using set -- "${@:#}"
where # is the starting number of the array element we want to preserve forward:
#!/bin/bash
someVar="${1}"
someOtherVar="${2}"
set -- "${@:3}"
input=${@}
[[ "${input[*],,}" == *"someword"* ]] && someNewVar="trigger"
echo -e "${someVar}\n${someOtherVar}\n${someNewVar}\n\n${@}"
Basically, the set -- "${@:3}"
just pops off the first two elements in the array like perl's shift and preserves all remaining elements including the third. I suspect there's a way to pop off the last elements as well.
Just throwing this out there, but try retyping things manually. There's a chance that your quotation marks are the "wrong" ones as there's a similar unicode character which looks similar but is NOT a quotation mark.
If you copy/pasted the code snippits off a website, that might be your problem.
Un updated answer: in knitr 1.17
you can simply use
![Image Title](path/to/your/image){width=250px}
edit as per comment from @jsb
Note this works only without spaces, e.g. {width=250px} not {width = 250px}
time.second helps a lot put that at the top of your python.