If you
then you can
git reset --soft HEAD~(number of commits you'd like to revert)
git commit -m "The stuff you didn't like."
git log
# copy the hash of your last commit
git revert <hash of your last (squashed) commit>
Then when you want to push your changes remember to use the -f
flag because you modified the history
git push <your fork> <your branch> -f
By default git revert
refuses to revert a merge commit as what that actually means is ambiguous. I presume that your HEAD
is in fact a merge commit.
If you want to revert the merge commit, you have to specify which parent of the merge you want to consider to be the main trunk, i.e. what you want to revert to.
Often this will be parent number one, for example if you were on master
and did git merge unwanted
and then decided to revert the merge of unwanted
. The first parent would be your pre-merge master
branch and the second parent would be the tip of unwanted
.
In this case you could do:
git revert -m 1 HEAD
Identify the hash of the commit, using git log
, then use git revert <commit>
to create a new commit that removes these changes. In a way, git revert
is the converse of git cherry-pick
-- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.
First, reset any changes
This will undo any changes you've made to tracked files and restore deleted files:
git reset HEAD --hard
Second, remove new files
This will delete any new files that were added since the last commit:
git clean -fd
Files that are not tracked due to .gitignore
are preserved; they will not be removed
Warning: using -x
instead of -fd
would delete ignored files. You probably don't want to do this.
Try simply to reset last commit using --soft
flag
git reset --soft HEAD~1
Note :
For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"
To revert the revert without screwing up your workflow too much:
Your feature branch should now be able to be merged as normal when you're ready for it. The only downside here is that you'll a have a few extra merge/revert commits in your history.
WARNING:
git clean -f
will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.
Try this and see git clean -f
.
git reset --hard
will not remove untracked files, where as git-clean
will remove any files from the tracked root directory that are not under Git tracking.
Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)
git clean -df
git clean -xdf
CAUTION! This will also delete ignored filesTry this:
git checkout [revision] .
where [revision]
is the commit hash (for example: 12345678901234567890123456789012345678ab
).
Don't forget the .
at the end, very important. This will apply changes to the whole tree. You should execute this command in the git project root. If you are in any sub directory, then this command only changes the files in the current directory. Then commit and you should be good.
You can undo this by
git reset --hard
that will delete all modifications from the working directory and staging area.
If you broke the tree but didn't commit the code, you can use git reset
, and if you just want to restore one file, you can use git checkout
.
If you broke the tree and committed the code, you can use git revert HEAD
.
http://book.git-scm.com/4_undoing_in_git_-_reset,_checkout_and_revert.html
OK, going back to a previous commit in Git is quite easy...
Revert back without keeping the changes:
git reset --hard <commit>
Revert back with keeping the changes:
git reset --soft <commit>
Explanation: using git reset
, you can reset to a specific state. It's common using it with a commit hash as you see above.
But as you see the difference is using the two flags --soft
and --hard
, by default git reset
using --soft
flag, but it's a good practice always using the flag, I explain each flag:
The default flag as explained, not need to provide it, does not change the working tree, but it adds all changed files ready to commit, so you go back to the commit status which changes to files get unstaged.
Be careful with this flag. It resets the working tree and all changes to tracked files and all will be gone!
I also created the image below that may happen in a real life working with Git:
You don't want git revert
. That undoes a previous commit. You want git checkout
to get git's version of the file from master.
git checkout -- filename.txt
In general, when you want to perform a git operation on a single file, use -- filename
.
2020 Update
Git introduced a new command git restore
in version 2.23.0
. Therefore, if you have git version 2.23.0+
, you can simply git restore filename.txt
- which does the same thing as git checkout -- filename.txt
. The docs for this command do note that it is currently experimental.
First reset
locally:
git reset 23b6772
To see if you're on the right position, verify with:
git status
You will see something like:
On branch master Your branch is behind 'origin/master' by 17 commits, and can be fast-forwarded.
Then rewrite history on your remote tracking branch to reflect the change:
git push --force-with-lease // a useful command @oktober mentions in comments
Using --force-with-lease
instead of --force
will raise an error if others have meanwhile committed to the remote branch, in which case you should fetch first. More info in this article.
Use "git checkout -- ..." to discard changes in working directory
git checkout -- app/views/posts/index.html.erb
or
git checkout -- *
removes all changes made to unstaged files in git status eg
modified: app/controllers/posts.rb
modified: app/views/posts/index.html.erb
I used the javascript date funtion toLocaleDateString to get
var Today = new Date();
var r = Today.toLocaleDateString();
The result of r will be
11/29/2016
More info at: http://www.w3schools.com/jsref/jsref_tolocaledatestring.asp
I don't know why but:
#ifdef main
#undef main
#endif
After the includes but before your main should fix it from my experience.
Just to expand on this error in the context of an interface, if you are type hinting your function parameters like so:
interface A
use Bar;
interface A
{
public function foo(Bar $b);
}
Class B
class B implements A
{
public function foo(Bar $b);
}
If you have forgotten to include the use
statement on your implementing class (Class B), then you will also get this error even though the method parameters are identical.
I'll throw this in as an alternative just for the heck of it, even though it's pretty much useless when compared to " ".join(my_list)
for strings. For non-strings (such as an array of ints) this may be better:
" ".join(str(item) for item in my_list)
The following has a pretty comprehensive guide on how to configure and present popovers. https://www.appcoda.com/presentation-controllers-tutorial/
In summary, a viable implementation (with some updates from the original article syntax for Swift 4.2), to then be called from elsewhere, would be something like the following:
func showPopover(ofViewController popoverViewController: UIViewController, originView: UIView) {
popoverViewController.modalPresentationStyle = UIModalPresentationStyle.popover
if let popoverController = popoverViewController.popoverPresentationController {
popoverController.delegate = self
popoverController.sourceView = originView
popoverController.sourceRect = originView.bounds
popoverController.permittedArrowDirections = UIPopoverArrowDirection.any
}
self.present(popoverViewController, animated: true)
}
A lot of this was already covered in the answer from @mmc, but the article helps to explain some of those code elements used, and also show how it could be expanded.
It also provides a lot of additional detail about using delegation to handle the presentation style for iPhone vs. iPad, and to allow dismissal of the popover if it's ever shown full-screen. Again, updated for Swift 4.2:
func adaptivePresentationStyle(for: UIPresentationController) -> UIModalPresentationStyle {
//return UIModalPresentationStyle.fullScreen
return UIModalPresentationStyle.none
}
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
if traitCollection.horizontalSizeClass == .compact {
return UIModalPresentationStyle.none
//return UIModalPresentationStyle.fullScreen
}
//return UIModalPresentationStyle.fullScreen
return UIModalPresentationStyle.none
}
func presentationController(_ controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? {
switch style {
case .fullScreen:
let navigationController = UINavigationController(rootViewController: controller.presentedViewController)
let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(doneWithPopover))
navigationController.topViewController?.navigationItem.rightBarButtonItem = doneButton
return navigationController
default:
return controller.presentedViewController
}
}
// As of Swift 4, functions used in selectors must be declared as @objc
@objc private func doneWithPopover() {
self.dismiss(animated: true, completion: nil)
}
Hope this helps.
Try the following:
CONCAT(datepart(yyyy,DATE),'-', DATEPART(qq,DATE))
It returns:
yyyy-q
Example: 2017-3
for 2017-07-11
So to fix this properly, I did what others here did and used css to get hide the horizontal toolbar:
.name {
max-width: 100%;
overflow-x: hidden;
}
Then in js, I created an event listener to look for scrolling, and counteracted the users attempted horizontal scroll.
var scrollEventHandler = function()
{
window.scroll(0, window.pageYOffset)
}
window.addEventListener("scroll", scrollEventHandler, false);
I saw somebody do something similar, but apparently that didn't work. This however is working perfectly fine for me.
span
s are by default displayed inline, which means they don't have a height and width.
Try adding a display: block
to your span.
This worked for me.
<table>
<tr>
<td *ngFor="#group of groups">
<h1>{{group.name}}</h1>
</td>
</tr>
</table>
Strictly speaking, there is no single configuration file. Excluding ASP.NET1 there can be three configuration files using the inbuilt (System.Configuration
) support. In addition to the machine config: app.exe.config
, user roaming, and user local.
To get the "global" configuration (exe.config):
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
.FilePath
Use different ConfigurationUserLevel
values for per-use roaming and non-roaming configuration files.
1 Which has a completely different model where the content of a child folders (IIS-virtual or file system) web.config
can (depending on the setting) add to or override the parent's web.config
.
Reset (Clear) Form throught Javascript
& jQuery
:
Example Javascript:
document.getElementById("client").reset();
Example jQuery:
You may try using trigger()
Reference Link
$('#client.frm').trigger("reset");
With PHP 5.6 on Amazon Linux (should be the same on RedHat or CentOS):
yum install php56-opcache
and then restart apache.
You can do it by using a constructor, like this:
struct Date
{
int day;
int month;
int year;
Date()
{
day=0;
month=0;
year=0;
}
};
or like this:
struct Date
{
int day;
int month;
int year;
Date():day(0),
month(0),
year(0){}
};
In your case bar.c is undefined,and its value depends on the compiler (while a and b were set to true).
In Oracle the location that contains information about all database objects including tables and stored procedures is called the Data Dictionary. It is a collection of views that provides you with access to the metadata that defines the database. You can query the Data Dictionary views for a list of desired database objects and then use the functions available in dbms_metadata
package to get the DDL for each object. Alternative is to investigate the support in dbms_metadata
to export DDLs for a collection of objects.
For a few pointers, for example to get a list of tables you can use the following Data Dictionary views
user_tables
contains all tables owned by the userall_tables
contains all tables that are accessible by the userYou can write the where
clause as:
where (case when (:stateCode = '') then (1)
when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
else 0)
end) = 1;
Alternatively, remove the case
entirely:
where (:stateCode = '') or
((:stateCode != '') and vw.state_cd in (:stateCode));
Or, even better:
where (:stateCode = '') or vw.state_cd in (:stateCode)
from msdn Do not use a variable in a SELECT statement to concatenate values (that is, to compute aggregate values). Unexpected query results may occur. This is because all expressions in the SELECT list (including assignments) are not guaranteed to be executed exactly once for each output row
The above seems to say that concatenation as done above is not valid as the assignment might be done more times than there are rows returned by the select
Almost the same as skornos, but with variable declarations for a more explicit answer. It can work with Flask-RESTful extension:
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class UserAPI(Resource):
def show(userId, username=None):
pass
api.add_resource(UserAPI, '/<userId>', '/<userId>/<username>', endpoint='user')
if __name__ == '__main__':
app.run()
The add_resource
method allows pass multiples URLs. Each one will be routed to your Resource.
He're the full migration for Laravel 5:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('user_id')->nullable()->change();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('user_id')->nullable(false)->change();
});
}
The point is, you can remove nullable
by passing false
as an argument.
You need to add gravity to the layout not the Button, gravity in button settings is for Text inside the button
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_gravity="right"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
//Runs function after x seconds
public static func runThisAfterDelay(seconds: Double, after: @escaping () -> Void) {
runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after)
}
public static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping () -> Void) {
let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
queue.asyncAfter(deadline: time, execute: after)
}
//Use:-
runThisAfterDelay(seconds: x){
//write your code here
}
I know you asked to Rebase, but I'd Cherry-Pick the commits I wanted to move from Branch2 to Branch1 instead. That way, I wouldn't need to care about when which branch was created from master, and I'd have more control over the merging.
a -- b -- c <-- Master
\ \
\ d -- e -- f -- g <-- Branch1 (Cherry-Pick f & g)
\
f -- g <-- Branch2
The Substring
method provides us a way to extract a particular string from the original string based on a starting position and length. If only one argument is provided, it is taken to be the starting position, and the remainder of the string is outputted.
PS > "test_string".Substring(0,4)
Test
PS > "test_string".Substring(4)
_stringPS >
But this is easier...
$s = 'Hello World is in here Hello World!'
$p = 'Hello World'
$s -match $p
And finally, to recurse through a directory selecting only the .txt files and searching for occurrence of "Hello World":
dir -rec -filter *.txt | Select-String 'Hello World'
Make sure that sleep.sh
has execution permissions, and run it with shell=True
:
#!/usr/bin/python
import subprocess
print "start"
subprocess.call("./sleep.sh", shell=True)
print "end"
If you need just one character and you don't want to keep things in the buffer, you can simply read a whole line and drop everything that isn't needed.
Replace:
stdin.read(1)
with
stdin.readline().strip()[:1]
This will read a line, remove spaces and newlines and just keep the first character.
They are indeed both the same, functionally.
But if the endif
is getting too far from the correspondent if
I think it's much better practice to give a referencing comment to it. Just so you can easily find where it was open. No matter what language it is:
if (my_horn_is_red or her_umbrella_is_yellow)
{
// ...
// let's pretend this is a lot of code in the middle
foreach (day in week) {
sing(a_different_song[day]);
}
// ...
} //if my_horn_is_red
That actually applies to any analogous "closing thing"! ;)
Also, in general, editors deal better with curly brackets, in the sense they can point you to where it was open. But even that doesn't make the descriptive comments any less valid.
You just need to add 'table-layout: fixed;'
.table {
display: table;
height: 100px;
width: 100%;
table-layout: fixed;
}
The correct way would be:
location / {
rewrite (.*) base.html last;
}
Using last
will make nginx find a new suitable location
block according to the result of rewriting.
try_files
is also a perfectly valid approach to this problem.
Thanks guys for help. From your suggestions i reached a solution like this.
new LayoutBuilder(
builder:
(BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints:
BoxConstraints(minHeight: viewportConstraints.maxHeight),
child: Column(children: [
// remaining stuffs
]),
),
);
},
)
I had a similar problem recently, and google landed me here, so I put this answer here in case others land here as well, for completeness.
I noticed that when I had badly formatted html, I was actually having all my html tags stripped out, with just the non-tag content remaining. I particularly had a table with a missing opening table tag, and then all my html tags from the entire string where ripped out completely.
So, if the above doesn't work, and you're still scratching your head, then also check you html for being valid.
I notice even after I got it working, MVC was adding tbody tags where I had none. This tells me there is clean up happening (MVC 5), and that when it can't happen, it strips out all/some tags.
I'm a bit confused by the quotes, however, below should work for you:
SELECT "Gc_Staff_Number",
"Start_Date", x.end_date
FROM "Employment_History" eh,
(SELECT "End_Date"
FROM "Employment_History"
WHERE "Current_Flag" != 'Y'
AND ROWNUM = 1
AND "Employee_Number" = eh.Employee_Number
ORDER BY "End_Date" ASC) x
WHERE "Current_Flag" = 'Y'
package name with 0 may cause problem for sharedPreference.
(OK) con = createPackageContext("com.example.android.sf1", 0);
(Problem but no error)
con = createPackageContext("com.example.android.sf01", 0);
I have a workaround using jquery... although we cannot style a particular option, we can style the select itself - and use javascript to change the class of the select based on what is selected. It works sufficiently for simple cases.
$('select.potentially_red').on('change', function() {_x000D_
if ($(this).val()=='red') {_x000D_
$(this).addClass('option_red');_x000D_
} else {_x000D_
$(this).removeClass('option_red');_x000D_
}_x000D_
});_x000D_
$('select.potentially_red').each( function() {_x000D_
if ($(this).val()=='red') {_x000D_
$(this).addClass('option_red');_x000D_
} else {_x000D_
$(this).removeClass('option_red');_x000D_
}_x000D_
});
_x000D_
.option_red {_x000D_
background-color: #cc0000; _x000D_
font-weight: bold; _x000D_
font-size: 12px; _x000D_
color: white;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<!-- The js will affect all selects which have the class 'potentially_red' -->_x000D_
<select name="color" class="potentially_red">_x000D_
<option value="red">Red</option>_x000D_
<option value="white">White</option>_x000D_
<option value="blue">Blue</option>_x000D_
<option value="green">Green</option>_x000D_
</select>
_x000D_
Note that the js is in two parts, the each
part for initializing everything on the page correctly, the .on('change', ...
part for responding to change. I was unable to mangle the js into a function to DRY it up, it breaks it for some reason
#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
int main() {
vector<int> v = {2,7,6,10};
cout<<"Sum of all the elements are:"<<endl;
cout<<accumulate(v.begin(),v.end(),0);
}
Go to Python Website/dowloads/windows. Download Windows x86-64 embeddable zip file. 2. Open Windows Explorer
open zipped folder python-3.7.0 In the windows toolbar with the Red flair saying “Compressed Folder Tool” Press “Extract” button on the tool bar with “File” “Home “Share” “View” Select Extract all Extraction process is not covered yet Once extracted save onto SDD or fastest memory device. Not usb. HDD is fine. SDD Users/butte/ProgramFiles blah blah ooooor D:\Python Or Hook up to your cloud 3. Click your User Icon in the Windows tool bar.
Search environment variable Proceed with progressing with “Environment Variables” button press Under the “user variables” table select “New..” After the Canvas of Information Add Python in Variable Name Select the “D:\Python\python-3.7.0-embed-amd64\python.exe;” click ok Under the “System Variables” label and in the Canvas the first row has a value marked “Path” Select “Edit” when “Path” is highlighted. Select “New” Enter D:\Python\python-3.7.0-embed-amd click ok Ok Save and double check Open Power Shell python --help
python --version
Source to tutorial https://thedishbunnybitch.com/2018/08/11/installing-python-on-windows-10-for-powershell/
As json.loads
simply returns a dict, you can use the operators that apply to dicts:
>>> jdata = json.load('{"uri": "http:", "foo", "bar"}')
>>> 'uri' in jdata # Check if 'uri' is in jdata's keys
True
>>> jdata['uri'] # Will return the value belonging to the key 'uri'
u'http:'
Edit: to give an idea regarding how to loop through the data, consider the following example:
>>> import json
>>> jdata = json.loads(open ('bookmarks.json').read())
>>> for c in jdata['children'][0]['children']:
... print 'Title: {}, URI: {}'.format(c.get('title', 'No title'),
c.get('uri', 'No uri'))
...
Title: Recently Bookmarked, URI: place:folder=BOOKMARKS_MENU(...)
Title: Recent Tags, URI: place:sort=14&type=6&maxResults=10&queryType=1
Title: , URI: No uri
Title: Mozilla Firefox, URI: No uri
Inspecting the jdata
data structure will allow you to navigate it as you wish. The pprint
call you already have is a good starting point for this.
Edit2: Another attempt. This gets the file you mentioned in a list of dictionaries. With this, I think you should be able to adapt it to your needs.
>>> def build_structure(data, d=[]):
... if 'children' in data:
... for c in data['children']:
... d.append({'title': c.get('title', 'No title'),
... 'uri': c.get('uri', None)})
... build_structure(c, d)
... return d
...
>>> pprint.pprint(build_structure(jdata))
[{'title': u'Bookmarks Menu', 'uri': None},
{'title': u'Recently Bookmarked',
'uri': u'place:folder=BOOKMARKS_MENU&folder=UNFILED_BOOKMARKS&(...)'},
{'title': u'Recent Tags',
'uri': u'place:sort=14&type=6&maxResults=10&queryType=1'},
{'title': u'', 'uri': None},
{'title': u'Mozilla Firefox', 'uri': None},
{'title': u'Help and Tutorials',
'uri': u'http://www.mozilla.com/en-US/firefox/help/'},
(...)
}]
To then "search through it for u'uri': u'http:'
", do something like this:
for c in build_structure(jdata):
if c['uri'].startswith('http:'):
print 'Started with http'
SELECT t1.a, t2.b
FROM t1
JOIN t2 ON t1.a LIKE '%'+t2.b +'%'
because the last answer not work
See the below code (taken from this post)
Put this code in a Module in VBA (Developer Tab -> Visual Basic)
Dim TimerActive As Boolean
Sub StartTimer()
Start_Timer
End Sub
Private Sub Start_Timer()
TimerActive = True
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
TimerActive = False
End Sub
Private Sub Timer()
If TimerActive Then
ActiveSheet.Cells(1, 1).Value = Time
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End If
End Sub
You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.
Private Sub Workbook_Open()
Module1.StartTimer
End Sub
Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.
This worked for me:
If you wrote your Serialized class object into a file, then made some changes to file and compiled it, and then you try to read an object, then this will happen.
So, write the necessary objects to file again if a class is modified and recompiled.
PS: This is NOT a solution; was meant to be a workaround.
i think i'd try with MAX something like this:
SELECT staff_id, max( date ) from owner.table group by staff_id
then link in your other columns:
select staff_id, site_id, pay_level, latest
from owner.table,
( SELECT staff_id, max( date ) latest from owner.table group by staff_id ) m
where m.staff_id = staff_id
and m.latest = date
You can do this to avoid timezone issue:
public static Date truncDate(Date date) {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
Although Java Date
object is timestamp value, but during truncate, it will be converted to local timezone, so you will get surprising value if you expect value from UTC timezone.
I had this error today and discovered it was an incorrectly-formatted year...
select * from es_timeexpense where parsedate > to_date('12/3/2018', 'MM/dd/yyy')
Notice the year has only three 'y's. It should have 4.
Double-check your format.
Some of the answers no longer work as explained.
Currently here is something that works for me in ansible 2.6.x
when: register_var.stdout is search('some_string')
Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3
Then in the project Add Reference -> Browse. Push the browse button and go to the C:\Users\UserName\Documents\Visual Studio 2015\Projects\ProjectName\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45 and add the needed .dll file
Setting sourceCompatibility = JavaVersion.VERSION_1_8
enables desugaring, but it is currently unable to desugar all the Java 8 features that the Kotlin compiler uses.
Fix - Setting kotlinOptions.jvmTarget to JavaVersion.VERSION_1_8
in the app module Gradle would fix the issue.
Use Java 8 language features: https://developer.android.com/studio/write/java8-support
android {
...
// Configure only for each module that uses Java 8
// language features (either in its source code or
// through dependencies).
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
// For Kotlin projects
kotlinOptions {
jvmTarget = "1.8"
}
}
I looked at Android Source Tree.
Inside com.android.server.am.ActivityManagerService.java (internal service exposed by android.app.ActivityManager).
public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
outInfo.availMem = Process.getFreeMemory();
outInfo.totalMem = Process.getTotalMemory();
outInfo.threshold = homeAppMem;
outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
outInfo.hiddenAppThreshold = hiddenAppMem;
outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
ProcessList.SERVICE_ADJ);
outInfo.visibleAppThreshold = mProcessList.getMemLevel(
ProcessList.VISIBLE_APP_ADJ);
outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
ProcessList.FOREGROUND_APP_ADJ);
}
Inside android.os.Process.java
/** @hide */
public static final native long getFreeMemory();
/** @hide */
public static final native long getTotalMemory();
It calls JNI method from android_util_Process.cpp
Conclusion
MemoryInfo.availMem = MemFree + Cached in /proc/meminfo.
Notes
Total Memory is added in API level 16.
Here is an interesting solution: it uses the browsers CSS engine to to add a dummy property to elements matching the selector and then evaluates the computed style to find matched elements:
It does dynamically create a style rule [...] It then scans the whole document (using the much decried and IE-specific but very fast document.all) and gets the computed style for each of the elements. We then look for the foo property on the resulting object and check whether it evaluates as “bar”. For each element that matches, we add to an array.
I always use the cuttr.js library to truncate strings and add custom ellipsis:
new Cuttr('.container', {
//options here
truncate: 'words',
length: 8,
ending: '... ?'
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/cuttr.min.js"></script>
<p class="container">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. </p>
_x000D_
This is bar far the easiest method (and doesn't have any dependencies) I know to cut strings with JS and its also available as jQuery plugin.
CAUTION: commit any work you wish to retain first.
You may reset your workspace (and recover the deleted files)
git checkout ./*
Solution using only javascript
function saveFile(fileName,urlFile){
let a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
a.href = urlFile;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
let textData = `El contenido del archivo
que sera descargado`;
let blobData = new Blob([textData], {type: "text/plain"});
let url = window.URL.createObjectURL(blobData);
//let url = "pathExample/localFile.png"; // LocalFileDownload
saveFile('archivo.txt',url);
Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.
<div class="modal-backdrop"></div>
Made a small demo: http://jsfiddle.net/PfBnq/
Like other people have said, generally Python strings are supposed to be immutable.
However, if you are using CPython, the implementation at python.org, it is possible to use ctypes to modify the string structure in memory.
Here is an example where I use the technique to clear a string.
Mark data as sensitive in python
I mention this for the sake of completeness, and this should be your last resort as it is hackish.
There's also an option to Auto Sync built-in in Aptana.
I've searched through their docs and it seems there is not xpath option. Also, as you can see here on a similar question on SO, the OP is asking for a translation from xpath to BeautifulSoup, so my conclusion would be - no, there is no xpath parsing available.
After getting used to the var
keyword in C#, I'm starting to use the auto
keyword in C++11. They both determine type by inference and are useful when you just want the compiler to figure out the type for you. Here's the C++11 port of your code:
#include <array>
#include <string>
using namespace std;
array<string, 3> strarr = {"ram", "mohan", "sita"};
for(auto str: strarr) {
listbox.items.add(str);
}
Aside from the Random Class, which generates integers and doubles, consider:
Stack Overflow question Generation of (pseudo) random constrained values of (U)Int64 and Decimal
I've found this is often a misnaming error, if you install from a package manager you bin may be called nodejs so you just need to symlink it like so
ln -s /usr/bin/nodejs /usr/bin/node
I've used node-cron and agenda.
node-cron is a very simple library, which provide very basic and easy to understand api like crontab. It doesn't need any config and just works.
var cronJob = require('cron').CronJob;
var myJob = new cronJob('00 30 11 * * 1-5', function(){...});
myJob.start();
agenda is very powerful and fit for much more complex services. Think about ifttt, you have to run millions of tasks. agenda would be the best choice.
Note: You need Mongodb to use Agenda
var Agenda = require("Agenda");
var agenda = new Agenda({db: { address: 'localhost:27017/agenda-example'}});
agenda.every('*/3 * * * *', 'delete old users');
agenda.start();
Or place the image in a location relative to a class and you don't need all that package/path info in the string itself.
com.xyz.SomeClassInThisPackage.class.getResource( "resources/camera.png" );
That way if you move the class to a different package, you dont have to find all the strings, you just move the class and its resources directory.
Best try for windows:
Open up cmd.
run the following command:
C:\wamp64\bin\apache\apache2.4.17\bin\httpd.exe -d C:/wamp64/bin/apache/apache2.4.17
C:\wamp64\bin\apache\apache2.4.17\bin\ Should be replaced with the path where your Apache is installed.
you use \ because \ is an escape character ;)
If the service could not start it will return the error.
For me it was the DocumentRoot was invalid :)
It looks like data
not contains what you think it contains - check it.
let data={"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"};_x000D_
_x000D_
console.log( data["jobtitel"] );_x000D_
console.log( data.jobtitel );
_x000D_
Some JavaScript engines keep keys in insertion order. V8, for instance, keeps all keys in insertion order except for keys that can be parsed as unsigned 32-bit integers.
This means that if you run either of the following:
var animals = {};
animals['dog'] = true;
animals['bear'] = true;
animals['monkey'] = true;
for (var animal in animals) {
if (animals.hasOwnProperty(animal)) {
$('<li>').text(animal).appendTo('#animals');
}
}
var animals = JSON.parse('{ "dog": true, "bear": true, "monkey": true }');
for (var animal in animals) {
$('<li>').text(animal).appendTo('#animals');
}
You'll consistently get dog, bear, and monkey in that order, on Chrome, which uses V8. Node.js also uses V8. This will hold true even if you have thousands of items. YMMV with other JavaScript engines.
You can try :
@media print {
.table td,
.table th {
background-color: transparent !important;
-webkit-print-color-adjust: exact !important;
}
}
Maybe I'm late, but this helped me accept SDK licenses for OSX,
If you have android SDK tools installed, run the following command
~/Library/Android/sdk/tools/bin/sdkmanager --licenses
Accept all licenses by pressing y
Voila! You have accepted SDK licenses and are good to go..
You can't make change
fire here (correct behavior, since nothing changed). However, you could bind click
as well...though this may fire too often...there's not much middle ground between the two though.
$("#fileID").bind("click change", function() {
//do stuff
});
SOLVED I struggled with this and later on, I realized that I was working on PHP 5.6, so I upgraded to PHP 7.0, then I released there were comments placed by git for conflicting codes. I found something like this in my code <<<<<<<< But solved it.
swift 4:
let username = "username"
let password = "password"
let loginString = "\(username):\(password)"
guard let loginData = loginString.data(using: String.Encoding.utf8) else {
return
}
let base64LoginString = loginData.base64EncodedString()
request.httpMethod = "GET"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
Nice classes by Rich Tebb! I've been using DisplayAttribute and the code did not work for me. The only thing I've added is handling of DisplayAttribute. Brief search yielded that this attribute is new to MVC3 & .Net 4 and does almost the same thing plus more. Here's a modified version of the method:
public static string GetPropertyDisplayString<T>(Expression<Func<T, object>> propertyExpression)
{
var memberInfo = GetPropertyInformation(propertyExpression.Body);
if (memberInfo == null)
{
throw new ArgumentException(
"No property reference expression was found.",
"propertyExpression");
}
var displayAttribute = memberInfo.GetAttribute<DisplayAttribute>(false);
if (displayAttribute != null)
{
return displayAttribute.Name;
}
else
{
var displayNameAttribute = memberInfo.GetAttribute<DisplayNameAttribute>(false);
if (displayNameAttribute != null)
{
return displayNameAttribute.DisplayName;
}
else
{
return memberInfo.Name;
}
}
}
Any chance the build process is looking into the subdirectories and including something it shouldn't? BTW, you can do a legal checkout, then remove the .svn and all it contains. That should give you the same as an export. Try compiling that, before and after removing the metadata, as it were.
Here is a complete AsyncTask
class
public class GetMethodDemo extends AsyncTask<String , Void ,String> {
String server_response;
@Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
}
}
// Converting InputStream to String
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
To Call this AsyncTask
class
new GetMethodDemo().execute("your web-service url");
You are applying the formatting to the workbook that has the code, not the added workbook. You'll want to get in the habit of fully qualifying sheet and range references. The code below does that and works for me in Excel 2010:
Sub test()
Dim wb As Excel.Workbook
Set wb = Workbooks.Add
With wb.Sheets(1)
.Range("A1") = "Acctdate"
.Range("B1") = "Ledger"
.Range("C1") = "CY"
.Range("D1") = "BusinessUnit"
.Range("E1") = "OperatingUnit"
.Range("F1") = "LOB"
.Range("G1") = "Account"
.Range("H1") = "TreatyCode"
.Range("I1") = "Amount"
.Range("J1") = "TransactionCurrency"
.Range("K1") = "USDEquivalentAmount"
.Range("L1") = "KeyCol"
.Range("A2", "A50000").Value = Me.TextBox3.Value
.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
End With
End Sub
If you are using Google App Engine or MongoDB as your backend, and you are using the djangoappengine
library, there is a built in ListField
that does exactly what you want. Further, it's easy to query the Listfield to find all objects that contain an element in the list.
I originally found a CSS way to bypass this when using the Cycle jQuery plugin. Cycle uses JavaScript to set my slide to overflow: hidden
, so when setting my pictures to width: 100%
the pictures would look vertically cut, and so I forced them to be visible with !important
and to avoid showing the slide animation out of the box I set overflow: hidden
to the container div of the slide. Hope it works for you.
UPDATE - New Solution:
Original problem -> http://jsfiddle.net/xMddf/1/
(Even if I use overflow-y: visible
it becomes "auto" and actually "scroll".)
#content {
height: 100px;
width: 200px;
overflow-x: hidden;
overflow-y: visible;
}
The new solution -> http://jsfiddle.net/xMddf/2/
(I found a workaround using a wrapper div to apply overflow-x
and overflow-y
to different DOM elements as James Khoury advised on the problem of combining visible
and hidden
to a single DOM element.)
#wrapper {
height: 100px;
overflow-y: visible;
}
#content {
width: 200px;
overflow-x: hidden;
}
i believe you can use
CREATE TABLE test (
id INTEGER PRIMARY KEY AUTOINCREMENT,
t TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
);
as of version 3.1 (source)
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/
You can use the row_numer() over(partition by ...)
syntax like so:
select * from
(
select *
, ROW_NUMBER() OVER(PARTITION BY CName ORDER BY AddressLine) AS row
from myTable
) as a
where row = 1
What this does is that it creates a column called row
, which is a counter that increments every time it sees the same CName
, and indexes those occurrences by AddressLine
. By imposing where row = 1
, one can select the CName
whose AddressLine
comes first alphabetically. If the order by
was desc
, then it would pick the CName
whose AddressLine
comes last alphabetically.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button").click(function(){
alert("Hello");
});
});
</script>
<input type="button" id="button" value="Click me">
You can try:
SELECT *
FROM public."my_table"
Don't forget double quotes near my_table.
We use
wsdlLocation = "WEB-INF/wsdl/WSDL.wsdl"
In other words, use a path relative to the classpath.
I believe the WSDL may be needed at runtime for validation of messages during marshal/unmarshal.
You can sum up the values of a BigDecimal
stream using a reusable Collector named summingUp
:
BigDecimal sum = bigDecimalStream.collect(summingUp());
The Collector
can be implemented like this:
public static Collector<BigDecimal, ?, BigDecimal> summingUp() {
return Collectors.reducing(BigDecimal.ZERO, BigDecimal::add);
}
if the purpose is to show or hide a part of the page then you can do the following things
1) wrap it in markup with
<% if(somecondition) { %>
some html
<% } %>
2) Wrap the parts in a Panel control and in codebehind use the if statement to set the Visible property of the Panel.
Looks like I got all the possible issues with that installation.
Troubleshooting: look at actual log file (in the log provided by the installer look for LOGFILE=...):
Process.Start: C:\Windows\system32\msiexec.exe /quiet /norestart /i "c:\2964b29c3cd7dcb37c9e\Packages\AppFabric-1.1-for-Windows-Server-64.msi" ADDDEFAULT=Worker,WorkerAdmin,CacheService,CacheClient,CacheAdmin,Setup /l*vx "c:\Temp\AppServerSetup1_1(2014-07-09 11-58-09).log" LOGFILE="c:\Temp\AppServerSetup1_1_CustomActions(2014-07-09 11-58-09).log" INSTALLDIR="C:\Program Files\AppFabric 1.1 for Windows Server" LANGID=en-US
After you located the actual log file, check for errors. I had to:
done. Hope that helps.
It is kind of a workaround but works like a charm. Just add <option value="" style="display: none"></option>
as a filler. Like in:
<select size="4" ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
<option value="" style="display: none"></option>
</select>
Here is another example:
##
## Python Properties Example
##
class GetterSetterExample( object ):
## Set the default value for x ( we reference it using self.x, set a value using self.x = value )
__x = None
##
## On Class Initialization - do something... if we want..
##
def __init__( self ):
## Set a value to __x through the getter / setter... Since __x is defined above, this doesn't need to be set...
self.x = 1234
return None
##
## Define x as a property, ie a getter - All getters should have a default value arg, so I added it - it will not be passed in when setting a value, so you need to set the default here so it will be used..
##
@property
def x( self, _default = None ):
## I added an optional default value argument as all getters should have this - set it to the default value you want to return...
_value = ( self.__x, _default )[ self.__x == None ]
## Debugging - so you can see the order the calls are made...
print( '[ Test Class ] Get x = ' + str( _value ) )
## Return the value - we are a getter afterall...
return _value
##
## Define the setter function for x...
##
@x.setter
def x( self, _value = None ):
## Debugging - so you can see the order the calls are made...
print( '[ Test Class ] Set x = ' + str( _value ) )
## This is to show the setter function works.... If the value is above 0, set it to a negative value... otherwise keep it as is ( 0 is the only non-negative number, it can't be negative or positive anyway )
if ( _value > 0 ):
self.__x = -_value
else:
self.__x = _value
##
## Define the deleter function for x...
##
@x.deleter
def x( self ):
## Unload the assignment / data for x
if ( self.__x != None ):
del self.__x
##
## To String / Output Function for the class - this will show the property value for each property we add...
##
def __str__( self ):
## Output the x property data...
print( '[ x ] ' + str( self.x ) )
## Return a new line - technically we should return a string so it can be printed where we want it, instead of printed early if _data = str( C( ) ) is used....
return '\n'
##
##
##
_test = GetterSetterExample( )
print( _test )
## For some reason the deleter isn't being called...
del _test.x
Basically, the same as the C( object ) example except I'm using x instead... I also don't initialize in __init - ... well.. I do, but it can be removed because __x is defined as part of the class....
The output is:
[ Test Class ] Set x = 1234
[ Test Class ] Get x = -1234
[ x ] -1234
and if I comment out the self.x = 1234 in init then the output is:
[ Test Class ] Get x = None
[ x ] None
and if I set the _default = None to _default = 0 in the getter function ( as all getters should have a default value but it isn't passed in by the property values from what I've seen so you can define it here, and it actually isn't bad because you can define the default once and use it everywhere ) ie: def x( self, _default = 0 ):
[ Test Class ] Get x = 0
[ x ] 0
Note: The getter logic is there just to have the value be manipulated by it to ensure it is manipulated by it - the same for the print statements...
Note: I'm used to Lua and being able to dynamically create 10+ helpers when I call a single function and I made something similar for Python without using properties and it works to a degree, but, even though the functions are being created before being used, there are still issues at times with them being called prior to being created which is strange as it isn't coded that way... I prefer the flexibility of Lua meta-tables and the fact I can use actual setters / getters instead of essentially directly accessing a variable... I do like how quickly some things can be built with Python though - for instance gui programs. although one I am designing may not be possible without a lot of additional libraries - if I code it in AutoHotkey I can directly access the dll calls I need, and the same can be done in Java, C#, C++, and more - maybe I haven't found the right thing yet but for that project I may switch from Python..
Note: The code output in this forum is broken - I had to add spaces to the first part of the code for it to work - when copy / pasting ensure you convert all spaces to tabs.... I use tabs for Python because in a file which is 10,000 lines the filesize can be 512KB to 1MB with spaces and 100 to 200KB with tabs which equates to a massive difference for file size, and reduction in processing time...
Tabs can also be adjusted per user - so if you prefer 2 spaces width, 4, 8 or whatever you can do it meaning it is thoughtful for developers with eye-sight deficits.
Note: All of the functions defined in the class aren't indented properly because of a bug in the forum software - ensure you indent it if you copy / paste
You can list the tags on remote repository with ls-remote
, and then check if it's there. Supposing the remote reference name is origin
in the following.
git ls-remote --tags origin
And you can list tags local with tag
.
git tag
You can compare the results manually or in script.
For anyone interested in computing multiple distances at once, I've done a little comparison using perfplot (a small project of mine).
The first advice is to organize your data such that the arrays have dimension (3, n)
(and are C-contiguous obviously). If adding happens in the contiguous first dimension, things are faster, and it doesn't matter too much if you use sqrt-sum
with axis=0
, linalg.norm
with axis=0
, or
a_min_b = a - b
numpy.sqrt(numpy.einsum('ij,ij->j', a_min_b, a_min_b))
which is, by a slight margin, the fastest variant. (That actually holds true for just one row as well.)
The variants where you sum up over the second axis, axis=1
, are all substantially slower.
Code to reproduce the plot:
import numpy
import perfplot
from scipy.spatial import distance
def linalg_norm(data):
a, b = data[0]
return numpy.linalg.norm(a - b, axis=1)
def linalg_norm_T(data):
a, b = data[1]
return numpy.linalg.norm(a - b, axis=0)
def sqrt_sum(data):
a, b = data[0]
return numpy.sqrt(numpy.sum((a - b) ** 2, axis=1))
def sqrt_sum_T(data):
a, b = data[1]
return numpy.sqrt(numpy.sum((a - b) ** 2, axis=0))
def scipy_distance(data):
a, b = data[0]
return list(map(distance.euclidean, a, b))
def sqrt_einsum(data):
a, b = data[0]
a_min_b = a - b
return numpy.sqrt(numpy.einsum("ij,ij->i", a_min_b, a_min_b))
def sqrt_einsum_T(data):
a, b = data[1]
a_min_b = a - b
return numpy.sqrt(numpy.einsum("ij,ij->j", a_min_b, a_min_b))
def setup(n):
a = numpy.random.rand(n, 3)
b = numpy.random.rand(n, 3)
out0 = numpy.array([a, b])
out1 = numpy.array([a.T, b.T])
return out0, out1
perfplot.save(
"norm.png",
setup=setup,
n_range=[2 ** k for k in range(22)],
kernels=[
linalg_norm,
linalg_norm_T,
scipy_distance,
sqrt_sum,
sqrt_sum_T,
sqrt_einsum,
sqrt_einsum_T,
],
xlabel="len(x), len(y)",
)
"If I want two columns for anything over 768px, should I apply both classes?"
This should be as simple as:
<div class="row">
<div class="col-sm-6"></div>
<div class="col-sm-6"></div>
</div>
No need to add the col-lg-6
too.
Note that these solutions use the Code Igniter Active Records Class
This method uses sub queries like you wish but you should sanitize $countryId
yourself!
$this->db->select('username')
->from('user')
->where('`locationId` in', '(select `locationId` from `locations` where `countryId` = '.$countryId.')', false)
->get();
Or this method would do it using joins and will sanitize the data for you (recommended)!
$this->db->select('username')
->from('users')
->join('locations', 'users.locationid = locations.locationid', 'inner')
->where('countryid', $countryId)
->get();
To chime in with another solution - I found that the "listen for bounds_changed event and then set new zoom" approach didn't work reliably for me. I think that I was sometimes calling fitBounds
before the map had been fully initialized, and the initialization was causing a bounds_changed event that would use up the listener, before fitBounds
changed the boundaries and zoom level. I ended up with this code, which seems to work so far:
// If there's only one marker, or if the markers are all super close together,
// `fitBounds` can zoom in too far. We want to limit the maximum zoom it can
// use.
//
// `fitBounds` is asynchronous, so we need to wait until the bounds have
// changed before we know what the new zoom is, using an event handler.
//
// Sometimes this handler gets triggered by a different event, before
// `fitBounds` takes effect; that particularly seems to happen if the map
// hasn't been fully initialized yet. So we don't immediately remove the
// listener; instead, we wait until the 'idle' event, and remove it then.
//
// But 'idle' might happen before 'bounds_changed', so we can't set up the
// removal handler immediately. Set it up in the first event handler.
var removeListener = null;
var listener = google.maps.event.addListener(map, 'bounds_changed', () => {
console.log(map.getZoom());
if (map.getZoom() > 15) {
map.setZoom(15);
}
if (!removeListener) {
removeListener = google.maps.event.addListenerOnce(map, 'idle', () => {
console.log('remove');
google.maps.event.removeListener(listener);
});
}
});
According to my knowledge we should use ng-change with the select option and in textbox case we should use ng-blur.
You need to do encode
on tmp[0]
, not on tmp
.
tmp
is not a string. It contains a (Unicode) string.
Try running type(tmp)
and print dir(tmp)
to see it for yourself.
For a solution that is free of fiddly external dependencies*, there is now readxl
:
The readxl package makes it easy to get data out of Excel and into R. Compared to many of the existing packages (e.g. gdata, xlsx, xlsReadWrite) readxl has no external dependencies so it's easy to install and use on all operating systems. It is designed to work with tabular data stored in a single sheet.
Readxl supports both the legacy .xls format and the modern xml-based .xlsx format. .xls support is made possible the with libxls C library, which abstracts away many of the complexities of the underlying binary format. To parse .xlsx, we use the RapidXML C++ library.
It can be installed like so:
install.packages("readxl") # CRAN version
or
devtools::install_github("hadley/readxl") # development version
Usage
library(readxl)
# read_excel reads both xls and xlsx files
read_excel("my-old-spreadsheet.xls")
read_excel("my-new-spreadsheet.xlsx")
# Specify sheet with a number or name
read_excel("my-spreadsheet.xls", sheet = "data")
read_excel("my-spreadsheet.xls", sheet = 2)
# If NAs are represented by something other than blank cells,
# set the na argument
read_excel("my-spreadsheet.xls", na = "NA")
* not strictly true, it requires the Rcpp
package, which in turn requires Rtools (for Windows) or Xcode (for OSX), which are dependencies external to R. But they don't require any fiddling with paths, etc., so that's an advantage over Java and Perl dependencies.
Update There is now the rexcel package. This promises to get Excel formatting, functions and many other kinds of information from the Excel file and into R.
SELECT datetime('now', 'localtime');
As of CMake Wiki:
CMAKE_BINARY_DIR if you are building in-source, this is the same as CMAKE_SOURCE_DIR, otherwise this is the top level directory of your build tree
Compare these two variables to determine if out-of-source build was started
Since this is ASP.NET, you can simply use the ASP <%= %> tag to print the generated ClientID of txtTitle:
$('<%= txtTitle.ClientID %>')
This will result in...
$('ctl00$ContentBody$txtTitle')
... when the page is rendered.
Note: In Visual Studio, Intellisense will yell at you for putting ASP tags in JavaScript. You can ignore this as the result is valid JavaScript.
it simple, select columns want to insert primary key and click on Key icon on header and save table
happy coding..,
tl;dr You might not need to whack your entire NetBeans cache.
My problem manifested as running a clean build didn't delete the previous build
folder or testuserdir
folder, while I was using NetBeans 8.0.2.
The first time I had this problem, Ray Slater's answer above helped me immensely. I had two Project Groups, and had to close each project in both groups, close NetBeans, clear the cache, then add my projects back to my groups before it would work again.
Later, this problem cropped up again with NetBeans 8.1. I closed NetBeans, and ran ant build clean
at the command line, and it worked. When I reopened NetBeans, the problem was resolved. It occurs to me that NetBeans was keeping something open and just needed to be closed in order to delete the folders.
Update
I finally figured out what was going on. Somehow, my NetBeans "Module Suite Project" (yellow/orange puzzle pieces icon) had been closed and the "Module Project" (purple puzzle piece icon) having the same exact name as the "Module Suite Project" was open. Building clean cleaned that particular Project correctly, but did not clean the entire Suite.
Now that I have the "Module Suite Project" opened correctly again, things work as expected. This explains why ant build clean
worked, since it was done on the command line at the right level to clean the whole Suite.
I suspect I didn't strictly need to clean out my NetBeans cache at all though perhaps doing so actually fixed the issue of why it was only showing the "Module Project" instead of the "Module Suite Project", thereby doing the right thing when I clicked build clean
... If I had simply realized that the Suite was no longer open and only the Project was, I could have fixed it in three seconds.
Use this:
<style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorControlNormal">@color/white</item>
</style>
The answers to this question helped me find my problem, but my source was different, so hopefully this can shed light on someone finding this page searching for answers to the 'random' context crash:
I had specified a SharedPreferences object, and tried to instantiate it at it's class-level declaration, like so:
public class MyFragment extends FragmentActivity {
private SharedPreferences sharedPref =
PreferenceManager.getDefaultSharedPreferences(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
Referencing this
before the onCreate caused the "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference" error for me.
Instantiating the object inside the onCreate() solved my problem, like so:
public class MyFragment extends FragmentActivity {
private SharedPreferences sharedPref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Hope that helps.
td[rowspan] {
vertical-align: top;
text-align: left;
}
See: CSS attribute selectors.
If you don't use the NDK, unset the environment variable ANDROID_NDK_HOME
.
You asked about productive shortcuts, but I think your real question is: Is vim worth it? The answer to this stackoverflow question is -> "Yes"
You must have noticed two things. Vim is powerful, and vim is hard to learn. Much of it's power lies in it's expandability and endless combination of commands. Don't feel overwhelmed. Go slow. One command, one plugin at a time. Don't overdo it.
All that investment you put into vim will pay back a thousand fold. You're going to be inside a text editor for many, many hours before you die. Vim will be your companion.
The event must be cancelable
. Adding an if
statement solves this issue.
if (e.cancelable) {
e.preventDefault();
}
In your code you should put it here:
if (this.isSwipe(swipeThreshold) && e.cancelable) {
e.preventDefault();
e.stopPropagation();
swiping = true;
}
You can use NumberFormat Class object to accomplish the task.
// Creating number format object to set 2 places after decimal point
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
nf.setGroupingUsed(false);
System.out.println(nf.format(precision));// Assuming precision is a double type variable
SHA stands for Secure Hash Algorithm while AES stands for Advanced Encryption Standard. So SHA is a suite of hashing algorithms. AES on the other hand is a cipher which is used to encrypt. SHA algorithms (SHA-1, SHA-256 etc...) will take an input and produce a digest (hash), this is typically used in a digital signing process (produce a hash of some bytes and sign with a private key).
Here is what worked here: Simulates Excel 2003 (Save as CSV format)
SELECT
REPLACE( IFNULL(notes, ''), '\r\n' , '\n' ) AS notes
FROM sometables
INTO OUTFILE '/tmp/test.csv'
FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '"'
LINES TERMINATED BY '\r\n';
Seem this bug is not fixed yet [1]. Some people get worked, some people not. I also get not worked.
I tried clear cache with command: npm cache verify
then run install command again. I got worked.
If you want an easy-to-use way to add icons automatically when building locally (cordova emulate ios
, cordova run android
, etc) have a look at this gist:
https://gist.github.com/LinusU/7515016
Hopefully this will start to work out of the box sometime in the future, here is the relevant bug report on the Cordova project:
Finally the right solution for PHP 5.3 and above: (added optional Timezone to the Example like mentioned in the comments)
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date, new \DateTimeZone('UTC'));
$date->setTimezone(new \DateTimeZone('Europe/Berlin')); // optional
echo $date->format('m/d/y h:i a');
When learning a new concept I don't like using libraries or code dumps. I found a good description here and in the documentation of how to resize an image by pinching. This answer is a slightly modified summary. You will probably want to add more functionality later, but it will help you get started.
The ImageView
just uses the app logo since it is already available. You can replace it with any image you like, though.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@mipmap/ic_launcher"
android:layout_centerInParent="true"/>
</RelativeLayout>
We use a ScaleGestureDetector
on the activity to listen to touch events. When a scale (ie, pinch) gesture is detected, then the scale factor is used to resize the ImageView
.
public class MainActivity extends AppCompatActivity {
private ScaleGestureDetector mScaleGestureDetector;
private float mScaleFactor = 1.0f;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize the view and the gesture detector
mImageView = findViewById(R.id.imageView);
mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
}
// this redirects all touch events in the activity to the gesture detector
@Override
public boolean onTouchEvent(MotionEvent event) {
return mScaleGestureDetector.onTouchEvent(event);
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
// when a scale gesture is detected, use it to resize the image
@Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector){
mScaleFactor *= scaleGestureDetector.getScaleFactor();
mImageView.setScaleX(mScaleFactor);
mImageView.setScaleY(mScaleFactor);
return true;
}
}
}
You can limit the size of the scaling with something like
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
Thanks again to Pinch-to-zoom with multi-touch gestures In Android
You will probably want to do other things like panning and scaling to some focus point. You can develop these things yourself, but if you would like to use a pre-made custom view, copy TouchImageView.java
into your project and use it like a normal ImageView
. It worked well for me and I only ran into one bug. I plan to further edit the code to remove the warning and the parts that I don't need. You can do the same.
Open a new worksheet on the related instance (Alt-F10)
and run the following query
SELECT view_name, owner
FROM sys.all_views
ORDER BY owner, view_name
I believe the best way to change the password is simply to use:
\password
in the Postgres console.
Per ALTER USER
documentation:
Caution must be exercised when specifying an unencrypted password with this command. The password will be transmitted to the server in cleartext, and it might also be logged in the client's command history or the server log. psql contains a command \password that can be used to change a role's password without exposing the cleartext password.
Note: ALTER USER
is an alias for ALTER ROLE
Why do you want to use strange hard commands, when you can use:
if(a < 0)
a -= 2a;
The if statement obviously only applies when you aren't sure if the number will be positive or negative.
Otherwise you'll have to use this code:
a = abs(a) // a is an integer
a = fabs(a) // a is declared as a double
a = fabsf(a) // a is declared as a float (C++ 11 is able to use fabs(a) for floats instead of fabs)
To activate C++ 11 (if you are using Code::Blocks, you have to:
After following these steps, you should be able to use fabs(a) for floats instead of fabsf(a), which was used only for C99 or less! (Even C++ 98 could allow you to use fabs instead of fabsf :P)
The selected answer didn't work for me, but it's close. I found a tutorial that worked for me and the certificate I obtained from StartCom.
Change the leader and trailer so the file looks similar to this:
-----BEGIN PKCS7-----
[... certificate content here ...]
-----END PKCS7-----
For example, my StartCom certificate began with:
-----BEGIN CERTIFICATE-----
and ended with:
-----END CERTIFICATE-----
Run the following OpenSSL command (works on Ubuntu 14.04.4, as of this writing):
openssl pkcs7 -print_certs –in pkcs7.p7b -out pem.cer
The output is a .cer with the certificate chain.
Reference: http://www.freetutorialssubmit.com/extract-certificates-from-P7B/2206
Testing for name pointing to None
and name existing are two semantically different operations.
To check if val
is None:
if val is None:
pass # val exists and is None
To check if name exists:
try:
val
except NameError:
pass # val does not exist at all
I got the same error the first time I wanted to install LightGBM on python (GPU version).
You can simply fix it with this command line :
sudo apt-get install cmake libblkid-dev e2fslibs-dev libboost-all-dev libaudit-dev
the boost libraries will be installed and you'll be fine to continue your installation process.
for frequency distribution of a variable with excessive values you can collapse down the values in classes,
Here I excessive values for employrate
variable, and there's no meaning of it's frequency distribution with direct values_count(normalize=True)
country employrate alcconsumption
0 Afghanistan 55.700001 .03
1 Albania 11.000000 7.29
2 Algeria 11.000000 .69
3 Andorra nan 10.17
4 Angola 75.699997 5.57
.. ... ... ...
208 Vietnam 71.000000 3.91
209 West Bank and Gaza 32.000000
210 Yemen, Rep. 39.000000 .2
211 Zambia 61.000000 3.56
212 Zimbabwe 66.800003 4.96
[213 rows x 3 columns]
frequency distribution with values_count(normalize=True)
with no classification,length of result here is 139 (seems meaningless as a frequency distribution):
print(gm["employrate"].value_counts(sort=False,normalize=True))
50.500000 0.005618
61.500000 0.016854
46.000000 0.011236
64.500000 0.005618
63.500000 0.005618
58.599998 0.005618
63.799999 0.011236
63.200001 0.005618
65.599998 0.005618
68.300003 0.005618
Name: employrate, Length: 139, dtype: float64
putting classification we put all values with a certain range ie.
0-10 as 1, 11-20 as 2 21-30 as 3, and so forth.
gm["employrate"]=gm["employrate"].str.strip().dropna()
gm["employrate"]=pd.to_numeric(gm["employrate"])
gm['employrate'] = np.where(
(gm['employrate'] <=10) & (gm['employrate'] > 0) , 1, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=20) & (gm['employrate'] > 10) , 1, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=30) & (gm['employrate'] > 20) , 2, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=40) & (gm['employrate'] > 30) , 3, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=50) & (gm['employrate'] > 40) , 4, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=60) & (gm['employrate'] > 50) , 5, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=70) & (gm['employrate'] > 60) , 6, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=80) & (gm['employrate'] > 70) , 7, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=90) & (gm['employrate'] > 80) , 8, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=100) & (gm['employrate'] > 90) , 9, gm['employrate']
)
print(gm["employrate"].value_counts(sort=False,normalize=True))
after classification we have a clear frequency distribution.
here we can easily see, that 37.64%
of countries have employ rate between 51-60%
and 11.79%
of countries have employ rate between 71-80%
5.000000 0.376404
7.000000 0.117978
4.000000 0.179775
6.000000 0.264045
8.000000 0.033708
3.000000 0.028090
Name: employrate, dtype: float64
Since the question is specific to Python 3, here's using the new f-string syntax, available since Python 3.6:
>>> geopoint = {'latitude':41.123,'longitude':71.091}
>>> print(f'{geopoint["latitude"]} {geopoint["longitude"]}')
41.123 71.091
Note the outer single quotes and inner double quotes (you could also do it the other way around).
It should be this:
if (myString!="-1")
{
//Do things
}
Your equals and exclamation are the wrong way round.
Simply pass the sorted items from the dictionary to the plot()
function. concentration.items()
returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.
You can take advantage of list unpacking (with *
) to pass the sorted data directly to zip, and then again to pass it into plot()
:
import matplotlib.pyplot as plt
concentration = {
0: 0.19849878712984576,
5000: 0.093917341754771386,
10000: 0.075060643507712022,
20000: 0.06673074282575861,
30000: 0.057119318961966224,
50000: 0.046134834546203485,
100000: 0.032495766396631424,
200000: 0.018536317451599615,
500000: 0.0059499290585381479}
plt.plot(*zip(*sorted(concentration.items())))
plt.show()
sorted()
sorts tuples in the order of the tuple's items so you don't need to specify a key
function because the tuples returned by dict.item()
already begin with the key value.
First activity:
String food = (String)((Spinner)findViewById(R.id.food)).getSelectedItem();
RadioButton rb = (RadioButton) findViewById(R.id.rb);
Intent i = new Intent(this,secondActivity.class);
i.putExtra("food",food);
i.putExtra("rb",rb.isChecked());
Second activity:
String food = getIntent().getExtras().getString("food");
Boolean rb = getIntent().getExtras().getBoolean("rb");
You can use list comprehension:
content = open("path/to/file.txt").readlines()
lookup = 'the dog barked'
lines = [line_num for line_num, line_content in enumerate(content) if lookup in line_content]
print(lines)
In my case i had to load images on radio button click,
I just uses the regular onclick
event and it worked for me.
<input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion" onclick="return get_images(this, {{color.id}})">
<script>
function get_images(obj, color){
console.log($("input[type='radio'][name='colors']:checked").val());
}
</script>
The simple reason behind this is that Static data members of parent class can be accessed (only if they are not overridden) but for instance(non-static) data members or methods we need their reference and so they can only be called through an object.
A mutex is a special case of a semaphore. A semaphore allows several threads to go into the critical section. When creating a semaphore you define how may threads are allowed in the critical section. Of course your code must be able to handle several accesses to this critical section.
As I understand it int() is not intended as a 'cast' function for designating data type it's simply being (ab)used here to define the context as an arithmetic one. I've (ab)used (0+$val) in the past to ensure that $val is treated as a number.
This might work for you:
cat <<! | sed '/aaa=\(bbb\|ccc\|ddd\)/!s/\(aaa=\).*/\1xxx/'
> aaa=bbb
> aaa=ccc
> aaa=ddd
> aaa=[something else]
!
aaa=bbb
aaa=ccc
aaa=ddd
aaa=xxx
Another option suggested in this blog post is setting the style of the image as style="display: block;"
@bogatron has it right, you can use where
, it's worth noting that you can do this natively in pandas:
df1 = df.where(pd.notnull(df), None)
Note: this changes the dtype of all columns to object
.
Example:
In [1]: df = pd.DataFrame([1, np.nan])
In [2]: df
Out[2]:
0
0 1
1 NaN
In [3]: df1 = df.where(pd.notnull(df), None)
In [4]: df1
Out[4]:
0
0 1
1 None
Note: what you cannot do recast the DataFrames dtype
to allow all datatypes types, using astype
, and then the DataFrame fillna
method:
df1 = df.astype(object).replace(np.nan, 'None')
Unfortunately neither this, nor using replace
, works with None
see this (closed) issue.
As an aside, it's worth noting that for most use cases you don't need to replace NaN with None, see this question about the difference between NaN and None in pandas.
However, in this specific case it seems you do (at least at the time of this answer).
To hide status bar in iOS7 you need 2 lines of code
inapplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
write
[application setStatusBarHidden:YES];
in info.plist add this
View-Controller Based Status Bar Appearance = NO
By default in MySQL server remote access is disabled. The process to provide a remote access to user is.
PATH
mysql -uroot -proot
(or whatever the root password is.)mysql>
GRANT ALL PRIVILEGES ON *.* TO 'username'@'IP' IDENTIFIED BY 'password';
Here IP is IP address for which you want to allow remote access, if we put %
any IP address can access remotely.
Example:
C:\Users\UserName> cd C:\Program Files (x86)\MySQL\MySQL Server 5.0\bin
C:\Program Files (x86)\MySQL\MySQL Server 5.0\bin>mysql -uroot -proot
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root';
Query OK, 0 rows affected (0.27 sec)
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.25 sec)
This for a other user.
mysql> GRANT ALL PRIVILEGES ON *.* TO 'testUser'@'%' IDENTIFIED BY 'testUser';
Query OK, 0 rows affected (0.00 sec)
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
Hope this will help
Use size_t
:
for (size_t i=0; i < polygon.size(); i++)
Quoting Wikipedia:
The stdlib.h and stddef.h header files define a datatype called
size_t
which is used to represent the size of an object. Library functions that take sizes expect them to be of typesize_t
, and the sizeof operator evaluates tosize_t
.The actual type of
size_t
is platform-dependent; a common mistake is to assumesize_t
is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.
I have the same error and it fixed it including in the file the following
#include <stdint.h>
at the beginning of your file.
This work for me:
<a href="#" onclick="sposta(100)">SPOSTA</a>
function sposta(id) {
$("#sposta").data("id",id).dialog({
autoOpen: true,
modal: true,
buttons: { "Sposta": function () { alert($(this).data('id')); } }
});
}
When you click on "Sposta" in dialog alert display 100
To insert a new row into a given table (tblTable) :
INSERT INTO tblTable (DateColumn) VALUES (GETDATE())
To update an existing row :
UPDATE tblTable SET DateColumn = GETDATE()
WHERE ID = RequiredUpdateID
Note that when INSERT
ing a new row you will need to observe any constraints which are on the table - most likely the NOT NULL
constraint - so you may need to provide values for other columns eg...
INSERT INTO tblTable (Name, Type, DateColumn) VALUES ('John', 7, GETDATE())
Stuarts' answer is correct, but if you are not sure if you are saving the titles in lowercase, you can also make a case insensitive search
There are a lot of answered questions in Stack Overflow with more data on this:
$("#form-field").val("5").trigger("change");
On Kubuntu, my path to the library changed because of installing another Java version. Here's the whole picture, but in short:
sudo apt-get install libsvn-java
sudo find / -name libsvnjavahl-1.so
The output from the last command could look like this, for example:
/usr/lib/x86_64-linux-gnu/jni/libsvnjavahl-1.so
This gives you the path, so you can add the following to your eclipse.ini
:
-Djava.library.path=/usr/lib/x86_64-linux-gnu/jni/
To run Anaconda Prompt using icon, I made an icon and put
%windir%\System32\cmd.exe "/K" C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3
The file location would be different in each computer.
at icon -> right click -> Property -> Shortcut -> Target
I see %HOMEPATH%
at icon -> right click -> Property -> Start in
OS: Windows 10, Library: Anaconda 10 (64 bit)
Any CPU means that it will work on any platform. This is because managed code is similar to Java. Think of it as being compiled to a byte code that is interpreted by the .NET Framework at run-time.
C++ does not have this option because it is compiled to machine code that is platform specific.
If you're using an XML configuration file, you can add the following inside the phpunit
tag:
<groups>
<include>
<group>nameToInclude</group>
</include>
<exclude>
<group>nameToExclude</group>
</exclude>
</groups>
See https://phpunit.de/manual/current/en/appendixes.configuration.html
There is one more reason for such failure which I came to know when mine failed
This might not apply in this case but it also throws the same error and since this question comes up on top for this error, I have added this answer here.
Using the int value 1002
seems to work for PHP 5.3.0:
public static function createDB() {
$dbHost="localhost";
$dbName="project";
$dbUser="admin";
$dbPassword="whatever";
$dbOptions=array(1002 => 'SET NAMES utf8',);
return new DB($dbHost, $dbName, $dbUser, $dbPassword,$dbOptions);
}
function createConnexion() {
return new PDO(
"mysql:host=$this->dbHost;dbname=$this->dbName",
$this->dbUser,
$this->dbPassword,
$this->dbOptions);
}
Using the SSKeychain and code mentioned above. Here's code to copy/paste (add SSKeychain module):
+(NSString *) getUUID {
//Use the bundle name as the App identifier. No need to get the localized version.
NSString *Appname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
//Check if we have UUID already
NSString *retrieveuuid = [SSKeychain passwordForService:Appname account:@"user"];
if (retrieveuuid == NULL)
{
//Create new key for this app/device
CFUUIDRef newUniqueId = CFUUIDCreate(kCFAllocatorDefault);
retrieveuuid = (__bridge_transfer NSString*)CFUUIDCreateString(kCFAllocatorDefault, newUniqueId);
CFRelease(newUniqueId);
//Save key to Keychain
[SSKeychain setPassword:retrieveuuid forService:Appname account:@"user"];
}
return retrieveuuid;
}
If you want to only pass certain arguments, you can do so like this:
Foo.bar(TheClass, 'theMethod', 'arg1', 'arg2')
Foo.js
bar (obj, method, ...args) {
obj[method](...args)
}
obj
and method
are used by the bar()
method, while the rest of args are passed to the actual call.
VS 2012 has different project type support based on what you install at setup time and which edition you have. Certain options are available, e.g. web development tools, database development tools, etc. So if you're trying to open a web project but the web development tools weren't installed, it complains with this message.
This can happen if you create the project on another machine and try to open it on a new one. I figured it out trying to open an MVC project after I accidentally uninstalled the web tools.
If you have Pillow
installed with scipy
and it is still giving you error then check your scipy
version because it has been removed from scipy since 1.3.0rc1
.
rather install scipy 1.1.0
by :
pip install scipy==1.1.0
check https://github.com/scipy/scipy/issues/6212
The method imread
in scipy.misc
requires the forked package of PIL
named Pillow
. If you are having problem installing the right version of PIL try using imread
in other packages:
from matplotlib.pyplot import imread
im = imread(image.png)
To read jpg
images without PIL
use:
import cv2 as cv
im = cv.imread(image.jpg)
You can try
from scipy.misc.pilutil import imread
instead of from scipy.misc import imread
Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.
Try using 0 8 * * *. It should work
The solution I use is the following:
<input list="answers" id="answer">
<datalist id="answers">
<option data-value="42" value="The answer">
</datalist>
Then access the value to be sent to the server using JavaScript like this:
var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;
Hope it helps.
The original post requested for code which prints some rows (if they are true for some condition) plus the following row. My implementation would be this:
text = """1 sfasdf
asdfasdf
2 sfasdf
asdfgadfg
1 asfasdf
sdfasdgf
"""
text = text.splitlines()
rows_to_print = {}
for line in range(len(text)):
if text[line][0] == '1':
rows_to_print = rows_to_print | {line, line + 1}
rows_to_print = sorted(list(rows_to_print))
for i in rows_to_print:
print(text[i])
I would prefer AssertJ for this.
assertThatExceptionOfType(ExpectedException.class)
.isThrownBy(() -> {
// method call
}).withMessage("My message");
You probably won't be able to get it in a platform independent way. Windows you get number of processors.
You are using RxJS 6. Just replace
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
by
import { Observable, of } from 'rxjs';
$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);
Note: only work for your example.
It depends on what you do: Web developement, business software, etc. I think for this kind of stuff, you don't need math.
If you want to do computer graphics, audio/video processing, AI, cryptography, etc. then you need a math background, otherwise you can simply not do it.
Here is simple sample from android developer.
Basically, you can write a file in the internal storage like this :
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
I tried this and it works: ( Please replace this with the pill or tab you are using )
jQuery(document).ready(function() {
jQuery('a[data-toggle="pill"]').on('show.bs.tab', function(e) {
localStorage.setItem('activeTab', jQuery(e.target).attr('href'));
});
// Here, save the index to which the tab corresponds. You can see it
// in the chrome dev tool.
var activeTab = localStorage.getItem('activeTab');
// In the console you will be shown the tab where you made the last
// click and the save to "activeTab". I leave the console for you to
// see. And when you refresh the browser, the last one where you
// clicked will be active.
console.log(activeTab);
if (activeTab) {
jQuery('a[href="' + activeTab + '"]').tab('show');
}
});
I hope it would help somebody.
Here is the result: https://jsfiddle.net/neilbannet/ego1ncr5/5/
Remove the space or empty line in server.xml or context.xml at the beginning of your code
The second thing i did was Uninstall my Anti-Virus software (AVG Antivirus) {sounds crazy but, i had to}. it reduced gradle build time upto 40%
The first thing i did was enable offline mode (1. click on Gradle usually on the right side of the editor 2. click on the connection button to toggle) it reduced the gradle build time for upto 20%
so my Gradle build time was reduced for upto 60% by doing these two things
since you capitalized the word, I assume you are referring to the interface javax.naming.Context
. A few classes implement this interface, and at its simplest description, it (generically) is a set of name/object pairs.
prototype
allows you to make classes. if you do not use prototype
then it becomes a static.
Here is a short example.
var obj = new Object();
obj.test = function() { alert('Hello?'); };
In the above case, you have static funcation call test. This function can be accessed only by obj.test where you can imagine obj to be a class.
where as in the below code
function obj()
{
}
obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();
obj2.test();
The obj has become a class which can now be instantiated. Multiple instances of obj can exist and they all have the test
function.
The above is my understanding. I am making it a community wiki, so people can correct me if I am wrong.
How about the below solution? It worked for me. Try this:
.modal .modal-body {
max-height: 420px;
overflow-y: auto;
}
Details:
overflow-y: auto;
or overflow: auto;
from .modal class (important)max-height: 400px;
from .modal
class (important)max-height: 400px;
to .modal .modal-body (or what ever, can be 420px
or less, but would not go more than 450px
)overflow-y: auto;
to .modal .modal-body
Done, only body will scroll.
Use OutputDebugString instead of afxDump.
Example:
#define _TRACE_MAXLEN 500
#if _MSC_VER >= 1900
#define _PRINT_DEBUG_STRING(text) OutputDebugString(text)
#else // _MSC_VER >= 1900
#define _PRINT_DEBUG_STRING(text) afxDump << text
#endif // _MSC_VER >= 1900
void MyTrace(LPCTSTR sFormat, ...)
{
TCHAR text[_TRACE_MAXLEN + 1];
memset(text, 0, _TRACE_MAXLEN + 1);
va_list args;
va_start(args, sFormat);
int n = _vsntprintf(text, _TRACE_MAXLEN, sFormat, args);
va_end(args);
_PRINT_DEBUG_STRING(text);
if(n <= 0)
_PRINT_DEBUG_STRING(_T("[...]"));
}
There is a way, although not very elegant:
ansible-playbook roles/hadoop_primary/tasks/hadoop_master.yml --step --start-at-task='start hadoop jobtracker services'
Perform task: start hadoop jobtracker services (y/n/c)
y
Ctrl-C
I had this issue ..
A working solution is to change ownership of /usr/local
to current user instead of root
by:
sudo chown -R $(whoami):admin /usr/local
But really this is not a proper way. Mainly if your machine is a server or multiple-user.
My suggestion is to change the ownership as above and do whatever you want to implement with Brew .. ( update, install ... etc ) then reset ownership back to root as:
sudo chown -R root:admin /usr/local
Thats would solve the issue and keep ownership set in proper set.
You could avoid changing the code (although I recommend Boris' answer) and mock the constructor, like in this example for mocking the creation of a File object inside a method. Don't forget to put the class that will create the file in the @PrepareForTest
.
package hello.easymock.constructor;
import java.io.File;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({File.class})
public class ConstructorExampleTest {
@Test
public void testMockFile() throws Exception {
// first, create a mock for File
final File fileMock = EasyMock.createMock(File.class);
EasyMock.expect(fileMock.getAbsolutePath()).andReturn("/my/fake/file/path");
EasyMock.replay(fileMock);
// then return the mocked object if the constructor is invoked
Class<?>[] parameterTypes = new Class[] { String.class };
PowerMock.expectNew(File.class, parameterTypes , EasyMock.isA(String.class)).andReturn(fileMock);
PowerMock.replay(File.class);
// try constructing a real File and check if the mock kicked in
final String mockedFilePath = new File("/real/path/for/file").getAbsolutePath();
Assert.assertEquals("/my/fake/file/path", mockedFilePath);
}
}
If you want to force the whiskers to extend to the max and min values, you can tweak the coef
argument. Default value for coef
is 1.5 (i.e. default length of the whiskers is 1.5 times the IQR).
# Load package and create a dummy data frame with outliers
#(using example from Ramnath's answer above)
library(ggplot2)
df = data.frame(y = c(-100, rnorm(100), 100))
# create boxplot that includes outliers
p0 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)))
# create boxplot where whiskers extend to max and min values
p1 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)), coef = 500)
Simplified version for Oracle. If you don't want to create OracleParameter
var sql = "Update [User] SET FirstName = :p0 WHERE Id = :p1";
context.Database.ExecuteSqlCommand(sql, firstName, id);
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
This can be done easily using ·
. You can color or size the dot according to the tags you wrap it with. For example, try and run this
<h2> I · love · Coding </h2>
It looks like you forgot the prefix on the color attribute. Try
<stroke android:width="2dp" android:color="#ff00ffff"/>
Here is the solution which works for me:
I do the relative imports as from ..sub2 import mod2
and then, if I want to run mod1.py
then I go to the parent directory of app
and run the module using the python -m switch as python -m app.sub1.mod1
.
The real reason why this problem occurs with relative imports, is that relative imports works by taking the __name__
property of the module. If the module is being directly run, then __name__
is set to __main__
and it doesn't contain any information about package structure. And, thats why python complains about the relative import in non-package
error.
So, by using the -m switch you provide the package structure information to python, through which it can resolve the relative imports successfully.
I have encountered this problem many times while doing relative imports. And, after reading all the previous answers, I was still not able to figure out how to solve it, in a clean way, without needing to put boilerplate code in all files. (Though some of the comments were really helpful, thanks to @ncoghlan and @XiongChiamiov)
Hope this helps someone who is fighting with relative imports problem, because going through PEP is really not fun.
Usually this happens if something is wrong with the byte array.
File.WriteAllBytes("filename.PDF", Byte[]);
This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
Asynchronous implementation of this is also available.
public static System.Threading.Tasks.Task WriteAllBytesAsync
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);
I fixed this problem by following the solution to this other StackOverflow question
I had the same problem. I fixed it by adding the maven archetype catalog to eclipse. Steps are provided below: (Please note the https protocol)
- Open Window > Preferences
- Open Maven > Archetypes
- Click 'Add Remote Catalog' and add the following:
- Catalog File: https://repo1.maven.org/maven2/archetype-catalog.xml
- Description: maven catalog
Using open, read, write means you have to worry about signal interaptions.
If the call was interrupted by a signal handler the functions will return -1 and set errno to EINTR.
So the proper way to close a file would be
while (retval = close(fd), retval == -1 && ernno == EINTR) ;
Both proposed possibilities (std::swap
and std::iter_swap
) work, they just have a slightly different syntax.
Let's swap a vector's first and second element, v[0]
and v[1]
.
We can swap based on the objects contents:
std::swap(v[0],v[1]);
Or swap based on the underlying iterator:
std::iter_swap(v.begin(),v.begin()+1);
Try it:
int main() {
int arr[] = {1,2,3,4,5,6,7,8,9};
std::vector<int> * v = new std::vector<int>(arr, arr + sizeof(arr) / sizeof(arr[0]));
// put one of the above swap lines here
// ..
for (std::vector<int>::iterator i=v->begin(); i!=v->end(); i++)
std::cout << *i << " ";
std::cout << std::endl;
}
Both times you get the first two elements swapped:
2 1 3 4 5 6 7 8 9
After installing docker on Ubuntu, I ran the following command:
sudo service docker start
Have you tried it?
I am not completely sure what you're trying to achieve by seeking to a specific offset and attempting to load individual values manually, the typical usage of the pickle
module is:
# save data to a file
with open('myfile.pickle','wb') as fout:
pickle.dump([1,2,3],fout)
# read data from a file
with open('myfile.pickle') as fin:
print pickle.load(fin)
# output
>> [1, 2, 3]
If you dumped a list, you'll load a list, there's no need to load each item individually.
you're saying that you got an error before you were seeking to the -5000 offset, maybe the file you're trying to read is corrupted.
If you have access to the original data, I suggest you try saving it to a new file and reading it as in the example.
// Note power of two buffer size
#define kNumPointsInMyBuffer 1024
typedef struct _ringBuffer {
UInt32 currentIndex;
UInt32 sizeOfBuffer;
double data[kNumPointsInMyBuffer];
} ringBuffer;
// Initialize the ring buffer
ringBuffer *myRingBuffer = (ringBuffer *)calloc(1, sizeof(ringBuffer));
myRingBuffer->sizeOfBuffer = kNumPointsInMyBuffer;
myRingBuffer->currentIndex = 0;
// A little function to write into the buffer
// N.B. First argument of writeIntoBuffer() just happens to have the
// same as the one calloc'ed above. It will only point to the same
// space in memory if the calloc'ed pointer is passed to
// writeIntoBuffer() as an arg when the function is called. Consider
// using another name for clarity
void writeIntoBuffer(ringBuffer *myRingBuffer, double *myData, int numsamples) {
// -1 for our binary modulo in a moment
int buffLen = myRingBuffer->sizeOfBuffer - 1;
int lastWrittenSample = myRingBuffer->currentIndex;
int idx;
for (int i=0; i < numsamples; ++i) {
// modulo will automagically wrap around our index
idx = (i + lastWrittenSample) & buffLen;
myRingBuffer->data[idx] = myData[i];
}
// Update the current index of our ring buffer.
myRingBuffer->currentIndex += numsamples;
myRingBuffer->currentIndex &= myRingBuffer->sizeOfBuffer - 1;
}
As long as your ring buffer's length is a power of two, the incredibly fast binary "&" operation will wrap around your index for you. For my application, I'm displaying a segment of audio to the user from a ring buffer of audio acquired from a microphone.
I always make sure that the maximum amount of audio that can be displayed on screen is much less than the size of the ring buffer. Otherwise you might be reading and writing from the same chunk. This would likely give you weird display artifacts.
How about mobiledetect.net?
Other solutions seem too basic. This is a lightweight PHP class. It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment. You can also benefit from Mobile Detect by using any of the 3rd party plugins available for: WordPress, Drupal, Joomla, Magento, etc.
I'm using XAMPP, in which there are several php.ini files.
You can find the line in the php.ini files:
;extension=php_curl.dll
Please remove ;
at the beginning of this line. And you may need to restart apache server.
Use g++ -std=c++11 -o <output_file_name> <file_to_be_compiled>
You can simply request https://graph.facebook.com/me?access_token=xxxxxxxxxxxxxxxxx if you get an error, the token is invalid. If you get a JSON object with an id property then it is valid.
Unfortunately this will only tell you if your token is valid, not if it came from your app.
Aside from the css reset, I also added the following to the css of my div
container and that fixed it.
position: relative;
top: -22px;
You can use below code
$.when( Typer() ).done(function() {
playBGM();
});
I've got a pretty simple yet smart workaround: Just define the array with variables in its name. For example:
for (( i=0 ; i<$(($maxvalue + 1)) ; i++ ))
do
for (( j=0 ; j<$(($maxargument + 1)) ; j++ ))
do
declare -a array$i[$j]=((Your rule))
done
done
Don't know whether this helps since it's not exactly what you asked for, but it works for me. (The same could be achieved just with variables without the array)
The book has a note how to find help on tag sets, e.g.:
nltk.help.upenn_tagset()
Others are probably similar. (Note: Maybe you first have to download tagsets
from the download helper's Models section for this)
Go To Build.Gradle(module:app)
use this - minifyEnabled false
??
is there to provide a value for a nullable type when the value is null. So, if formsAuth is null, it will return new FormsAuthenticationWrapper().
In addition to the answers above, AndAlso provides a conditioning process known as short circuiting. Many programming languages have this functionality built in like vb.net does, and can provide substantial performance increases in long condition statements by cutting out evaluations that are unneccessary.
Another similar condition is the OrElse condition which would only check the right condition if the left condition is false, thus cutting out unneccessary condition checks after a true condition is found.
I would advise you to always use short circuiting processes and structure your conditional statements in ways that can benefit the most by this. For example, test your most efficient and fastest conditions first so that you only run your long conditions when you absolutely have to and short circuit the other times.
For Laravel 5.5 or above just use the built in helper
$timestamp = now();
If you want a unix timestamp, you can also try this:
$unix_timestamp = now()->timestamp;
#sides{_x000D_
margin:0;_x000D_
}_x000D_
#left{_x000D_
float:left;_x000D_
width:75%;_x000D_
overflow:hidden;_x000D_
}_x000D_
#right{_x000D_
float:left;_x000D_
width:25%;_x000D_
overflow:hidden;_x000D_
}
_x000D_
<h1 id="left">Left Side</h1>_x000D_
<h1 id="right">Right Side</h1>_x000D_
<!-- It Works!-->
_x000D_
I'd prefer mapping after making sure the value is available
private String getStringIfObjectIsPresent(Optional<Object> object) {
Object ob = object.orElseThrow(MyCustomException::new);
// do your mapping with ob
String result = your-map-function(ob);
return result;
}
or one liner
private String getStringIfObjectIsPresent(Optional<Object> object) {
return your-map-function(object.orElseThrow(MyCustomException::new));
}
Make sure the last line of your .bash_profile
is:
export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"
As a good practice I think it is a good idea to test if a popup was blocked and take action in case. You need to know that window.open has a return value, and that value may be null if the action failed. For example, in the following code:
function pop(url,w,h) {
n=window.open(url,'_blank','toolbar=0,location=0,directories=0,status=1,menubar=0,titlebar=0,scrollbars=1,resizable=1,width='+w+',height='+h);
if(n==null) {
return true;
}
return false;
}
if the popup is blocked, window.open will return null. So the function will return false.
As an example, imagine calling this function directly from any link with
target="_blank"
: if the popup is successfully opened, returningfalse
will block the link action, else if the popup is blocked, returningtrue
will let the default behavior (open new _blank window) and go on.
<a href="http://whatever.com" target="_blank" onclick='return pop("http://whatever.com",300,200);' >
This way you will have a popup if it works, and a _blank window if not.
If the popup does not open, you can:
Does it have to be done in Java? I.e. does it need to be platform independent? If not, I'd suggest using the 'split' command in *nix. If you really wanted, you could execute this command via your java program. While I haven't tested, I imagine it perform faster than whatever Java IO implementation you could come up with.