For everyone else who has no duplicate Listen directives and no running processes on the port: check that you don't accidentally include ports.conf twice in apache2.conf (as I did due to a bad merge).
Go to
Tools > Android > (Uncheck) Enable ADB Integration (if studio hangs/gets stuck end adb process manually)
then,
Tools > Android > (Check) Enable ADB Integration
Stream audio in realtime without waiting for recording to end: https://github.com/noamtcohen/AudioStreamer
This streams PCM data but you could modify the code to stream mp3 or Speex
For Linux: (data excluded)
pg_dump -s -t tablename databasename > dump.sql
(For a specific table in database)
pg_dump -s databasename > dump.sql
(For the entire database)
Alternatively YUI has http://yuilibrary.com/yui/docs/api/classes/QueryString.html#method_stringify.
For example:
var data = { one: 'first', two: 'second' };
var result = Y.QueryString.stringify(data);
in your build.gradle add the following to the end of the android node
android {
....
....
sourceSets {
main.java.srcDirs += 'src/main/<YOUR DIRECTORY>'
}
}
The best solution for me is an extension with a function. Create a swift file with this extension
First is the UIWindow extension:
public extension UIWindow {
var visibleViewController: UIViewController? {
return UIWindow.visibleVC(vc: self.rootViewController)
}
static func visibleVC(vc: UIViewController?) -> UIViewController? {
if let navigationViewController = vc as? UINavigationController {
return UIWindow.visibleVC(vc: navigationViewController.visibleViewController)
} else if let tabBarVC = vc as? UITabBarController {
return UIWindow.visibleVC(vc: tabBarVC.selectedViewController)
} else {
if let presentedVC = vc?.presentedViewController {
return UIWindow.visibleVC(vc: presentedVC)
} else {
return vc
}
}
}
}
inside that file add function
func visibleViewController() -> UIViewController? {
let appDelegate = UIApplication.shared.delegate
if let window = appDelegate!.window {
return window?.visibleViewController
}
return nil
}
And if you want to use it, you can call it anywhere. Example:
override func viewDidLoad() {
super.viewDidLoad()
if let topVC = visibleViewController() {
//show some label or text field
}
}
File code is like this:
import UIKit
public extension UIWindow {
var visibleViewController: UIViewController? {
return UIWindow.visibleVC(vc: self.rootViewController)
}
static func visibleVC(vc: UIViewController?) -> UIViewController? {
if let navigationViewController = vc as? UINavigationController {
return UIWindow.visibleVC(vc: navigationViewController.visibleViewController)
} else if let tabBarVC = vc as? UITabBarController {
return UIWindow.visibleVC(vc: tabBarVC.selectedViewController)
} else {
if let presentedVC = vc?.presentedViewController {
return UIWindow.visibleVC(vc: presentedVC)
} else {
return vc
}
}
}
}
func visibleViewController() -> UIViewController? {
let appDelegate = UIApplication.shared.delegate
if let window = appDelegate!.window {
return window?.visibleViewController
}
return nil
}
The problem is here:
answer = newList.sort()
sort
does not return the sorted list; rather, it sorts the list in place.
Use:
answer = sorted(newList)
If you're using Django installed you can also try filesizeformat:
from django.template.defaultfilters import filesizeformat
filesizeformat(1073741824)
=>
"1.0 GB"
You can use strtotime() for time calculation. Here is an example:
$checkTime = strtotime('09:00:59');
echo 'Check Time : '.date('H:i:s', $checkTime);
echo '<hr>';
$loginTime = strtotime('09:01:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!'; echo '<br>';
echo 'Time diff in sec: '.abs($diff);
echo '<hr>';
$loginTime = strtotime('09:00:59');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
echo '<hr>';
$loginTime = strtotime('09:00:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
Check the already-asked question - how to get time difference in minutes:
Subtract the past-most one from the future-most one and divide by 60.
Times are done in unix format so they're just a big number showing the number of seconds from January 1 1970 00:00:00 GMT
I created this method, it is ideal because it aborts the connection without downloading it in its entirety, ideal for checking if videos or large images exist, decreasing the response time and the need to download the entire file
// if-url-exist.js v1
function ifUrlExist(url, callback) {
let request = new XMLHttpRequest;
request.open('GET', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Accept', '*/*');
request.onprogress = function(event) {
let status = event.target.status;
let statusFirstNumber = (status).toString()[0];
switch (statusFirstNumber) {
case '2':
request.abort();
return callback(true);
default:
request.abort();
return callback(false);
};
};
request.send('');
};
Example of use:
ifUrlExist(url, function(exists) {
console.log(exists);
});
Float the #list
and #similar
the right and add clear: right;
to #similar
Like so:
#map { float:left; width:700px; height:500px; }
#list { float:right; width:200px; background:#eee; list-style:none; padding:0; }
#similar { float:right; width:200px; background:#000; clear:right; }
<div id="map"></div>
<ul id="list"></ul>
<div id="similar">this text should be below, not next to ul.</div>
You might need a wrapper(div) around all of them though that's the same width of the left and right element.
I was getting this error; I just put a WHERE
clause for the field which was used within count
clause. it solved the issue. Note: if null value exist, check whether its critical for the report, as its excluded in the count.
Old query:
select city, Count(Emp_ID) as Emp_Count
from Emp_DB
group by city
New query:
select city, Count(Emp_ID) as Emp_Count
from Emp_DB
where Emp_ID is not null
group by city
There is a Hidden
helper alongside HiddenFor
which lets you set the value.
@Html.Hidden("RequiredProperty", "default")
EDIT Based on the edit you've made to the question, you could do this, but I believe you're moving into territory where it will be cheaper and more effective, in the long run, to fight for making the code change. As has been said, even by yourself, the controller or view model should be setting the default.
This code:
<ul>
@{
var stacks = new System.Diagnostics.StackTrace().GetFrames();
foreach (var frame in stacks)
{
<li>@frame.GetMethod().Name - @frame.GetMethod().DeclaringType</li>
}
}
</ul>
Will give output like this:
Execute - ASP._Page_Views_ViewDirectoryX__SubView_cshtml
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
ExecutePageHierarchy - System.Web.Mvc.WebViewPage
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
RenderView - System.Web.Mvc.RazorView
Render - System.Web.Mvc.BuildManagerCompiledView
RenderPartialInternal - System.Web.Mvc.HtmlHelper
RenderPartial - System.Web.Mvc.Html.RenderPartialExtensions
Execute - ASP._Page_Views_ViewDirectoryY__MainView_cshtml
So assuming the MVC framework will always go through the same stack, you can grab var frame = stacks[8];
and use the declaring type to determine who your parent view is, and then use that determination to set (or not) the default value. You could also walk the stack instead of directly grabbing [8]
which would be safer but even less efficient.
Moving to local folder is the quickest solution, nothing else worked for me esp because I was not admin on my system (can't edit registery etc), which is a typical case in a work environment.
Create a folder in C:\help drive, lets call it help and copy the files there and open.
Do not copy to mydocuments or anywhere else, those locations are usually on network drive in office setup and will not work.
Change your positioning a bit:
.container {
border: 1px solid #DDDDDD;
width: 200px;
height: 200px;
position:relative;
}
.tag {
float: left;
position: absolute;
left: 0px;
top: 0px;
background-color: green;
}
You need to set relative positioning on the container and then absolute on the inner tag div. The inner tag's absolute positioning will be with respect to the outer relatively positioned div. You don't even need the z-index rule on the tag div.
Below worked for me.
Height & width are taken to show that, if you 2 such children, it will scroll horizontally, since height of child is greater than height of parent scroll vertically.
Parent CSS:
.divParentClass {
width: 200px;
height: 100px;
overflow: scroll;
white-space: nowrap;
}
Children CSS:
.divChildClass {
width: 110px;
height: 200px;
display: inline-block;
}
To scroll horizontally only:
overflow-x: scroll;
overflow-y: hidden;
To scroll vertically only:
overflow-x: hidden;
overflow-y: scroll;
To describe the "paradigm shift", I think a short answer can suffice.
In jQuery, you typically use selectors to find elements, and then wire them up:
$('#id .class').click(doStuff);
In AngularJS, you use directives to mark the elements directly, to wire them up:
<a ng-click="doStuff()">
AngularJS doesn't need (or want) you to find elements using selectors - the primary difference between AngularJS's jqLite versus full-blown jQuery is that jqLite does not support selectors.
So when people say "don't include jQuery at all", it's mainly because they don't want you to use selectors; they want you to learn to use directives instead. Direct, not select!
From cmd (Windows):
C\Users\You> `vim foo.txt`
Now in Vim, enter command mode by typing: ":" (i.e. Shift + ;)
:tabedit $HOME/.vimrc
You may want to use window.onload, as the docs indicate that it's not fired until both the DOM is ready and ALL of the other assets in the page (images, etc.) are loaded.
Boolean primitive type is atomic for write and read operations, volatile guarantees the happens-before principle. So if you need a simple get() and set() then you don't need the AtomicBoolean.
On the other hand if you need to implement some check before setting the value of a variable, e.g. "if true then set to false", then you need to do this operation atomically as well, in this case use compareAndSet and other methods provided by AtomicBoolean, since if you try to implement this logic with volatile boolean you'll need some synchronization to be sure that the value has not changed between get and set.
I tried literally everything to get this working.
I found that for some reason, changes to objects from $store
don't necessarily trigger a .watch
method. My workaround was to
state
to act as a flag, which does propagate changes to a Component when watched$store.mutators
to alter the complex dataset and increment the counter flag$store.state
flag. When change is detected, update locally relevant reactive changes from the $store.state
complex data set$store.state
's dataset using our $store.mutators
methodThis is implemented something like this:
Store
let store = Vuex.Store({
state: {
counter: 0,
data: { someKey: 0 }
},
mutations: {
updateSomeKey(state, value) {
update the state.data.someKey = value;
state.counter++;
}
}
});
Component
data: {
dataFromStoreDataSomeKey: null,
someLocalValue: 1
},
watch: {
'$store.state.counter': {
immediate: true,
handler() {
// update locally relevant data
this.someLocalValue = this.$store.state.data.someKey;
}
}
},
methods: {
updateSomeKeyInStore() {
this.$store.commit('updateSomeKey', someLocalValue);
}
It's convoluted but basically here we are watching for a flag to change and then updating local data to reflect important changes in an object that's stored in the $state
Vue.config.devtools = false
const store = new Vuex.Store({
state: {
voteCounter: 0,
// changes to objectData trigger a watch when keys are added,
// but not when values are modified?
votes: {
'people': 0,
'companies': 0,
'total': 0,
},
},
mutations: {
vote(state, position) {
state.votes[position]++;
state.voteCounter++;
}
},
});
app = new Vue({
el: '#app',
store: store,
data: {
votesForPeople: null,
votesForCompanies: null,
pendingVote: null,
},
computed: {
totalVotes() {
return this.votesForPeople + this.votesForCompanies
},
peoplePercent() {
if (this.totalVotes > 0) {
return 100 * this.votesForPeople / this.totalVotes
} else {
return 0
}
},
companiesPercent() {
if (this.totalVotes > 0) {
return 100 * this.votesForCompanies / this.totalVotes
} else {
return 0
}
},
},
watch: {
'$store.state.voteCounter': {
immediate: true,
handler() {
// clone relevant data locally
this.votesForPeople = this.$store.state.votes.people
this.votesForCompanies = this.$store.state.votes.companies
}
}
},
methods: {
vote(event) {
if (this.pendingVote) {
this.$store.commit('vote', this.pendingVote)
}
}
}
})
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://unpkg.com/[email protected]/dist/vuex.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<div id="app">
<form @submit.prevent="vote($event)">
<div class="form-check">
<input
class="form-check-input"
type="radio"
name="vote"
id="voteCorps"
value="companies"
v-model="pendingVote"
>
<label class="form-check-label" for="voteCorps">
Equal rights for companies
</label>
</div>
<div class="form-check">
<input
class="form-check-input"
type="radio"
name="vote"
id="votePeople"
value="people"
v-model="pendingVote"
>
<label class="form-check-label" for="votePeople">
Equal rights for people
</label>
</div>
<button
class="btn btn-primary"
:disabled="pendingVote==null"
>Vote</button>
</form>
<div
class="progress mt-2"
v-if="totalVotes > 0"
>
<div class="progress-bar"
role="progressbar"
aria-valuemin="0"
:style="'width: ' + peoplePercent + '%'"
:aria-aluenow="votesForPeople"
:aria-valuemax="totalVotes"
>People</div>
<div
class="progress-bar bg-success"
role="progressbar"
aria-valuemin="0"
:style="'width: ' + companiesPercent + '%'"
:aria-valuenow="votesForCompanies"
:aria-valuemax="totalVotes"
>Companies</div>
</div>
</div>
_x000D_
The following solution works well when you want to move the text closer to the bullet and even if you have multiple lines of text.
margin-right
allows you to move the text closer to the bullet
text-indent
ensures that multiple lines of text still line up correctly
li:before {_x000D_
content: "";_x000D_
margin-right: -5px; /* Adjust this to move text closer to the bullet */_x000D_
}_x000D_
_x000D_
li {_x000D_
text-indent: 5px; /* Aligns second line of text */_x000D_
}
_x000D_
<ul>_x000D_
<li> Item 1 ... </li>_x000D_
<li> Item 2 ... this item has tons and tons of text that causes a second line! Notice how even the second line is lined up with the first!</li>_x000D_
<li> Item 3 ... </li>_x000D_
</ul>
_x000D_
Aren't you performing the operations in the wrong order? You requirement seems to be foo[:-3].replace(" ", "").upper()
You could implement a onActivityResult in Class B as well and launch Class C using startActivityForResult. Once you get the result in Class B then set the result there (for Class A) based on the result from Class C. I haven't tried this out but I think this should work.
Another thing to look out for is that Activity A should not be a singleInstance activity. For startActivityForResult to work your Class B needs to be a sub activity to Activity A and that is not possible in a single instance activity, the new Activity (Class B) starts in a new task.
I got the error as, "svn: Commit blocked by pre-commit hook (exit code 1) with output: Failed with exception: Lost connection to MySQL server at 'reading initial communication packet', system error: 104."
I tried 'svn commit' after 'svn cleanup'. And It works fine!.
Based on gniourf_gniourf’s answer,
find "file.txt" -size -90k
will write file.txt
to stdout if and only if the size of file.txt
is less than 90K, and
find "file.txt" -size -90k -exec command \;
will execute the command command
if file.txt
has a size less than 90K.
I have tested this on Linux.
From find(1)
,
… Command-line arguments following (the
-H
,-L
and-P
options) are taken to be names of files or directories to be examined, up to the first argument that begins with ‘-’, …
(emphasis added).
If you're using MySQL and want the database itself to perform the conversion, use this:
If you prefer to format using Java, use this:
SimpleDateFormat dateFormat = new SimpleDateFormat("M/dd/yyyy");
dateFormat.format( new Date() );
To turn off line numbering, again follow the preceding instructions, except this time enter the following line at the : prompt:
set nonumber
Use LinearLayout.LayoutParams
:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
Button button = new Button(this);
button.setLayoutParams(params);
EDIT: Ah, Erich's answer is easier!
You're allowed to have more than one return
statement, so it's legal to write
if (some_condition) {
return true;
}
return false;
It's also unnecessary to compare boolean values to true
or false
, so you can write
if (verifyPwd()) {
// do_task
}
Edit: Sometimes you can't return early because there's more work to be done. In that case you can declare a boolean variable and set it appropriately inside the conditional blocks.
boolean success = true;
if (some_condition) {
// Handle the condition.
success = false;
} else if (some_other_condition) {
// Handle the other condition.
success = false;
}
if (another_condition) {
// Handle the third condition.
}
// Do some more critical things.
return success;
One more possible cause is this:
If you attempt to set the button's title in the (id)initWithNibName: ...
method, then you're button property will still be nil. It hasn't yet been assigned to the UIButton.
You must be sure that you're setting your buttons in a method like (void)viewWillLoad
or (void)viewWillAppear
, but you probably don't want to set them as late as (void)viewDidAppear
.
You can use .NET 4's dynamic type and built-in JavaScriptSerializer to do that. Something like this, maybe:
string json = "{\"items\":[{\"Name\":\"AAA\",\"Age\":\"22\",\"Job\":\"PPP\"},{\"Name\":\"BBB\",\"Age\":\"25\",\"Job\":\"QQQ\"},{\"Name\":\"CCC\",\"Age\":\"38\",\"Job\":\"RRR\"}]}";
var jss = new JavaScriptSerializer();
dynamic data = jss.Deserialize<dynamic>(json);
StringBuilder sb = new StringBuilder();
sb.Append("<table>\n <thead>\n <tr>\n");
// Build the header based on the keys in the
// first data item.
foreach (string key in data["items"][0].Keys) {
sb.AppendFormat(" <th>{0}</th>\n", key);
}
sb.Append(" </tr>\n </thead>\n <tbody>\n");
foreach (Dictionary<string, object> item in data["items"]) {
sb.Append(" <tr>\n");
foreach (string val in item.Values) {
sb.AppendFormat(" <td>{0}</td>\n", val);
}
}
sb.Append(" </tr>\n </tbody>\n</table>");
string myTable = sb.ToString();
At the end, myTable
will hold a string that looks like this:
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Job</th>
</tr>
</thead>
<tbody>
<tr>
<td>AAA</td>
<td>22</td>
<td>PPP</td>
<tr>
<td>BBB</td>
<td>25</td>
<td>QQQ</td>
<tr>
<td>CCC</td>
<td>38</td>
<td>RRR</td>
</tr>
</tbody>
</table>
Try this:
$str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}, $str);
In case it's UTF-16 based C/C++/Java/Json-style:
$str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UTF-16BE');
}, $str);
Yeah in simulator. Some times it wont recognise the selector there is a bug it seems. Even i faced not for your code , then i just changed the action name (selector). It works
let buttonPuzzle:UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
buttonPuzzle.backgroundColor = UIColor.greenColor()
buttonPuzzle.setTitle("Puzzle", forState: UIControlState.Normal)
buttonPuzzle.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
buttonPuzzle.tag = 22;
self.view.addSubview(buttonPuzzle)
Selector Function is Here:
func buttonAction(sender:UIButton!)
{
var btnsendtag:UIButton = sender
if btnsendtag.tag == 22 {
//println("Button tapped tag 22")
}
}
I also facing same problem it will be occur if your mysql server
is not running by default it will again stop after some sec so you again run ($ sudo service mysql start
) command you can change if know.
for that use command
$ sudo service mysql start
(put user password if required because we use sudo
)
and then run
$ sudo mysql -u root -p (put user password if required )
now you got your database
To do this task download.js library can be used. Here is an example from library docs:
download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////yH5BAAAAP8ALAAAAABGABUAAAj/AAEIHAgggMGDCAkSRMgwgEKBDRM+LBjRoEKDAjJq1GhxIMaNGzt6DAAypMORJTmeLKhxgMuXKiGSzPgSZsaVMwXUdBmTYsudKjHuBCoAIc2hMBnqRMqz6MGjTJ0KZcrz5EyqA276xJrVKlSkWqdGLQpxKVWyW8+iJcl1LVu1XttafTs2Lla3ZqNavAo37dm9X4eGFQtWKt+6T+8aDkxUqWKjeQUvfvw0MtHJcCtTJiwZsmLMiD9uplvY82jLNW9qzsy58WrWpDu/Lp0YNmPXrVMvRm3T6GneSX3bBt5VeOjDemfLFv1XOW7kncvKdZi7t/S7e2M3LkscLcvH3LF7HwSuVeZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==", "dlDataUrlBin.gif", "image/gif");
If you understand the difference between scope and session then it will be very easy to understand these methods.
A very nice blog post by Adam Anderson describes this difference:
Session means the current connection that's executing the command.
Scope means the immediate context of a command. Every stored procedure call executes in its own scope, and nested calls execute in a nested scope within the calling procedure's scope. Likewise, a SQL command executed from an application or SSMS executes in its own scope, and if that command fires any triggers, each trigger executes within its own nested scope.
Thus the differences between the three identity retrieval methods are as follows:
@@identity
returns the last identity value generated in this session but any scope.
scope_identity()
returns the last identity value generated in this session and this scope.
ident_current()
returns the last identity value generated for a particular table in any session and any scope.
Ubuntu has the option to install a headless Java -- this means without graphics libraries. This wasn't always the case, but I encountered this while trying to run a Java text editor on 10.10 the other day. Run the following command to install a JDK that has these libraries:
sudo apt-get install openjdk-6-jdk
EDIT: Actually, looking at my config, you might need the JRE. If that's the case, run:
sudo apt-get install openjdk-6-jre
Another variation of Iftah
var counter = 10;
var checkExist = setInterval(function() {
console.log(counter);
counter--
if ($('#the-canvas').length || counter === 0) {
console.log("by bye!");
clearInterval(checkExist);
}
}, 200);
Just in case the element is never shown, so we don't check infinitely.
As mentioned by Niels, this happens because the server process user can't write to the Wordpress folder.
But here's the thing a lot of articles don't explain. It's the owner of the php process, not the nginx process. If you try to change the nginx owner, it won't solve this.
To solve it, try running ps aux
to see which user owns the php-fpm process. Then check that user is the same user as the owner of the wordpress folder, or can at least write to it. If the user can't write to it, you'll need to change permissions and/or ownership of the folder; or put the two users (server owner and wordpress folder owner) in a common group which can write to the folder; or change php.ini "user" property to a user that can write to the folder.
I came here looking for the query string, not how to get values from the query string.
request.query_string
returns the URL parameters as raw byte string (Ref 1).
Example of using request.query_string
:
from flask import Flask, request
app = Flask(__name__)
@app.route('/data', methods=['GET'])
def get_query_string():
return request.query_string
if __name__ == '__main__':
app.run(debug=True)
Output:
References:
you attach the .onerror handler to the ajax object, why people insist on posting JQuery for responses when vanila works cross platform...
quickie example:
ajax = new XMLHttpRequest();
ajax.open( "POST", "/url/to/handler.php", true );
ajax.onerror = function(){
alert("Oops! Something went wrong...");
}
ajax.send(someWebFormToken );
I am using using Ubuntu.
Problem for me solved by using sudo in terminal with the command.
Use a regular for loop and format the index to be used in the selector.
var array = [];
for (var i = 0; i < 4; i++) {
var selector = '' + i;
if (selector.length == 1)
selector = '0' + selector;
selector = '#event' + selector;
array.push($(selector, response).html());
}
I wrapped the code of the best answers to the question into a single, reusable class extending UIImageView, so you can directly use asynchronous loading UIImageViews in your storyboard (or create them from code).
Here is my class:
import Foundation
import UIKit
class UIImageViewAsync :UIImageView
{
override init()
{
super.init(frame: CGRect())
}
override init(frame:CGRect)
{
super.init(frame:frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func getDataFromUrl(url:String, completion: ((data: NSData?) -> Void)) {
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) { (data, response, error) in
completion(data: NSData(data: data))
}.resume()
}
func downloadImage(url:String){
getDataFromUrl(url) { data in
dispatch_async(dispatch_get_main_queue()) {
self.contentMode = UIViewContentMode.ScaleAspectFill
self.image = UIImage(data: data!)
}
}
}
}
and here is how to use it:
imageView.downloadImage("http://www.image-server.com/myImage.jpg")
Your initial problem was:
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
var numPages: Int = { return categoriesPerPage.count }
}
Instance member 'categoriesPerPage' cannot be used on type 'ReportView'
previous posts correctly point out, if you want a computed property, the =
sign is errant.
Additional possibility for error:
If your intent was to "Setting a Default Property Value with a Closure or Function", you need only slightly change it as well. (Note: this example was obviously not intended to do that)
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
var numPages: Int = { return categoriesPerPage.count }()
}
Instead of removing the =
, we add ()
to denote a default initialization closure. (This can be useful when initializing UI code, to keep it all in one place.)
However, the exact same error occurs:
Instance member 'categoriesPerPage' cannot be used on type 'ReportView'
The problem is trying to initialize one property with the value of another. One solution is to make the initializer lazy
. It will not be executed until the value is accessed.
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
lazy var numPages: Int = { return categoriesPerPage.count }()
}
now the compiler is happy!
As I see no similar answer here - it is worth pointing out that with the usage of a (list / generator) comprehension, you can unpack those multiple values and assign them to multiple variables in a single line of code:
first_val, second_val = (myDict.get(key) for key in [first_key, second_key])
jQuery :
$("#data td").toggle(function(){
$(this).css('background-color','blue')
},function(){
$(this).css('background-color','ur_default_color')
});
LinkedList<String>list = new LinkedList<String>();
list.add("abc");
list.add("Bcd");
list.add("aAb");
list.sort(String::compareToIgnoreCase);
Another option would be using lambda expressions:
list.sort((o1, o2) -> o1.compareToIgnoreCase(o2));
I had a similar issue and found that it was much simpler to to get rid of the Excel files as soon as possible. As part of the first steps in my package I used Powershell to extract the data out of the Excel files into CSV files. My own Excel files were simple but here
Extract and convert all Excel worksheets into CSV files using PowerShell
is an excellent article by Tim Smith on extracting data from multiple Excel files and/or multiple sheets.
Once the Excel files have been converted to CSV the data import is much less complicated.
Instead of using pull-right
class, it is better to use text-right
class in the column, because pull-right
creates problems sometimes while resizing the page.
You can't. It's immediate mode graphics. But you can sort of simulate it by drawing a rectangle over it in the background color with an opacity.
If the image is over something other than a constant color, then it gets quite a bit trickier. You should be able to use the pixel manipulation methods in this case. Just save the area before drawing the image, and then blend that back on top with an opacity afterwards.
If we're willing to sacrifice the succinctness of Hayden's solution, one could also do something like this:
In [22]: orders_df['C'] = orders_df.Action.apply(
lambda x: (1 if x == 'Sell' else -1))
In [23]: orders_df # New column C represents the sign of the transaction
Out[23]:
Prices Amount Action C
0 3 57 Sell 1
1 89 42 Sell 1
2 45 70 Buy -1
3 6 43 Sell 1
4 60 47 Sell 1
5 19 16 Buy -1
6 56 89 Sell 1
7 3 28 Buy -1
8 56 69 Sell 1
9 90 49 Buy -1
Now we have eliminated the need for the if
statement. Using DataFrame.apply()
, we also do away with the for
loop. As Hayden noted, vectorized operations are always faster.
In [24]: orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.C
In [25]: orders_df # The resulting dataframe
Out[25]:
Prices Amount Action C Value
0 3 57 Sell 1 171
1 89 42 Sell 1 3738
2 45 70 Buy -1 -3150
3 6 43 Sell 1 258
4 60 47 Sell 1 2820
5 19 16 Buy -1 -304
6 56 89 Sell 1 4984
7 3 28 Buy -1 -84
8 56 69 Sell 1 3864
9 90 49 Buy -1 -4410
This solution takes two lines of code instead of one, but is a bit easier to read. I suspect that the computational costs are similar as well.
mvc:annotation-driven is a tag added in Spring 3.0 which does the following:
context:annotation-config Looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like @Autowired, @Resource, @Required, @PostConstruct etc etc.
The solution for me was setting the Graphics option on the Android Virtual Device to Software
instead of Automatic
or Hardware
.
I believe this was the solution because I am working on a windows machine that did not have a dedicated graphics card.
No, you shouldn't call those methods manually. At the end of the using
block the Dispose()
method is automatically called which will take care to free unmanaged resources (at least for standard .NET BCL classes such as streams, readers/writers, ...). So you could also write your code like this:
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
using (StreamWriter writer = new StreamWriter(filename))
{
int chunkSize = 1024;
while (!reader.EndOfStream)
{
char[] buffer = new char[chunkSize];
int count = reader.Read(buffer, 0, chunkSize);
if (count != 0)
{
writer.Write(buffer, 0, count);
}
}
}
The Close()
method calls Dispose()
.
Turns out you can't use the root
user in 5.7 anymore without becoming a sudoer. That means you can't just run mysql -u root
anymore and have to do sudo mysql -u root
instead.
That also means that it will no longer work if you're using the root
user in a GUI (or supposedly any non-command line application). To make it work you'll have to create a new user with the required privileges and use that instead.
See this answer for more details.
I have generated 100 different colors of different contrast, and you can increase values according to your need:
Example on Feedle: http://jsfiddle.net/zFbfE/29/ -
// CHANGE THE INITIAL SEED HERE
Math.seed = 23;
/**
* Math.seededRandom()
*
*/
Math.seededRandom = function(max, min) {
max = max || 1;
min = min || 0;
Math.seed = (Math.seed * 9301 + 49297) % 233280;
var rnd = Math.seed / 233280.0;
return min + rnd * (max - min);
}
var c, r = 0,
l = 100000,
t,
random = [],
seededRandom = [];
for(var i=0; i<100; i++)
{
random[i] = 0;
seededRandom[i] = 0;
}
// Do some loops withouth benchmarking
// to have a "fair" comparison
/*for (c = 0; c < l; ++c) {
r = 5+5;
}*/
// benchmark Math.random()
t = new Date().getTime();
s = '';
// benchmark Math.seededRandom()
t = new Date().getTime();
while(l--){
r = Math.seededRandom();
seededRandom[(r*100)|0] += 1;
}
var inc = 0;
for(c=0; c<seededRandom.length; c++) {
//var inc=15;
for(var i=0; i<seededRandom.length; i++)
{
if(i!==c) {
if(seededRandom[c] == seededRandom[i]) {
seededRandom[c] += inc;
inc = inc + 10;
// console.log(seededRandom[c]);
}
}
}
inc = inc > 255 ? 0 : inc;
}
var a=[], b=[], d=[], inc=0, dec=255;
for(c=0; c<seededRandom.length; c++) {
a[c] = (seededRandom[c] % 100) + inc;
b[c] = dec - Math.floor(seededRandom[c]/100);
if(b[c] < 0)
b[c] = b[c]* - 1;
if(a[c] > 255)
a[c] -= 255;
d[c] = Math.floor(b[c]/2);
inc += 5;
dec -= 5;
}
var app = angular.module("myAppp", []).controller('myCtrl',function($scope, $http) {
$scope.id = [];
for(var i=0; i<seededRandom.length; i++)
$scope.id.push(i);
// Generate random number
$scope.Icon = [];$scope.Icon2 = [], $scope.Icon3 = [];
var ran = 0, inc = 5, dec = 255;
for(var i=0;i<seededRandom.length;i++)
{
$scope.Icon.push(a[i]%100);
$scope.Icon2.push(b[i]%100);
$scope.Icon3.push(d[i]%100);
console.log(a[i] + "|" + b[i] + "|" + d[i]);
}
});
It works for me and I think it would be helpful for you also.
One best thing in this example is, it will generate 100 random colors and colors would be same on every page load.
Apart from custom class or .Net 4.0 Tuples, since C# 7.0 there is a new feature called ValueTuple, which is a struct that can be used in this case. Instead of writing:
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
and access values through t.Item1
and t.Item2
, you can simply do it like that:
(string message, int count) = ("Hello", 4);
or even:
(var message, var count) = ("Hello", 4);
Can you assign a unique CSS class to each distinct timer? That way you could use the selector for the CSS class, which would work fine with multiple div
elements.
It is technically approved that MD5 is faster than SHA256 so in just verifying file integrity it will be sufficient and better for performance.
You are able to checkout the following resources:
It means that you're trying to insert into table2
a UserID
value that doesn't exist in table1
.
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
$array[9] = 'Apple';
$array[12] = 'Orange';
$array[5] = 'Peach';
$array = array_values($array);
through this function you can reset your array
$array[0] = 'Apple';
$array[1] = 'Orange';
$array[2] = 'Peach';
Here's how to do this with Pandas FWIW:
import pandas as pd
pd.date_range("1990/04/03", "2014/12/31", freq="MS")
DatetimeIndex(['1990-05-01', '1990-06-01', '1990-07-01', '1990-08-01',
'1990-09-01', '1990-10-01', '1990-11-01', '1990-12-01',
'1991-01-01', '1991-02-01',
...
'2014-03-01', '2014-04-01', '2014-05-01', '2014-06-01',
'2014-07-01', '2014-08-01', '2014-09-01', '2014-10-01',
'2014-11-01', '2014-12-01'],
dtype='datetime64[ns]', length=296, freq='MS')
Notice it starts with the month after the given start date.
This problem occurs when we set our app as unavailable to the public.
STEP 1
Open Facebook developer account
STEP 2
Select your application
STEP 3
Click the app Review tab.
Change switch value no to yes. See picture below.
After this your app is live.
I had two services running who were accidentally coupled to the same EventSource eventLog.Source = "MySource";
After uninstalling both services, and reinstalling the one that suffered from error 1053, my service started up normally.
I believe the intent was to rename System32, but so many applications hard-coded for that path, that it wasn't feasible to remove it.
SysWoW64 wasn't intended for the dlls of 64-bit systems, it's actually something like "Windows on Windows64", meaning the bits you need to run 32bit apps on a 64bit windows.
This article explains a bit:
"Windows x64 has a directory System32 that contains 64-bit DLLs (sic!). Thus native processes with a bitness of 64 find “their” DLLs where they expect them: in the System32 folder. A second directory, SysWOW64, contains the 32-bit DLLs. The file system redirector does the magic of hiding the real System32 directory for 32-bit processes and showing SysWOW64 under the name of System32."
Edit: If you're talking about an installer, you really should not hard-code the path to the system folder. Instead, let Windows take care of it for you based on whether or not your installer is running on the emulation layer.
Great sadness: neither Cloneable/clone nor a constructor are great solutions: I DON'T WANT TO KNOW THE IMPLEMENTING CLASS!!! (e.g. - I have a Map, which I want copied, using the same hidden MumbleMap implementation) I just want to make a copy, if doing so is supported. But, alas, Cloneable doesn't have the clone method on it, so there is nothing to which you can safely type-cast on which to invoke clone().
Whatever the best "copy object" library out there is, Oracle should make it a standard component of the next Java release (unless it already is, hidden somewhere).
Of course, if more of the library (e.g. - Collections) were immutable, this "copy" task would just go away. But then we would start designing Java programs with things like "class invariants" rather than the verdammt "bean" pattern (make a broken object and mutate until good [enough]).
If you are getting this from your own package.json
, just add the repository
field to it. (use the link to your actual repository):
"repository" : {
"type" : "git",
"url" : "https://github.com/npm/npm.git"
}
For Excel 2016 64-bit on a Windows 10 machine, I have used a hex editor to be able to change the password of a protected xla (have not tested this for any other extensions). Tip: create a backup before you do this.
The steps I took:
I hope this helped some of you!
For requirements like this I have created Utility to customize Seekbar progress like below code:
SeekBarUtil.class
import android.widget.SeekBar;
import android.widget.TextView;
public class SeekBarUtil {
public static void setSeekBar(SeekBar mSeekbar, int minVal, int maxVal, int intervalVal, final TextView mTextView, String startPrefix, String endSuffix) {
int totalCount = (maxVal - minVal) / intervalVal;
mSeekbar.setMax(totalCount);
mSeekbar.setOnSeekBarChangeListener(new CustomSeekBarListener(minVal, maxVal, intervalVal) {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//progress = ((int)Math.round(progress/interval))*interval;
int val = min;
if (interval == totalCount) {
val = max;
} else {
val = min + (progress * interval);
}
seekBar.setProgress(progress);
mTextView.setText(startPrefix + val + endSuffix);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) { }
@Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
}
}
and CustomSeekBarListener.class
import android.widget.SeekBar;
class CustomSeekBarListener implements SeekBar.OnSeekBarChangeListener {
int min=0,max=0,interval=1;
int totalCount;
public CustomSeekBarListener(int min, int max, int interval) {
this.min = min;
this.max = max;
this.interval = interval;
totalCount= (max - min) / interval;
}
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) { }
@Override
public void onStartTrackingTouch(SeekBar seekBar) { }
@Override
public void onStopTrackingTouch(SeekBar seekBar) { }
}
and you can use it like below code snippet
SeekBarUtil.setSeekBar(seekbarAmountNeeded,10000,200000,5000,textAmount,"$"," PA");
Additional-> To clear the Child Controls The below function would clear the nested(Child) controls also, wrap up in a class.
public static void ClearControl(Control control)
{
if (control is TextBox)
{
TextBox txtbox = (TextBox)control;
txtbox.Text = string.Empty;
}
else if (control is CheckBox)
{
CheckBox chkbox = (CheckBox)control;
chkbox.Checked = false;
}
else if (control is RadioButton)
{
RadioButton rdbtn = (RadioButton)control;
rdbtn.Checked = false;
}
else if (control is DateTimePicker)
{
DateTimePicker dtp = (DateTimePicker)control;
dtp.Value = DateTime.Now;
}
else if (control is ComboBox)
{
ComboBox cmb = (ComboBox)control;
if (cmb.DataSource != null)
{
cmb.SelectedItem = string.Empty;
cmb.SelectedValue = 0;
}
}
ClearErrors(control);
// repeat for combobox, listbox, checkbox and any other controls you want to clear
if (control.HasChildren)
{
foreach (Control child in control.Controls)
{
ClearControl(child);
}
}
}
Other answers have already explained meaning of None beautifully. However, I would still like to throw more light on this using an example.
Example:
def extendList(val, list=[]):
list.append(val)
return list
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3
Now try to guess output of above list. Well, the answer is surprisingly as below:
list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']
But Why?
Many will mistakenly expect list1 to be equal to [10] and list3 to be equal to ['a'], thinking that the list argument will be set to its default value of [] each time extendList is called.
However, what actually happens is that the new default list is created only once when the function is defined, and that same list is then used subsequently whenever extendList is invoked without a list argument being specified. This is because expressions in default arguments are calculated when the function is defined, not when it’s called.
list1 and list3 are therefore operating on the same default list, whereas list2 is operating on a separate list that it created (by passing its own empty list as the value for the list parameter).
'None' the savior: (Modify example above to produce desired behavior)
def extendList(val, list=None):
if list is None:
list = []
list.append(val)
return list
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3
With this revised implementation, the output would be:
list1 = [10]
list2 = [123]
list3 = ['a']
Note - Example credit to toptal.com
print locals()
edit continued from comment.
To make it look a little prettier when printing:
import sys, pprint
sys.displayhook = pprint.pprint
locals()
That should give you a more vertical printout.
Let's say you have:
<a></a>
<(.*)>
would match a></a
where as <(.*?)>
would match a
.
The latter stops after the first match of >
. It checks for one
or 0 matches of .*
followed by the next expression.
The first expression <(.*)>
doesn't stop when matching the first >
. It will continue until the last match of >
.
if you are using extracted tomcat then,
startup.sh
and shutdown.sh
are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that
if tomcat is installed then
/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart
SELECT
dp.state_desc + ' '
+ dp.permission_name collate latin1_general_cs_as
+ ISNULL((' ON ' + QUOTENAME(s.name) + '.' + QUOTENAME(o.name)),'')
+ ' TO ' + QUOTENAME(dpr.name)
FROM sys.database_permissions AS dp
LEFT JOIN sys.objects AS o ON dp.major_id=o.object_id
LEFT JOIN sys.schemas AS s ON o.schema_id = s.schema_id
LEFT JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
WHERE dpr.name NOT IN ('public','guest')
Slight change of the accepted answer if you want to grab permissions that are applied at database level in addition to object level. Basically switch to LEFT JOIN
and make sure to handle NULL
for object
and schema
names
.
Let's start from here, As defined on MDN: Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions 'remember' the environment in which they were created.
Lexical scoping
Consider the following:
function init() {
var name = 'Mozilla'; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();
init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is only available within the body of the init() function. The displayName() function has no local variables of its own. However, because inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().
function init() {
var name = "Mozilla"; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert (name); // displayName() uses variable declared in the parent function
}
displayName();
}
init();
Run the code and notice that the alert() statement within the displayName() function successfully displays the value of the name variable, which is declared in its parent function. This is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. The word "lexical" refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.
Closure
Now consider the following example:
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
Running this code has exactly the same effect as the previous example of the init() function above: this time, the string "Mozilla" will be displayed in a JavaScript alert box. What's different — and interesting — is that the displayName() inner function is returned from the outer function before being executed.
At first glance, it may seem unintuitive that this code still works. In some programming languages, the local variables within a function exist only for the duration of that function's execution. Once makeFunc() has finished executing, you might expect that the name variable would no longer be accessible. However, because the code still works as expected, this is obviously not the case in JavaScript.
The reason is that functions in JavaScript form closures. A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time that the closure was created. In this case, myFunc is a reference to the instance of the function displayName created when makeFunc is run. The instance of displayName maintains a reference to its lexical environment, within which the variable name exists. For this reason, when myFunc is invoked, the variable name remains available for use and "Mozilla" is passed to alert.
Here's a slightly more interesting example — a makeAdder function:
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
In this example, we have defined a function makeAdder(x), which takes a single argument, x, and returns a new function. The function it returns takes a single argument, y, and returns the sum of x and y.
In essence, makeAdder is a function factory — it creates functions which can add a specific value to their argument. In the above example we use our function factory to create two new functions — one that adds 5 to its argument, and one that adds 10.
add5 and add10 are both closures. They share the same function body definition, but store different lexical environments. In add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10.
Practical closures
Closures are useful because they let you associate some data (the lexical environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods.
Consequently, you can use a closure anywhere that you might normally use an object with only a single method.
Situations where you might want to do this are particularly common on the web. Much of the code we write in front-end JavaScript is event-based — we define some behavior, then attach it to an event that is triggered by the user (such as a click or a keypress). Our code is generally attached as a callback: a single function which is executed in response to the event.
For instance, suppose we wish to add some buttons to a page that adjust the text size. One way of doing this is to specify the font-size of the body element in pixels, then set the size of the other elements on the page (such as headers) using the relative em unit:
body {
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
}
h1 {
font-size: 1.5em;
}
h2 {
font-size: 1.2em;
}
Our interactive text size buttons can change the font-size property of the body element, and the adjustments will be picked up by other elements on the page thanks to the relative units. Here's the JavaScript:
function makeSizer(size) {
return function() {
document.body.style.fontSize = size + 'px';
};
}
var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);
size12, size14, and size16 are now functions which will resize the body text to 12, 14, and 16 pixels, respectively. We can attach them to buttons (in this case links) as follows:
document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
<a href="#" id="size-12">12</a>
<a href="#" id="size-14">14</a>
<a href="#" id="size-16">16</a>
function makeSizer(size) {
return function() {
document.body.style.fontSize = size + 'px';
};
}
var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);
document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
for reading more about closures, visit the link on MDN
As a supplementary to the two previous answers (of user "sudo rm -rf" and "Evan Mulawski"), if you don't want to do anything when your alert view is clicked, you can just allocate, show and release it. You don't have to declare the delegate protocol.
[xml]$xmlfile = '<xml> <Section name="BackendStatus"> <BEName BE="crust" Status="1" /> <BEName BE="pizza" Status="1" /> <BEName BE="pie" Status="1" /> <BEName BE="bread" Status="1" /> <BEName BE="Kulcha" Status="1" /> <BEName BE="kulfi" Status="1" /> <BEName BE="cheese" Status="1" /> </Section> </xml>'
foreach ($bename in $xmlfile.xml.Section.BEName) {
if($bename.Status -eq 1){
#Do something
}
}
You can easily debug such things when you go through the generated CSS. In this case the pseudo-selector after conversion has to be attached to the class. Which is not the case. Use "&".
http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector
.class {
margin:20px;
&:hover {
color:yellow;
}
}
You are just missing the words "primary key" as far as I can see to meet your specified objective.
For your other columns it's best to explicitly define whether they should be NULL
or NOT NULL
though so you are not relying on the ANSI_NULL_DFLT_ON
setting.
CREATE TABLE #tmp
(
ID INT IDENTITY(1, 1) primary key ,
AssignedTo NVARCHAR(100),
AltBusinessSeverity NVARCHAR(100),
DefectCount int
);
insert into #tmp
select 'user','high',5 union all
select 'user','med',4
select * from #tmp
create_function
did not work for me inside a class. I had to use call_user_func
.
<?php
class Dispatcher {
//Added explicit callback declaration.
var $callback;
public function Dispatcher( $callback ){
$this->callback = $callback;
}
public function asynchronous_method(){
//do asynch stuff, like fwrite...then, fire callback.
if ( isset( $this->callback ) ) {
if (function_exists( $this->callback )) call_user_func( $this->callback, "File done!" );
}
}
}
Then, to use:
<?php
include_once('Dispatcher.php');
$d = new Dispatcher( 'do_callback' );
$d->asynchronous_method();
function do_callback( $data ){
print 'Data is: ' . $data . "\n";
}
?>
[Edit] Added a missing parenthesis. Also, added the callback declaration, I prefer it that way.
%hash1 = (%hash1, %hash2) ## or else ... @hash1{keys %hash2} = values %hash2; ## or with references ... $hash_ref1 = { %$hash_ref1, %$hash_ref2 };
undef
, zero, empty string, false
, falsy ...)1 * (aka associative-array, aka dictionary)
In laravel 5.3 and above, the laravel team moved all procedural files (routes.php
) out of the app/
directory, and the entire app/
folder is psr-4
autoloaded. The accepted answer will work in this case but it doesn't feel right to me.
So what I did was I created a helpers/
directory at the root of my project and put the helper files inside of that, and in my composer.json
file I did this:
...
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"helpers/ui_helpers.php"
]
},
...
This way my app/
directory is still a psr-4 autoloaded one, and the helpers are a little better organized.
Hope this helps someone.
It can be, but it's a hack.
See Is DoEvents Evil?.
Direct from the MSDN page that thedev referenced:
Calling this method causes the current thread to be suspended while all waiting window messages are processed. If a message causes an event to be triggered, then other areas of your application code may execute. This can cause your application to exhibit unexpected behaviors that are difficult to debug. If you perform operations or computations that take a long time, it is often preferable to perform those operations on a new thread. For more information about asynchronous programming, see Asynchronous Programming Overview.
So Microsoft cautions against its use.
Also, I consider it a hack because its behavior is unpredictable and side effect prone (this comes from experience trying to use DoEvents instead of spinning up a new thread or using background worker).
There is no machismo here - if it worked as a robust solution I would be all over it. However, trying to use DoEvents in .NET has caused me nothing but pain.
Simple answer is Add a subview and change it's alpha.
UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
UIView *subView = [[UIView alloc] initWithFrame:popupView.frame];
UIColor * backImgColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blue_Img.png"]];
subView.backgroundColor = backImgColor;
subView.alpha = 0.5;
[mainView addSubview:subView];
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];_x000D_
var data = arrofobject.map(arrofobject => arrofobject);_x000D_
console.log(data)
_x000D_
for more details please look at jQuery.map()
You can simply cast to bool, dont forget to handle zero.
function isEmpty(string $string): bool {
if($string === '0') {
return false;
}
return !(bool)$string;
}
var_dump(isEmpty('')); // bool(true)
var_dump(isEmpty('foo')); // bool(false)
var_dump(isEmpty('0')); // bool(false)
if you have neccessary .net
framework installed. Ex ; .Net 4.0
or .Net 3.5
, then you can just copy Gacutil.exe
from any of the machine and to the new machine.
1) Open CMD as adminstrator in new server.
2) Traverse to the folder where you copied the Gacutil.exe. For eg - C:\program files.(in my case).
3) Type the below in the cmd prompt and install.
C:\Program Files\gacutil.exe /I dllname
Check service dependencies if they are disabled.
Set those dependencies to Automatic, Start them and it should work.
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
In case of an associative array or numbered array where you do not want to change the array keys:
$firstItem = array('foo' => 'bar');
$arr = $firstItem + $arr;
array_merge
does not work as it always reindexes the array.
Following on from @Wilf's answer, I was trying to import a spreadsheet which had spaces in one of the headings, which I eliminated. I checked for leading and trailing spaces, but still had the same problem - until I used Ctrl-Right from the last real heading cell, and found another cell on the first row that looked blank but obviously contained some whitespace. After deleting this, my import works. Thanks for the pointers :)
Very simple. Just cast your char
as an int
.
char character = 'a';
int ascii = (int) character;
In your case, you need to get the specific Character from the String first and then cast it.
char character = name.charAt(0); // This gives the character 'a'
int ascii = (int) character; // ascii is now 97.
Though cast is not required explicitly, but its improves readability.
int ascii = character; // Even this will do the trick.
As much as I love XAML, for this kinds of tasks I switch to code behind. Attached behaviors are a good pattern for this. Keep in mind, Expression Blend 3 provides a standard way to program and use behaviors. There are a few existing ones on the Expression Community Site.
To create a new branch (locally):
With the commit hash (or part of it)
git checkout -b new_branch 6e559cb
or to go back 4 commits from HEAD
git checkout -b new_branch HEAD~4
Once your new branch is created (locally), you might want to replicate this change on a remote of the same name: How can I push my changes to a remote branch
For discarding the last three commits, see Lunaryorn's answer below.
For moving your current branch HEAD to the specified commit without creating a new branch, see Arpiagar's answer below.
This is old, but I put exports in my alias for connecting to the db:
alias schema_one.con="PGOPTIONS='--search_path=schema_one' psql -h host -U user -d database etc"
And for another schema:
alias schema_two.con="PGOPTIONS='--search_path=schema_two' psql -h host -U user -d database etc"
You can also use:
@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")
To specify the format of your output in a scenario where you need to use Charset, Type, etc.
Found this sweet snippet from a post by Changhui Xu for those looking to get unique objects. I haven't measured its performance against the other alternatives though.
const array = [{_x000D_
name: 'Joe',_x000D_
age: 17_x000D_
},_x000D_
{_x000D_
name: 'Bob',_x000D_
age: 17_x000D_
},_x000D_
{_x000D_
name: 'Tom',_x000D_
age: 25_x000D_
},_x000D_
{_x000D_
name: 'John',_x000D_
age: 22_x000D_
},_x000D_
{_x000D_
name: 'Jane',_x000D_
age: 20_x000D_
},_x000D_
];_x000D_
_x000D_
const distinctAges = [...new Set(array.map(a => a.age))];_x000D_
_x000D_
console.log(distinctAges)
_x000D_
Did you try showing your window using the ShowDialog method?
Don't forget to set the Owner property on the dialog window to the main window. This will avoid weird behavior when Alt+Tabbing, etc.
Here's a one-liner using Maven:
mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38
Then, with default settings, it's available in:
$HOME/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar
Just replace the version number if you need a different one.
Mine was putting the schema on the table Alias by mistake:
SELECT * FROM schema.CustomerOrders co
WHERE schema.co.ID = 1 -- oops!
Text shouldn't be on its own. Put it into a span
element.
Change it to this:
<div id="one">
<div class="first"></div>
<span>"Hi I am text"</span>
<div class="second"></div>
<div class="third"></div>
</div>
$('#one span').text('Hi I am replace');
While all of the above links have merit, and have benefited me greatly in the past, as a linguist "exposed" to various Lucene search engines for the last 15 years, I have to say that elastic-search development is very fast in Python. That being said, some of the code felt non-intuitive to me. So, I reached out to one component of the ELK stack, Kibana, from an open source perspective, and found that I could generate the somewhat cryptic code of elasticsearch very easily in Kibana. Also, I could pull Chrome Sense es queries into Kibana as well. If you use Kibana to evaluate es, it will further speed up your evaluation. What took hours to run on other platforms was up and running in JSON in Sense on top of elasticsearch (RESTful interface) in a few minutes at worst (largest data sets); in seconds at best. The documentation for elasticsearch, while 700+ pages, didn't answer questions I had that normally would be resolved in SOLR or other Lucene documentation, which obviously took more time to analyze. Also, you may want to take a look at Aggregates in elastic-search, which have taken Faceting to a new level.
Bigger picture: if you're doing data science, text analytics, or computational linguistics, elasticsearch has some ranking algorithms that seem to innovate well in the information retrieval area. If you're using any TF/IDF algorithms, Text Frequency/Inverse Document Frequency, elasticsearch extends this 1960's algorithm to a new level, even using BM25, Best Match 25, and other Relevancy Ranking algorithms. So, if you are scoring or ranking words, phrases or sentences, elasticsearch does this scoring on the fly, without the large overhead of other data analytics approaches that take hours--another elasticsearch time savings. With es, combining some of the strengths of bucketing from aggregations with the real-time JSON data relevancy scoring and ranking, you could find a winning combination, depending on either your agile (stories) or architectural(use cases) approach.
Note: did see a similar discussion on aggregations above, but not on aggregations and relevancy scoring--my apology for any overlap. Disclosure: I don't work for elastic and won't be able to benefit in the near future from their excellent work due to a different architecural path, unless I do some charity work with elasticsearch, which wouldn't be a bad idea
This is the sort of thing that the CSS flexbox model will fix, because it will let you specify that each li will receive an equal proportion of the remaining width.
Just for a sake of completeness, if you need to find all positions of a character in a string, you can do the following:
s = 'shak#spea#e'
c = '#'
print([pos for pos, char in enumerate(s) if char == c])
which will print: [4, 9]
If you work with generics, use List instead of ArrayList. The List has exactly the GetEnumerator method you need.
List<MyObject> myList = new List<MyObject>();
I had the same problem and I just tried using the following as a workaround. Seems to work so far. You can even create a dummy template that just contains references to all those static assets.
{% stylesheets
output='assets/fonts/glyphicons-halflings-regular.ttf'
'bundles/bootstrap/fonts/glyphicons-halflings-regular.ttf'
%}{% endstylesheets %}
Notice the omission of any output which means nothing shows up on the template. When I run assetic:dump the files are copied over to the desired location and the css includes work as expected.
Select A.ARIDNR,A.LIEFNR
from Table A
join Table B
on A.ARIDNR = B.ARIDNR
and A.LIEFNR<> B.LIEFNR
group by A.ARIDNR,A.LIEFNR
You shall probably use the "Resolve Auto Layout Issues" (bottom right - triangle icon in the storyboard view) to add/reset to suggested constraints (Xcode 6.0.1).
This is an old post now, but for anyone looking for the answer, this link should help. Go to this answer if you are already using EF 6.2.x. To this answer if you're using EF Core 2.x
Short version:
SqlFunctions.PatIndex method - returns the starting position of the first occurrence of a pattern in a specified expression, or zeros if the pattern is not found, on all valid text and character data types
Namespace: System.Data.Objects.SqlClient Assembly: System.Data.Entity (in System.Data.Entity.dll)
A bit of an explanation also appears in this forum thread.
You can use the function outer()
to generate it.
Have a look at the demo for the function persp()
, which is a base graphics function to draw perspective plots for surfaces.
Here is their first example:
x <- seq(-10, 10, length.out = 50)
y <- x
rotsinc <- function(x,y) {
sinc <- function(x) { y <- sin(x)/x ; y[is.na(y)] <- 1; y }
10 * sinc( sqrt(x^2+y^2) )
}
z <- outer(x, y, rotsinc)
persp(x, y, z)
The same applies to surface3d()
:
require(rgl)
surface3d(x, y, z)
This can't be done with just HTML/CSS. You need to use javascript here. In jQuery it would be:
$('#button').click(function(e){
e.preventDefault(); //to prevent standard click event
$('#wizard').toggle();
});
Just put your Images in Public Directory (public/...folder or direct images).
Public directory is by default rendered by laravel application.
Let's suppose I stored images in public/images/myimage.jpg
.
Then in your HTML view, page like: (image.blade.php)
<img src="{{url('/images/myimage.jpg')}}" alt="Image"/>
var len = $('#your_form_id input:radio:checked').length;
if (!len) {
alert("None checked");
};
alert("checked: "+ len);
It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split()
can do the correct tokenization for args (I'm using Blender's example of the call):
import shlex
from subprocess import Popen, PIPE
command = shlex.split('swfdump /tmp/filename.swf/ -d')
process = Popen(command, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
Intent intent = new Intent(activity1.this, activity2.class);
intent.putExtra("message", message);
startActivity(intent);
In activity2, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Just add map:
" ~/.vimrc
inoremap <c-p> <c-r>*
restart vim and when press Crtl+p
in insert mode,
copied text will be pasted
Assuming that you have posted valid JSON,
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content['uuid']
# Return data as JSON
return jsonify(content)
getline()
is what you're looking for. You use strings in C++, and you don't need to know the size ahead of time.
Assuming std namespace:
ifstream file1("myfile.txt");
string stuff;
while (getline(file1, stuff, '\n')) {
cout << stuff << endl;
}
file1.close();
typedef struct{
char array[4];
}my_array;
my_array array = { .array = {1,1,1,1} }; // initialisation
void assign(my_array a)
{
array.array[0] = a.array[0];
array.array[1] = a.array[1];
array.array[2] = a.array[2];
array.array[3] = a.array[3];
}
char num = 5;
char ber = 6;
int main(void)
{
printf("%d\n", array.array[0]);
// ...
// this works even after initialisation
assign((my_array){ .array = {num,ber,num,ber} });
printf("%d\n", array.array[0]);
// ....
return 0;
}
I know I'm answering this question almost two and a half years after it was asked, but I just wanted to provide some hard data from a project I'm working on right now that shows that indeed doing multiple VALUE blocks per insert is MUCH faster than sequential single VALUE block INSERT statements.
The code I wrote for this benchmark in C# uses ODBC to read data into memory from an MSSQL data source (~19,000 rows, all are read before any writing commences), and the MySql .NET connector (Mysql.Data.*) stuff to INSERT the data from memory into a table on a MySQL server via prepared statements. It was written in such a way as to allow me to dynamically adjust the number of VALUE blocks per prepared INSERT (ie, insert n rows at a time, where I could adjust the value of n before a run.) I also ran the test multiple times for each n.
Doing single VALUE blocks (eg, 1 row at a time) took 5.7 - 5.9 seconds to run. The other values are as follows:
2 rows at a time: 3.5 - 3.5 seconds
5 rows at a time: 2.2 - 2.2 seconds
10 rows at a time: 1.7 - 1.7 seconds
50 rows at a time: 1.17 - 1.18 seconds
100 rows at a time: 1.1 - 1.4 seconds
500 rows at a time: 1.1 - 1.2 seconds
1000 rows at a time: 1.17 - 1.17 seconds
So yes, even just bundling 2 or 3 writes together provides a dramatic improvement in speed (runtime cut by a factor of n), until you get to somewhere between n = 5 and n = 10, at which point the improvement drops off markedly, and somewhere in the n = 10 to n = 50 range the improvement becomes negligible.
Hope that helps people decide on (a) whether to use the multiprepare idea, and (b) how many VALUE blocks to create per statement (assuming you want to work with data that may be large enough to push the query past the max query size for MySQL, which I believe is 16MB by default in a lot of places, possibly larger or smaller depending on the value of max_allowed_packet set on the server.)
// O(n)
var arr = [1, 2, 3, 2, 3, 3, 5, 6];
var duplicates = {};
max = '';
maxi = 0;
arr.forEach((el) => {
duplicates[el] = duplicates[el] + 1 || 1;
if (maxi < duplicates[el]) {
max = el;
maxi = duplicates[el];
}
});
console.log(max);
UPDATE: 2019-12-30
It seem that this tool is no longer working!
[Request for update!]
UPDATE 2019-01-06: You can bypass X-Frame-Options
in an <iframe>
using my X-Frame-Bypass Web Component. It extends the IFrame element by using multiple CORS proxies and it was tested in the latest Firefox and Chrome.
You can use it as follows:
(Optional) Include the Custom Elements with Built-in Extends polyfill for Safari:
<script src="https://unpkg.com/@ungap/custom-elements-builtin"></script>
Include the X-Frame-Bypass JS module:
<script type="module" src="x-frame-bypass.js"></script>
Insert the X-Frame-Bypass Custom Element:
<iframe is="x-frame-bypass" src="https://example.org/"></iframe>
This is a C++ interview test question not homework.
Then your interviewer needs to refresh his recollection with how the C++ standard works. And I quote:
For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration.
The whole "whose underlying type is not fixed" part is from C++11, but the rest is all standard C++98/03. In short, the sizeof(months_t)
is not 4. It is not 2 either. It could be any of those. The standard does not say what size it should be; only that it should be big enough to fit any enumerator.
why the all size is 4 bytes ? not 12 x 4 = 48 bytes ?
Because enums are not variables. The members of an enum are not actual variables; they're just a semi-type-safe form of #define. They're a way of storing a number in a reader-friendly format. The compiler will transform all uses of an enumerator into the actual numerical value.
Enumerators are just another way of talking about a number. january
is just shorthand for 0
. And how much space does 0 take up? It depends on what you store it in.
display:
is not transitionable. You'll probably need to use jQuery to do what you want to do.
I created an insecure but simple text cipher/decipher util. No dependencies with any external library.
These are the functions
const cipher = salt => {
const textToChars = text => text.split('').map(c => c.charCodeAt(0));
const byteHex = n => ("0" + Number(n).toString(16)).substr(-2);
const applySaltToChar = code => textToChars(salt).reduce((a,b) => a ^ b, code);
return text => text.split('')
.map(textToChars)
.map(applySaltToChar)
.map(byteHex)
.join('');
}
const decipher = salt => {
const textToChars = text => text.split('').map(c => c.charCodeAt(0));
const applySaltToChar = code => textToChars(salt).reduce((a,b) => a ^ b, code);
return encoded => encoded.match(/.{1,2}/g)
.map(hex => parseInt(hex, 16))
.map(applySaltToChar)
.map(charCode => String.fromCharCode(charCode))
.join('');
}
And you can use them as follows:
// To create a cipher
const myCipher = cipher('mySecretSalt')
//Then cipher any text:
myCipher('the secret string') // --> "7c606d287b6d6b7a6d7c287b7c7a61666f"
//To decipher, you need to create a decipher and use it:
const myDecipher = decipher('mySecretSalt')
myDecipher("7c606d287b6d6b7a6d7c287b7c7a61666f") // --> 'the secret string'
If you want to visualize your dependencies in a graph you can use gradle-dependency-graph-generator plugin.
Generally the output of this plugin can be found in build/reports/dependency-graph directory and it contains three files (.dot|.png|.svg) if you are using the 0.5.0 version of the plugin.
Example of dependences graph in a real app (Chess Clock):
Every WP install has a readme.html file.
So just type www.yourdomain.com/readme.html
Just for the sake of completeness you can just take the wanted data type and add brackets with the number of elements like so:
x <- character(10)
For right to left (entry animation) and left to right (exit animation):
styles.xml:
<style name="CustomDialog" parent="@android:style/Theme.Dialog">
<item name="android:windowAnimationStyle">@style/CustomDialogAnimation</item>
</style>
<style name="CustomDialogAnimation">
<item name="android:windowEnterAnimation">@anim/translate_left_side</item>
<item name="android:windowExitAnimation">@anim/translate_right_side</item>
</style>
Create two files in res/anim/:
translate_right_side.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0%" android:toXDelta="100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="600"/>
translate_left_side.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="600"
android:fromXDelta="100%"
android:toXDelta="0%"/>
In you Fragment/Activity:
Dialog dialog = new Dialog(getActivity(), R.style.CustomDialog);
The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.
However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.
You can do this to execute a static method:
MyClass.staticMethod(); // Simply refers to the class's static code
But to execute a non-static method, you must do this:
MyClass obj = new MyClass();//Create an instance
obj.nonstaticMethod(); // Refer to the instance's class's code
On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.
You would need to call RAND() for each row. Here is a good example
Both source and target should be specified. I recommend providing ant defaults, that way you do not need to specify source/target attribute for every javac task:
<property name="ant.build.javac.source" value="1.5"/>
<property name="ant.build.javac.target" value="1.5"/>
See Java cross-compiling notes for more information.
You can use the following command:
svn status -q
According to svnbook:
With --quiet (-q), it prints only summary information about locally modified items.
WARNING: The output of this command only shows your modification. So I suggest to do a svn up
to get latest version of the file and then use svn status -q
to get the files you have modified.
I had my tryst with KSOAP; I chose a rather simpler approach.
Given a WSDL file, create SOAP Request templates for each Request(for e.g.: using SOAP UI) and then substitute the values to be passed in code. POST this data to the service end point using DefaultHttpClient instance and get the response stream. Parse the Response Stream using an XML Pull parser.
Yes, and then some, example from documentation:
public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7);
// in kilograms
private final double mass;
// in meters
private final double radius;
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
private double mass() { return mass; }
private double radius() { return radius; }
// universal gravitational
// constant (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
double surfaceGravity() {
return G * mass / (radius * radius);
}
double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java Planet <earth_weight>");
System.exit(-1);
}
double earthWeight = Double.parseDouble(args[0]);
double mass = earthWeight/EARTH.surfaceGravity();
for (Planet p : Planet.values())
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
}
We've tried a number of obfuscators. None of them work on a large client/server app that uses remoting. Problem is that client and server share some dlls, and we haven't found any obfuscator that can handle it.
We've tried DotFuscator Pro, SmartAssembly, XenoCode, Salamander, and several small time apps whose names escape me.
Frankly, I'm convinced obfuscation is a big hack.
Even the problems it addresses is not entirely a real problem. The only thing you really need to protect is connection strings, activation codes, security-sensitive things like that. This nonsense that another company is going to reverse-engineer your whole codebase and create a competing product from it is something from a paranoid manager's nightmare, not reality.
For those still searching for a tree with CSS3, this is a fantastic piece of code I found on the net:
http://thecodeplayer.com/walkthrough/css3-family-tree
<div class="tree">
<ul>
<li>
<a href="#">Parent</a>
<ul>
<li>
<a href="#">Child</a>
<ul>
<li>
<a href="#">Grand Child</a>
</li>
</ul>
</li>
<li>
<a href="#">Child</a>
<ul>
<li><a href="#">Grand Child</a></li>
<li>
<a href="#">Grand Child</a>
<ul>
<li>
<a href="#">Great Grand Child</a>
</li>
<li>
<a href="#">Great Grand Child</a>
</li>
<li>
<a href="#">Great Grand Child</a>
</li>
</ul>
</li>
<li><a href="#">Grand Child</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
* {margin: 0; padding: 0;}
.tree ul {
padding-top: 20px; position: relative;
transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}
.tree li {
float: left; text-align: center;
list-style-type: none;
position: relative;
padding: 20px 5px 0 5px;
transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}
/*We will use ::before and ::after to draw the connectors*/
.tree li::before, .tree li::after{
content: '';
position: absolute; top: 0; right: 50%;
border-top: 1px solid #ccc;
width: 50%; height: 20px;
}
.tree li::after{
right: auto; left: 50%;
border-left: 1px solid #ccc;
}
/*We need to remove left-right connectors from elements without
any siblings*/
.tree li:only-child::after, .tree li:only-child::before {
display: none;
}
/*Remove space from the top of single children*/
.tree li:only-child{ padding-top: 0;}
/*Remove left connector from first child and
right connector from last child*/
.tree li:first-child::before, .tree li:last-child::after{
border: 0 none;
}
/*Adding back the vertical connector to the last nodes*/
.tree li:last-child::before{
border-right: 1px solid #ccc;
border-radius: 0 5px 0 0;
-webkit-border-radius: 0 5px 0 0;
-moz-border-radius: 0 5px 0 0;
}
.tree li:first-child::after{
border-radius: 5px 0 0 0;
-webkit-border-radius: 5px 0 0 0;
-moz-border-radius: 5px 0 0 0;
}
/*Time to add downward connectors from parents*/
.tree ul ul::before{
content: '';
position: absolute; top: 0; left: 50%;
border-left: 1px solid #ccc;
width: 0; height: 20px;
}
.tree li a{
border: 1px solid #ccc;
padding: 5px 10px;
text-decoration: none;
color: #666;
font-family: arial, verdana, tahoma;
font-size: 11px;
display: inline-block;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}
/*Time for some hover effects*/
/*We will apply the hover effect the the lineage of the element also*/
.tree li a:hover, .tree li a:hover+ul li a {
background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}
/*Connector styles on hover*/
.tree li a:hover+ul li::after,
.tree li a:hover+ul li::before,
.tree li a:hover+ul::before,
.tree li a:hover+ul ul::before{
border-color: #94a0b4;
}
PS: apart from the code, I also like the way the site shows it in action... really innovative.
According to docs you can just do:
{{ p|default('', true) }}
Cause None
casts to False
in boolean context.
Update: As lindes mentioned, it works only for simple data types.
I'm surprised that nobody mention the problem with multiple input in CMS's very nice snipped.
Basically, you would have to define delay variable individually for each input. Otherwise if sb put text to first input and quickly jump to other input and start typing, callback for the first one WON'T be called!
See the code below I came with based on other answers:
(function($) {
/**
* KeyUp with delay event setup
*
* @link http://stackoverflow.com/questions/1909441/jquery-keyup-delay#answer-12581187
* @param function callback
* @param int ms
*/
$.fn.delayKeyup = function(callback, ms){
$(this).keyup(function( event ){
var srcEl = event.currentTarget;
if( srcEl.delayTimer )
clearTimeout (srcEl.delayTimer );
srcEl.delayTimer = setTimeout(function(){ callback( $(srcEl) ); }, ms);
});
return $(this);
};
})(jQuery);
This solution keeps setTimeout reference within input's delayTimer variable. It also passes reference of element to callback as fazzyx suggested.
Tested in IE6, 8(comp - 7), 8 and Opera 12.11.
I was also looking to list repositories in SVN. I did something like this on shell prompt:
~$ svn list https://www.repo.rr.com/svn/main/team/gaurav
Test/
Test2/
Test3/
Test4/
Test5/
Test6/
Why don't you simply use set_index
method?
In : col = ['a','b','c']
In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)
In : data
Out:
a b c
0 1 2 3
1 10 11 12
2 20 21 22
In : data2 = data.set_index('a')
In : data2
Out:
b c
a
1 2 3
10 11 12
20 21 22
This will give DISTINCT values across all the columns:
SELECT DISTINCT value
FROM (
SELECT DISTINCT a AS value FROM my_table
UNION SELECT DISTINCT b AS value FROM my_table
UNION SELECT DISTINCT c AS value FROM my_table
) AS derived
I don't know that you can do it in Chrome outside of Windows -- some Googling shows that Chrome (and therefore possibly Chromium) might respond well to a certain registry hack.
However, if you're just looking for a simple solution without modifying your code base, have you considered Firefox? In the about:config you can search for "network.http.max" and there are a few values in there that are definitely worth looking at.
Also, for a device that will not be moving (i.e. it is mounted in a fixed location) you should consider not using Wi-Fi (even a Home-Plug would be a step up as far as latency / stability / dropped connections go).
<summary>
and <details>
Using <summary>
and <details>
elements is the simplest but see browser support as current IE is not supporting it. You can polyfill though (most are jQuery-based). Do note that unsupported browser will simply show the expanded version of course, so that may be acceptable in some cases.
/* Optional styling */_x000D_
summary::-webkit-details-marker {_x000D_
color: blue;_x000D_
}_x000D_
summary:focus {_x000D_
outline-style: none;_x000D_
}
_x000D_
<details>_x000D_
<summary>Summary, caption, or legend for the content</summary>_x000D_
Content goes here._x000D_
</details>
_x000D_
See also how to style the <details>
element (HTML5 Doctor) (little bit tricky).
The :target
selector has a pretty good browser support, and it can be used to make a single collapsible element within the frame.
.details,_x000D_
.show,_x000D_
.hide:target {_x000D_
display: none;_x000D_
}_x000D_
.hide:target + .show,_x000D_
.hide:target ~ .details {_x000D_
display: block;_x000D_
}
_x000D_
<div>_x000D_
<a id="hide1" href="#hide1" class="hide">+ Summary goes here</a>_x000D_
<a id="show1" href="#show1" class="show">- Summary goes here</a>_x000D_
<div class="details">_x000D_
Content goes here._x000D_
</div>_x000D_
</div>_x000D_
<div>_x000D_
<a id="hide2" href="#hide2" class="hide">+ Summary goes here</a>_x000D_
<a id="show2" href="#show2" class="show">- Summary goes here</a>_x000D_
<div class="details">_x000D_
Content goes here._x000D_
</div>_x000D_
</div>
_x000D_
In your Activity (where you're calling the adapter) just change getActivityContext()
with YourActivity.this
.
Here's an exemple:
yourAdapter = new YourAdapter(yourList, YourActivity.this); // Here YourActivity.this is the Context instead of getActivityContext()
recyclerView.setAdapter(yourAdapter);
For latest versions, use following steps:
Here is my list (updated for 1.0):
// sending to sender-client only
socket.emit('message', "this is a test");
// sending to all clients, include sender
io.emit('message', "this is a test");
// sending to all clients except sender
socket.broadcast.emit('message', "this is a test");
// sending to all clients in 'game' room(channel) except sender
socket.broadcast.to('game').emit('message', 'nice game');
// sending to all clients in 'game' room(channel), include sender
io.in('game').emit('message', 'cool game');
// sending to sender client, only if they are in 'game' room(channel)
socket.to('game').emit('message', 'enjoy the game');
// sending to all clients in namespace 'myNamespace', include sender
io.of('myNamespace').emit('message', 'gg');
// sending to individual socketid
socket.broadcast.to(socketid).emit('message', 'for your eyes only');
// list socketid
for (var socketid in io.sockets.sockets) {}
OR
Object.keys(io.sockets.sockets).forEach((socketid) => {});
My workaround for this issue was to set display: inline
to the image element.
With this, your image and text will be aligned to the right if you set text-align: right
from a parent container.
With Scanner the default delimiters are the whitespace characters.
But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:
So useDelimiter()
methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:
And here is an Example:
public static void main(String[] args) {
// Initialize Scanner object
Scanner scan = new Scanner("Anna Mills/Female/18");
// initialize the string delimiter
scan.useDelimiter("/");
// Printing the tokenized Strings
while(scan.hasNext()){
System.out.println(scan.next());
}
// closing the scanner stream
scan.close();
}
Prints this output:
Anna Mills
Female
18
A better and neater solution would be to use $_SESSION:
Using the session:
$_SESSION['POST'] = $_POST;
and for the redirect header request use:
header('Location: http://www.provider.com/process.jsp?id=12345&name=John', true, 307;)
307
is the http_response_code
you can use for the redirection request with submitted POST
values.
I would either one of the following:
Application.Exit();
for a winform or
Environment.Exit(0);
for a console application (works on winforms too).
Thanks!
Guava provides the adapter you want as Int.asList(). There is an equivalent for each primitive type in the associated class, e.g., Booleans
for boolean
, etc.
int foo[] = {1,2,3,4,5,6,7,8,9,0};
Iterable<Integer> fooBar = Ints.asList(foo);
for(Integer i : fooBar) {
System.out.println(i);
}
The suggestions above to use Arrays.asList
won't work, even if they compile because you get an Iterator<int[]>
rather than Iterator<Integer>
. What happens is that rather than creating a list backed by your array, you created a 1-element list of arrays, containing your array.
Thought I knew I had read about that in the standard; but can't find it. Keeps looking. Old; answering heading; not Q-tex ;P:
The following program would determine that:
#include <stdio.h>
#include <stdint.h>
int is_big_endian(void)
{
union {
uint32_t i;
char c[4];
} e = { 0x01000000 };
return e.c[0];
}
int main(void)
{
printf("System is %s-endian.\n",
is_big_endian() ? "big" : "little");
return 0;
}
You also have this approach; from Quake II:
byte swaptest[2] = {1,0};
if ( *(short *)swaptest == 1) {
bigendien = false;
And !is_big_endian()
is not 100% to be little as it can be mixed/middle.
Believe this can be checked using same approach only change value from 0x01000000
to i.e. 0x01020304
giving:
switch(e.c[0]) {
case 0x01: BIG
case 0x02: MIX
default: LITTLE
But not entirely sure about that one ...
From the HTTP 1.1 specification:
no-store:
The purpose of the no-store directive is to prevent the inadvertent release or retention of sensitive information (for example, on backup tapes). The no-store directive applies to the entire message, and MAY be sent either in a response or in a request. If sent in a request, a cache MUST NOT store any part of either this request or any response to it. If sent in a response, a cache MUST NOT store any part of either this response or the request that elicited it. This directive applies to both non- shared and shared caches. "MUST NOT store" in this context means that the cache MUST NOT intentionally store the information in non-volatile storage, and MUST make a best-effort attempt to remove the information from volatile storage as promptly as possible after forwarding it. Even when this directive is associated with a response, users might explicitly store such a response outside of the caching system (e.g., with a "Save As" dialog). History buffers MAY store such responses as part of their normal operation. The purpose of this directive is to meet the stated requirements of certain users and service authors who are concerned about accidental releases of information via unanticipated accesses to cache data structures. While the use of this directive might improve privacy in some cases, we caution that it is NOT in any way a reliable or sufficient mechanism for ensuring privacy. In particular, malicious or compromised caches might not recognize or obey this directive, and communications networks might be vulnerable to eavesdropping.
function Do-SendKeys {
param (
$SENDKEYS,
$WINDOWTITLE
)
$wshell = New-Object -ComObject wscript.shell;
IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
Sleep 1
IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'
You don't need to create a user-defined setting. The built-in setting "Preprocessor Macros" works just fine. alt text http://idisk.mac.com/cdespinosa/Public/Picture%204.png
If you have multiple targets or projects that use the same prefix file, use Preprocessor Macros Not Used In Precompiled Headers instead, so differences in your macro definition don't trigger an unnecessary extra set of precompiled headers.
//CSS:
.textarea {
resize: none;
min-width: //-> Integer number of pixels
min-height: //-> Integer number of pixels
max-width: //-> min-width
max-height: //-> min-height
}
above code works on most browsers
//HTML:
<textarea id='textarea' draggable='false'></textarea>
do both for it to work on the maximum number of browsers
Loop through divs every 10 seconds.
$(function () {
var counter = 0,
divs = $('#div1, #div2, #div3');
function showDiv () {
divs.hide() // hide all divs
.filter(function (index) { return index == counter % 3; }) // figure out correct div to show
.show('fast'); // and show it
counter++;
}; // function to loop through divs and show correct div
showDiv(); // show first div
setInterval(function () {
showDiv(); // show next div
}, 10 * 1000); // do this every 10 seconds
});
(Edit) The previously recomended add-on is not available any longer, you may try this other one
For development purposes in Chrome, installing this add on will get rid of that specific error:
Access to XMLHttpRequest at 'http://192.168.1.42:8080/sockjs-node/info?t=1546163388687'
from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the
'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'
when the request's credentials mode is 'include'. The credentials mode of requests
initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
After installing, make sure you add your url pattern to the Intercepted URLs
by clicking on the AddOn's (CORS, green or red) icon and filling the appropriate textbox. An example URL pattern to add here that will work with http://localhost:8080
would be: *://*
Besides the correct answers offered as long term solutions, you can use git to remove all unnecessary files once for you with the git clean -f
command but use git clean --dry-run
first to ensure nothing unintended would happen.
This has the benefit of using tested built in functionality of Git over scripts specific to your OS/shell to remove the files.
I found the following was a better solution depending on the content of your left, center and right items. A width of 100% without a margin caused overlapping of divs and was preventing anchor tags to work correctly - that is without the messy use of z-indexes.
.navbar-brand
{
position: absolute;
width: 100%;
left: 0;
margin: auto;
margin-left: 48%;
}
you can directly send mail from php mail() function if you specified the smtp server and smtp port in php.ini, first ask the SMTP server credential to your ISP.
SMTP = smtp.wlink.com.np //put your ISP's smtp server
smtp_port = 25 // your ISP's smtp port.
then just restart the apache server and it will start working. ENjoy ...
Another approach:
declaring an int first with the default fontsize
int txtSize = 16;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTextView.setTextSize(txtSize++);
}
});
You can download the 10.7 Lion JDK from http://connect.apple.com.
Sign in and click the java
section on the right.
The jdk is installed into a different location then previous. This will result in IDEs (such as Eclipse) being unable to locate source code and javadocs.
At the time of writing the JDK ended up here:
/Library/Java/JavaVirtualMachines/1.6.0_26-b03-383.jdk/Contents/Home
Open up eclipse preferences and go to Java --> Installed JREs page
Rather than use the "JVM Contents (MacOS X Default) we will need to use the JDK location
At the time of writing Search is not aware of the new JDK location; we we will need to click on the Add button
From the Add JRE wizard choose "MacOS X VM" for the JRE Type
For the JRE Definition Page we need to fill in the following:
The other fields will now auto fill, with the default JRE name being "Home". You can quickly correct this to something more meaningful:
Finish the wizard and return to the Installed JREs page
Choose "System JDK" from the list
You can now develop normally with:
Although this question is a bit old, this service tip might help users searching for a similar solution checking email addresses beyond syntax validation prior to sending.
I have been using this open sourced service for a more in depth validating of emails (checking for mx records on the e-mail address domain etc.) for a few projects with good results. It also checks for common typos witch is quite useful. Demo here.
to copy one list into the other list, u can use the method called Collection.copy(myObject myTempObject).now after executing these line of code u can see all the list values in the myObject.
var CurrentMouseXPostion;
var CurrentMouseYPostion;
$(document).mousemove(function(event) {
CurrentMouseXPostion = event.pageX;
CurrentMouseYPostion = event.pageY;
});
Make an eventListener on the main object , in my case the document object, to get the mouse coords every frame and store them in global variables, and like that you can read mouse Y & Z whenever youlike , wherever you like.
I found a new and undocumented reason for status == 0. Here is what I had:
XMLHttpRequest.status === 0
XMLHttpRequest.readyState === 0
XMLHttpRequest.responseText === ''
XMLHttpRequest.state() === 'rejected'
It was not cross-origin, network, or due to cancelled requests (by code or by user navigation). Nothing in the developer console or network log.
I could find very little documentation on state() (Mozilla does not list it, W3C does) and none of it mentioned "rejected".
Turns out it was my ad blocker (uBlock Origin on Firefox).
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(typeof(YourObjectType));
YourObjectType yourObject = (YourObjectType)serializer.ReadObject(jsonStream);
You could also use the JavaScriptSerializer
, but DataContractJsonSerializer
is supposedly better able to handle complex types.
Oddly enough JavaScriptSerializer was once deprecated (in 3.5) and then resurrected because of ASP.NET MVC (in 3.5 SP1). That would definitely be enough to shake my confidence and lead me to use DataContractJsonSerializer
since it is hard baked for WCF.
Try this:
<tr ng-repeat="player in players | filter:{id: player_id, name:player_name} | filter:ageFilter">
$scope.ageFilter = function (player) {
return (player.age > $scope.min_age && player.age < $scope.max_age);
}
Math.floor()
will always round down ie., it returns LESSER integer. While round()
will return the NEAREST integer
math.floor()
Returns the largest integer less than or equal to the specified number.
math.truncate()
Calculates the integral part of a number.
Alternatively to Martin's answer, you could also add the INTO part at the end of the query to make the query more readable:
SELECT Id, dateCreated FROM products INTO iId, dCreate
comp:~$ python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2
>>> import timeit
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)
5.656799077987671
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)
5.579368829727173
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)
21.54827117919922
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)
22.014557123184204
With timeit number=1 param:
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)
0.2245171070098877
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=1)
0.10750913619995117
comp:~$ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)
9.113872020003328
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)
9.07014398300089
With timeit number=1,2,3,4 param works quick and in linear way:
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)
0.09329321900440846
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=2)
0.18501482300052885
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=3)
0.2703447980020428
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=4)
0.36209142999723554
So it seems if we measure 1 running loop cycle like timeit.timeit("[x for x in range(1000000) if x%4]",number=1) (as we actually use in real code) python3 works quick enough, but in repeated loops python 2 xrange() wins in speed against range() from python 3.
try using the Date
property on the DateTime
Object...
if(dtOne.Date == dtTwo.Date)
....
There is also a plot.background
option in addition to panel.background
:
df <- data.frame(y=d,x=1)
p <- ggplot(df) + stat_boxplot(aes(x = x,y=y))
p <- p + opts(
panel.background = theme_rect(fill = "transparent",colour = NA), # or theme_blank()
panel.grid.minor = theme_blank(),
panel.grid.major = theme_blank(),
plot.background = theme_rect(fill = "transparent",colour = NA)
)
#returns white background
png('tr_tst2.png',width=300,height=300,units="px",bg = "transparent")
print(p)
dev.off()
For some reason, the uploaded image is displaying differently than on my computer, so I've omitted it. But for me, I get a plot with an entirely gray background except for the box part of the boxplot which is still white. That can be changed using the fill aesthetic in the boxplot geom as well, I believe.
Edit
ggplot2 has since been updated and the opts()
function has been deprecated. Currently, you would use theme()
instead of opts()
and element_rect()
instead of theme_rect()
, etc.
<p class="pull-left">Text left</p>
<p class="text-right">Text right in same line</p>
This work for me.
edit: An example with your snippet:
@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.css');_x000D_
.container {_x000D_
margin-top: 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="row-fluid">_x000D_
<div class="span6 pull-left">_x000D_
<p>Text left</p>_x000D_
</div>_x000D_
<div class="span6 text-right">_x000D_
<p>text right</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
I use this command for scripts which extracts data for dimensional tables (DW). So, I use the following syntax:
set colsep '|'
set echo off
set feedback off
set linesize 1000
set pagesize 0
set sqlprompt ''
set trimspool on
set headsep off
spool output.dat
select '|', <table>.*, '|'
from <table>
where <conditions>
spool off
And works. I don't use sed for format the output file.
Based on your edit and comments.. would this be what you're after?
byte[] newByteArray = UTF8Encoding.UTF8.GetBytes(Convert.ToBase64String(currentByteArray));
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.Performing a lock: Quite cheap (still more expensive than a null test).
Performing a lock when another thread has it: You get the cost of whatever they've still to do while locking, added to your own time.
Performing a lock when another thread has it, and dozens of other threads are also waiting on it: Crippling.
For performance reasons, you always want to have locks that another thread wants, for the shortest period of time at all possible.
Of course it's easier to reason about "broad" locks than narrow, so it's worth starting with them broad and optimising as needed, but there are some cases that we learn from experience and familiarity where a narrower fits the pattern.
(Incidentally, if you can possibly just use private static volatile Singleton instance = new Singleton()
or if you can possibly just not use singletons but use a static class instead, both are better in regards to these concerns).
For people like me, linq addicts, and based on svick's answer, here a linq approach:
using System.Linq;
//...
//make it linq iterable.
var obj_linq = Response.Cast<KeyValuePair<string, JToken>>();
Now you can make linq expressions like:
JToken x = obj_linq
.Where( d => d.Key == "my_key")
.Select(v => v)
.FirstOrDefault()
.Value;
string y = ((JValue)x).Value;
Or just:
var y = obj_linq
.Where(d => d.Key == "my_key")
.Select(v => ((JValue)v.Value).Value)
.FirstOrDefault();
Or this one to iterate over all data:
obj_linq.ToList().ForEach( x => { do stuff } );
here's my solution (coffeescript) :
_.mixin
deepUniq: (coll) ->
result = []
remove_first_el_duplicates = (coll2) ->
rest = _.rest(coll2)
first = _.first(coll2)
result.push first
equalsFirst = (el) -> _.isEqual(el,first)
newColl = _.reject rest, equalsFirst
unless _.isEmpty newColl
remove_first_el_duplicates newColl
remove_first_el_duplicates(coll)
result
example:
_.deepUniq([ {a:1,b:12}, [ 2, 1, 2, 1 ], [ 1, 2, 1, 2 ],[ 2, 1, 2, 1 ], {a:1,b:12} ])
//=> [ { a: 1, b: 12 }, [ 2, 1, 2, 1 ], [ 1, 2, 1, 2 ] ]
These answers are much too complicated.
A simpler way to do this without creating two arcs or convert to different coordinate systems..
This assumes your canvas area has width w
and height h
.
`M${w*0.5 + radius},${h*0.5}
A${radius} ${radius} 0 1 0 ${w*0.5 + radius} ${h*0.5001}`
Just use the "long arc" flag, so the full flag is filled. Then make the arcs 99.9999% the full circle. Visually it is the same. Avoid the sweep flag by just starting the circle at the rightmost point in the circle (one radius directly horizontal from the center).
when you pushing code to another branch just follow the below git command. Remember demo is my other branch name you can replace with your branch name.
git push origin master:demo
Sometimes changing the namespace of the tests work. I had the folder structure as follows:
A
|___B
| |___D
|___C___E
The namespace was flat like Tests.< name > and they did not show up in the test window. When I changed the namespace to the structure of the directory, all the tests showed up. Now I could revert back to any other namespace structure I want.
Do not forget to build your project!
I have a simple solution for you!
{{ form.data.email }}
I tried this and it worked. This requires your view to populate the form class with the POST data.
Very simple example:
def your_view(request):
if request.method == 'POST':
form = YourForm(request.POST)
if form.is_valid():
# some code here
else:
form = YourForm()
return render_to_response('template.html', {'form':form})
Hope that helps you. If you have any questions please let me know.
You could try something like:
WebElement rxBtn = driver.findElement(By.className("icon-rx"));
WebElement otcBtn = driver.findElement(By.className("icon-otc"));
WebElement herbBtn = driver.findElement(By.className("icon-herb"));
Assert.assertEquals(true, rxBtn.isDisplayed());
Assert.assertEquals(true, otcBtn.isDisplayed());
Assert.assertEquals(true, herbBtn.isDisplayed());
This is just an example. Basically you declare and define the WebElement variables you wish to use and then Assert
whether or not they are displayed. This is using TestNG Assertions.
Print integer in hex-value with zero-padding (if needed) :
int intValue = 1234;
Console.WriteLine("{0,0:D4} {0,0:X3}", intValue);
https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros
I have installed my wamp server in D: drive so u have to go to the following path from ur command line->(and if u have installed ur wamp in c: drive then just replace the d: wtih c: here)
D:\>cd wamp
D:\wamp>cd bin
D:\wamp\bin>cd mysql
D:\wamp\bin\mysql>cd mysql5.5.8 (whatever ur verserion will be displayed here use keyboard Tab button)
D:\wamp\bin\mysql\mysql5.5.8>cd bin
D:\wamp\bin\mysql\mysql5.5.8\bin>mysql -u root -p password db_name < "d:\backupfile.sql"
here root is user of my phpmyadmin password is the password for phpmyadmin so if u haven't set any password for root just nothing type at that place, db_name is the database (for which database u r taking the backup) ,backupfile.sql is the file from which u want ur backup of ur database and u can also change the backup file location(d:\backupfile.sql) from to any other place on your computer
This code is ill-formed:
int&const icr=i;
Reference: C++17 [dcl.ref]/1:
Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name or decltype-specifier, in which case the cv-qualifiers are ignored.
This rule has been present in all standardized versions of C++. Because the code is ill-formed:
The compiler should reject the program; and if it doesn't, the executable's behaviour is completely undefined.
NB: Not sure how none of the other answers mentioned this yet... nobody's got access to a compiler?
I just got done doing this exact thing in a project. The HTML side looked a bit like this:
<a href="[fullsize]" class="gallerypic" title="">
<img src="[thumbnail pic]" height="90" width="140" alt="[Gallery Photo]" class="pic" />
<span class="zoom-icon">
<img src="/images/misc/zoom.gif" width="32" height="32" alt="Zoom">
</span>
</a>
Then using CSS:
a.gallerypic{
width:140px;
text-decoration:none;
position:relative;
display:block;
border:1px solid #666;
padding:3px;
margin-right:5px;
float:left;
}
a.gallerypic span.zoom-icon{
visibility:hidden;
position:absolute;
left:40%;
top:35%;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
}
a.gallerypic:hover span.zoom-icon{
visibility:visible;
}
I left a lot of the sample in there on the CSS so you can see how I decided to do the style. Note I lowered the opacity so you could see through the magnifying glass.
Hope this helps.
EDIT: To clarify for your example - you could ignore the visibility:hidden;
and kill the :hover
execution if you wanted, this was just the way I did it.
look at yt:statistics
tag.
It provides viewCount
, videoWatchCount
, favoriteCount
etc.
awk 's+=$2{print s/NR}' table | tail -1
I am using tail -1
to print the last line which should have the average number...
edittext.requestFocus()
works for me in my Activity
and Fragment
df =df['Date'].dt.dayofweek
dayofweek
is in numeric format