For me, this error came up when I was trying to rollback a transaction block after encountering an exception, inside another transaction block.
All I had to do to fix it was to remove my inner transaction block.
Things can get quite messy when using nested transactions, best to avoid this and just restructure your code.
If you could not find Local DTC in the component services try to run this PowerShell script first:
$DTCSettings = @(
"NetworkDtcAccess", # Network DTC Access
"NetworkDtcAccessClients", # Allow Remote Clients ( Client and Administration)
"NetworkDtcAccessAdmin", # Allow Remote Administration ( Client and Administration)
"NetworkDtcAccessTransactions", # (Transaction Manager Communication )
"NetworkDtcAccessInbound", # Allow Inbound (Transaction Manager Communication )
"NetworkDtcAccessOutbound" , # Allow Outbound (Transaction Manager Communication )
"XaTransactions", # Enable XA Transactions
"LuTransactions" # Enable SNA LU 6.2 Transactions
)
foreach($setting in $DTCSettings)
{
Set-ItemProperty -Path HKLM:\Software\Microsoft\MSDTC\Security -Name $setting -Value 1
}
Restart-Service msdtc
And it appears!
Source: The partner transaction manager has disabled its support for remote/network transactions
You can use .addAll()
to add the elements of the second list to the first:
array1.addAll(array2);
Edit: Based on your clarification above ("i want a single String in the new Arraylist which has both name and number."), you would want to loop through the first list and append the item from the second list to it.
Something like this:
int length = array1.size();
if (length != array2.size()) { // Too many names, or too many numbers
// Fail
}
ArrayList<String> array3 = new ArrayList<String>(length); // Make a new list
for (int i = 0; i < length; i++) { // Loop through every name/phone number combo
array3.add(array1.get(i) + " " + array2.get(i)); // Concat the two, and add it
}
If you put in:
array1 : ["a", "b", "c"]
array2 : ["1", "2", "3"]
You will get:
array3 : ["a 1", "b 2", "c 3"]
While performance issues are valid the real reasons in practice that you should avoid storing images in a database are for database management reasons. Your database will grow very rapidly and databases cost much more than simple file storage. Database backups and restores are much more expensive and time-consuming than file backup restores. In a pinch, you can restore a smaller database much more quickly than one bloated with images. Compare 1 TB of file storage on Azure to a 1 TB database and you'll see the vast difference in cost.
running the following command helps me running https web-page, with iframe which has ws (unsecured) connection
chrome.exe --user-data-dir=c:\temp-chrome --disable-web-security --allow-running-insecure-content
Based on the first sentence of the question: "I'm trying to write out a Byte[] array representing a complete file to a file."
The path of least resistance would be:
File.WriteAllBytes(string path, byte[] bytes)
Documented here:
try
ps huH p <PID_OF_U_PROCESS> | wc -l
or htop
In my case,
-Xms1024M -Xmx1024M is work
-Xms1024M -Xmx2048M result: Could not reserve enough space for object heap
after use JVM 64 bit, it allows using 2GB RAM, because I am using win server 2012
please see the available max heap size for JVM 32 bit on several OSs
https://www.codementor.io/@suryab/does-32-bit-or-64-bit-jvm-matter-anymore-w0sa2rk6z
For Bootstrap 4 I find the following very handy because:
It is the combination of col and col-auto which does the magic. So you don't have to define a col width (like col-2,...)
<div class="row">
<div class="col">Left</div>
<div class="col-auto">Right</div>
</div>
Ideal for aligning words, icons, buttons,... to the right.
An example to have this responsive on small devices:
<div class="row">
<div class="col">Left</div>
<div class="col-12 col-sm-auto">Right (Left on small)</div>
</div>
Check this Fiddle https://jsfiddle.net/Julesezaar/tx08zveL/
Access to the path 'C:\inetpub\wwwroot\mysite\images\savehere' is denied
Read the message carefully. You are trying to save to a file that has the same name as the directory. That cannot work, you can't overwrite a directory filled with files with a single new file. That would cause undiagnosable data loss, "Access to the path is denied" is the file system fighting back to prevent that from happening.
The exception message is not ideal, but it comes straight from the OS and they are cast in stone. The framework often adds extra checks to generate better messages, but this is an expensive test on a network. Perf is a feature too.
You need to use a name like 'C:\inetpub\wwwroot\mysite\images\savehere\mumble.jpg'. Consider Path.Combine() to reliably generate the path name.
This is an interesting question, and I started thinking about how I would implement something like this.
I came up with this (fiddle);
Basically, instead of trying to call a directive from a controller, I created a module to house all the popdown logic:
var PopdownModule = angular.module('Popdown', []);
I put two things in the module, a factory
for the API which can be injected anywhere, and the directive
for defining the behavior of the actual popdown element:
The factory just defines a couple of functions success
and error
and keeps track of a couple of variables:
PopdownModule.factory('PopdownAPI', function() {
return {
status: null,
message: null,
success: function(msg) {
this.status = 'success';
this.message = msg;
},
error: function(msg) {
this.status = 'error';
this.message = msg;
},
clear: function() {
this.status = null;
this.message = null;
}
}
});
The directive gets the API injected into its controller, and watches the api for changes (I'm using bootstrap css for convenience):
PopdownModule.directive('popdown', function() {
return {
restrict: 'E',
scope: {},
replace: true,
controller: function($scope, PopdownAPI) {
$scope.show = false;
$scope.api = PopdownAPI;
$scope.$watch('api.status', toggledisplay)
$scope.$watch('api.message', toggledisplay)
$scope.hide = function() {
$scope.show = false;
$scope.api.clear();
};
function toggledisplay() {
$scope.show = !!($scope.api.status && $scope.api.message);
}
},
template: '<div class="alert alert-{{api.status}}" ng-show="show">' +
' <button type="button" class="close" ng-click="hide()">×</button>' +
' {{api.message}}' +
'</div>'
}
})
Then I define an app
module that depends on Popdown
:
var app = angular.module('app', ['Popdown']);
app.controller('main', function($scope, PopdownAPI) {
$scope.success = function(msg) { PopdownAPI.success(msg); }
$scope.error = function(msg) { PopdownAPI.error(msg); }
});
And the HTML looks like:
<html ng-app="app">
<body ng-controller="main">
<popdown></popdown>
<a class="btn" ng-click="success('I am a success!')">Succeed</a>
<a class="btn" ng-click="error('Alas, I am a failure!')">Fail</a>
</body>
</html>
I'm not sure if it's completely ideal, but it seemed like a reasonable way to set up communication with a global-ish popdown directive.
Again, for reference, the fiddle.
Remove the spaces from the original string and split on semicolon
$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')
Or all in one line:
$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')
$addresses
becomes:
@('[email protected]','[email protected]','[email protected]')
There's a section of @media print
code in the css file (Bootstrap 3.3.1 [UPDATE:] to 3.3.5), this strips virtually all the styling, so you get fairly bland print-outs even when it is working.
For now I've had to resort to stripping out the @media print
section from bootstrap.css - which I'm really not happy about but my users want direct screen-grabs so this'll have to do for now. If anyone knows how to suppress it without changes to the bootstrap files I'd be very interested.
Here's the 'offending' code block, starts at line #192:
@media print {
*,
*:before,enter code here
*:after {
color: #000 !important;
text-shadow: none !important;
background: transparent !important;
-webkit-box-shadow: none !important;
box-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
a[href^="#"]:after,
a[href^="javascript:"]:after {
content: "";
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
thead {
display: table-header-group;
}
tr,
img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
select {
background: #fff !important;
}
.navbar {
display: none;
}
.btn > .caret,
.dropup > .btn > .caret {
border-top-color: #000 !important;
}
.label {
border: 1px solid #000;
}
.table {
border-collapse: collapse !important;
}
.table td,
.table th {
background-color: #fff !important;
}
.table-bordered th,
.table-bordered td {
border: 1px solid #ddd !important;
}
}
It's always problematic and often misleading to try and translate constructs and concepts between languages. Casting is no exception. Particularly because Java is a dynamic language and C++ is somewhat different.
All casting in Java, no matter how you do it, is done at runtime. Type information is held at runtime. C++ is a bit more of a mix. You can cast a struct in C++ to another and it's merely a reinterpretation of the bytes that represent those structs. Java doesn't work that way.
Also generics in Java and C++ are vastly different. Don't concern yourself overly with how you do C++ things in Java. You need to learn how to do things the Java way.
Pretty basic but works:
function dynamicHeight() {
var height = jQuery('').height();
jQuery('.edito-wrapper').css('height', editoHeight);
}
editoHeightSize();
jQuery(window).resize(function () {
editoHeightSize();
});
For me, I was having the same issue, the issue was that there was an unused RecyclerView in xml with view gone but I am not binding it to any adapter in Activity, hence the issue. It was solved as soon as I removed such unused recycler views in xml
i.e - I removed this view as this was not called in code or any adapter has been set
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rv_profileview_allactivities"
android:visibility="gone" />
this morning, i also had the same doubt and now its cleared i had just used JSON with 'open-weather-map'(https://openweathermap.org/) api and got data from the URL in the index.html file, the code looks like this:-
//got location_x000D_
var x = document.getElementById("demo");_x000D_
if (navigator.geolocation) {_x000D_
navigator.geolocation.getCurrentPosition(weatherdata);_x000D_
} else { _x000D_
x.innerHTML = "Geolocation is not supported by this browser.";_x000D_
}_x000D_
//fetch openweather map url with api key_x000D_
function weatherdata(position) {_x000D_
//put corrdinates to get weather data of that location_x000D_
fetch('https://api.openweathermap.org/data/2.5/weather?lat='+position.coords.latitude+'&lon='+position.coords.longitude+'&appid=b2c336bb5abf01acc0bbb8947211fbc6')_x000D_
.then(response => response.json())_x000D_
.then(data => {_x000D_
console.log(data);_x000D_
document.getElementById("demo").innerHTML = _x000D_
'<br>wind speed:-'+data.wind.speed + _x000D_
'<br>humidity :-'+data.main.humidity + _x000D_
'<br>temprature :-'+data.main.temp _x000D_
});_x000D_
}
_x000D_
<div id="demo"></div>
_x000D_
i had give api key openly because i had free subscription, just have a free subscriptions in beginning. you can find some good free api's and keys at "rapidapi.com"
If libncurses is not installed then install it and try again.
sudo apt-get install libncurses5:i386
or sudo apt-get install libncurses5
for 64 bit binaries
Also install the collection of libraries by using this command
sudo apt-get install ia32-libs
This is definitely not the best way to do this but, I got it done by doing something like following.
String imageName = "my_image.png";
String replace = imageName.replace('.','~');
String[] split = replace.split("~");
System.out.println("Image name : " + split[0]);
System.out.println("Image extension : " + split[1]);
Output,
Image name : my_image
Image extension : png
std::string stringify(double x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion("stringify(double)");
return o.str();
}
C++ FAQ: http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1
Path
C:\Program Files\Java\jdk1.7.0_76\bin
Now you're set. Type javac
in cmd. All javac options will be displayed.
Obj C:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (nonatomic) UITextView *textView;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize textView;
- (void)viewDidLoad{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor grayColor]];
self.textView = [[UITextView alloc] initWithFrame:CGRectMake(30,10,250,20)];
self.textView.delegate = self;
[self.view addSubview:self.textView];
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
}
- (void)textViewDidChange:(UITextView *)txtView{
float height = txtView.contentSize.height;
[UITextView beginAnimations:nil context:nil];
[UITextView setAnimationDuration:0.5];
CGRect frame = txtView.frame;
frame.size.height = height + 10.0; //Give it some padding
txtView.frame = frame;
[UITextView commitAnimations];
}
@end
Our system architecture often uses the Unity IoC framework to create instances of ClientBase so there's no sure way to enforce that the other developers even use using{}
blocks. In order to make it as fool-proof as possible, I made this custom class that extends ClientBase, and handles closing down the channel on dispose, or on finalize in case someone doesn't explicitly dispose of the Unity created instance.
There is also stuff that needed to be done in the constructor to set up the channel for custom credentials and stuff, so that's in here too...
public abstract class PFServer2ServerClientBase<TChannel> : ClientBase<TChannel>, IDisposable where TChannel : class
{
private bool disposed = false;
public PFServer2ServerClientBase()
{
// Copy information from custom identity into credentials, and other channel setup...
}
~PFServer2ServerClientBase()
{
this.Dispose(false);
}
void IDisposable.Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing)
{
if (!this.disposed)
{
try
{
if (this.State == CommunicationState.Opened)
this.Close();
}
finally
{
if (this.State == CommunicationState.Faulted)
this.Abort();
}
this.disposed = true;
}
}
}
Then a client can simply:
internal class TestClient : PFServer2ServerClientBase<ITest>, ITest
{
public string TestMethod(int value)
{
return base.Channel.TestMethod(value);
}
}
And the caller can do any of these:
public SomeClass
{
[Dependency]
public ITest test { get; set; }
// Not the best, but should still work due to finalizer.
public string Method1(int value)
{
return this.test.TestMethod(value);
}
// The good way to do it
public string Method2(int value)
{
using(ITest t = unityContainer.Resolve<ITest>())
{
return t.TestMethod(value);
}
}
}
Add *.DS_Store
to your .gitignore file. That works for me perfectly
that is an error.
first of all, first line should be like this (be careful of capitals)
class Test(object):
Whenever you call a method of a class, it gets itself as the first argument (hence the name self) and method_two gives this error
>>> a.method_two()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)
For python, you need to use
Class pg8000.types.Bytea (str) Bytea is a str-derived class that is mapped to a PostgreSQL byte array.
or
Pg8000.Binary (value) Construct an object holding binary data.
Since nobody has mentioned it, I'd like to add that Facebook chat is written in Erlang.
You can add to your css .erb extension. Ej: style.css.erb
Then you can put:
background: url(<%= asset_path 'logo.png' %>) no-repeat;
I found it best to only update the calculation when a specific cell is changed. Here is an example VBA code to place in the "Worksheet" "Change" event:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("F3")) Is Nothing Then
Application.CalculateFull
End If
End Sub
The following, with an additional dot before the index, works just as expected. Here, the square brackets are optional when the index is followed by another property:
{{people.[1].name}}
{{people.1.name}}
However, the square brackets are required in:
{{#with people.[1]}}
{{name}}
{{/with}}
In the latter, using the index number without the square brackets would get one:
Error: Parse error on line ...:
... {{#with people.1}}
-----------------------^
Expecting 'ID', got 'INTEGER'
As an aside: the brackets are (also) used for segment-literal syntax, to refer to actual identifiers (not index numbers) that would otherwise be invalid. More details in What is a valid identifier?
(Tested with Handlebars in YUI.)
You can now use the get
helper for this:
(get people index)
although if you get an error about index needing to be a string, do:
(get people (concat index ""))
Javascript String objects have a split function, doesn't really need to be jQuery specific
var str = "nice.test"
var strs = str.split(".")
strs would be
["nice", "test"]
I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed
success: function(data) {
var items = JSON.parse(data)
}
A quick guess if you post your code can say for sure but you might have done something along the lines of
HashMap<String, Object> test = new HashMap();
which will produce the warning when you need to do
HashMap<String, Object> test = new HashMap<String, Object>();
it might be worth looking at
Generics in the Java Programming Language
if your unfamiliar with what needs to be done.
That is because you are posting data through a get method.
Instead of
Route::get('/validate', 'MemberController@validateCredentials');
Try this
Route::post('/validate', 'MemberController@validateCredentials');
IMHO it is considered as malformed header data.
You actually want to send those name value pairs as the request content (this is the way POST works) and not as headers.
The second way is true.
In WPF you'll need to use the Content property instead:
label1.Content = DateTime.Now.ToString();
Following @Aravind's answer with more details
@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
myServiceMethodSettingCookie(request, response); //Do service call passing the response
return new ModelAndView("CustomerAddView");
}
// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
final String cookieName = "my_cool_cookie";
final String cookieValue = "my cool value here !"; // you could assign it some encoded value
final Boolean useSecureCookie = false;
final int expiryTime = 60 * 60 * 24; // 24h in seconds
final String cookiePath = "/";
Cookie cookie = new Cookie(cookieName, cookieValue);
cookie.setSecure(useSecureCookie); // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL
cookie.setMaxAge(expiryTime); // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
cookie.setPath(cookiePath); // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories
response.addCookie(cookie);
}
Related docs:
http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html
http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html
R.color.red
is an ID (which is also an int
), but is not a color.
Use one of the following instead:
// If you're in an activity:
Button11.setBackgroundColor(getResources().getColor(R.color.red));
// OR, if you're not:
Button11.setBackgroundColor(Button11.getContext().getResources().getColor(R.color.red));
Or, alternatively:
Button11.setBackgroundColor(Color.RED); // From android.graphics.Color
Or, for more pro skills:
Button11.setBackgroundColor(0xFFFF0000); // 0xAARRGGBB
For having .html
files parsed as well, you need to set the appropriate handler in your server config.
For Apache httpd 2.X this is the following line
AddHandler application/x-httpd-php .html
See the PHP docu for information on your specific server installation.
There is no such thing. It looks like you want something like "here documents" in Perl and the shells, but Python doesn't have that.
Using raw strings or multiline strings only means that there are fewer things to worry about. If you use a raw string then you still have to work around a terminal "\" and with any string solution you'll have to worry about the closing ", ', ''' or """ if it is included in your data.
That is, there's no way to have the string
' ''' """ " \
properly stored in any Python string literal without internal escaping of some sort.
select convert(nvarchar(255), 4343)
Should do the trick.
One method would be to run multiple instances of node.js on the server and then put a load balancer (preferably a non-blocking one like nginx) in front of them.
For React.js, you can do this with more readable code. Hope it helps.
handleCheckboxChange(e) {
console.log('value of checkbox : ', e.target.checked);
}
render() {
return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}
After experimenting with the code provided here: Bootstrap Tutorial
Here is another alternative using latest Bootstrap v3.0.2:
Markup:
<div id="headcontainer" class="container">
<p>Your Header</p>
</div>
<div id="maincontainer" class="container">
<div class="row">
<div class="col-xs-4">
<p>Your Navigation</p>
</div>
<div class="col-xs-8">
<p>Your Content</p>
</div>
</div>
</div>
Additional CSS:
#maincontainer, #headcontainer {
width: 100%;
}
#headcontainer {
background-color:#CCCC99;
height: 150px
}
#maincontainer .row .col-xs-4{
background-color:gray;
height:1000px
}
#maincontainer .row .col-xs-8{
background-color:green;
height: 1000px
}
Sample JSFiddle
Hope this helps anyone interested.
The error your seeing is probably due to a non-MySQL created directory in MySQL's data directory. MySQL maps the database structure pretty directly onto the file system, databases are mapped to directories and tables are files in those directories.
The name of the non-working database looks suspiciously like someone has copied the mysql database directory to a backup at some point and left it in MySQL's data directory. This isn't a problem as long as you don't try and use the database for anything. Unfortunately the information schema scans all of the databases it finds and finds that this one isn't a real database and gets upset.
The solution is to find the mysql.bak directory on the hard disk and move it well away from MySQL.
sed -e :a -e '/$/N; s/\n/\\n/; ta' [filename]
Explanation:
-e
- denotes a command to be executed
:a
- is a label
/$/N
- defines the scope of the match for the current and the (N)ext line
s/\n/\\n/;
- replaces all EOL with \n
ta;
- goto label a if the match is successful
Taken from my blog.
There are several ways to exit Vim and have everything the same when you return. There is very good documentation within Vim itself explaining the various ways this can be done. You can use the following command within vim to access the relevant help page: :help usr_21
To give you a brief summary, here are the different methods of quitting and returning with your session intact:
Suspend and resume - You don't actually quit Vim with this; you simply hide your session in the background until you need it. If you reset your computer or issue a kill command to Vim, you will lose your session. This is good for when you want to switch to another task temporarily, but if this is the case, then you might want to look into using the GNU Screen utility instead.
Sessions - This is the true way of saving your session between instances of Vim. Even if you truly quit Vim, your session will be there for you when you return. This is probably what you are looking for.
The best solution for this is to write a custom assignment_tag
. This solution is more clean than using a with
tag because it achieves a very clear separation between logic and styling.
Start by creating a template tag file (eg. appname/templatetags/hello_world.py
):
from django import template
register = template.Library()
@register.assignment_tag
def get_addressee():
return "World"
Now you may use the get_addressee
template tag in your templates:
{% load hello_world %}
{% get_addressee as addressee %}
<html>
<body>
<h1>hello {{addressee}}</h1>
</body>
</html>
To strip any whitespace, you can use a regular expression
$str=preg_replace('/\s+/', '', $str);
See also this answer for something which can handle whitespace in UTF-8 strings.
I would use GCJ (GNU Compiler for Java) in your situation. It's an AOT (ahead of time) compiler for Java, much like GCC is for C. Instead of interpreting code, or generating intermediate java code to be run at a later time by the Java VM, it generates machine code.
GCJ is available on almost any Linux system through its respective package manager (if available). After installation, the GCJ compiler should be added to the path so that it can be invoked through the terminal. If you're using Windows, you can download and install GCJ through Cygwin or MinGW.
I would strongly recommend, however, that you rewrite your source for another language that is meant to be compiled, such as C++. Java is meant to be a portable, interpreted language. Compiling it to machine code is completely against what the language was developed for.
connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass"word"
Since the web.config is XML, you need to escape the five special characters:
&
-> &
ampersand, U+0026
<
-> <
left angle bracket, less-than sign, U+003C
>
-> >
right angle bracket, greater-than sign, U+003E
"
-> "
quotation mark, U+0022
'
-> '
apostrophe, U+0027
+ is not a problem, I suppose.
Duc Filan adds:
You should also wrap your password with single quote '
:
connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass"word'"
I think http makes request on port 80, even though I mentioned the complete host url in options object. When I run the server application which has the API, on port 80, which I was running previously on port 3000, it worked. Note that to run an application on port 80 you will need root privilege.
Error with the request: getaddrinfo EAI_AGAIN localhost:3000:80
Here is a complete code snippet
var http=require('http');
var options = {
protocol:'http:',
host: 'localhost',
port:3000,
path: '/iso/country/Japan',
method:'GET'
};
var callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
var request=http.request(options, callback);
request.on('error', function(err) {
// handle errors with the request itself
console.error('Error with the request:', err.message);
});
request.end();
I created a reusable Angular service to handle high quality resizing of images / canvases for anyone who's interested: https://gist.github.com/transitive-bullshit/37bac5e741eaec60e983
The service includes two solutions because they both have their own pros / cons. The lanczos convolution approach is higher quality at the cost of being slower, whereas the step-wise downscaling approach produces reasonably antialiased results and is significantly faster.
Example usage:
angular.module('demo').controller('ExampleCtrl', function (imageService) {
// EXAMPLE USAGE
// NOTE: it's bad practice to access the DOM inside a controller,
// but this is just to show the example usage.
// resize by lanczos-sinc filter
imageService.resize($('#myimg')[0], 256, 256)
.then(function (resizedImage) {
// do something with resized image
})
// resize by stepping down image size in increments of 2x
imageService.resizeStep($('#myimg')[0], 256, 256)
.then(function (resizedImage) {
// do something with resized image
})
})
You don't need to escape it inside. You can use the |
character to delimit searches.
"\"foo\"\'bar\'".replace(/("|')/g, "")
You probably need to some plugin like Jquery multiselect dropdown. Here is a demo.
Also you need to close your option tags like this:
<select name="test" multiple>
<option>123</option>
<option>456</option>
<option>789</option>
</select>
Use foreach with key and value.
Example:
foreach($samplearr as $key => $val) {
print "<tr><td>"
. $key
. "</td><td>"
. $val['value1']
. "</td><td>"
. $val['value2']
. "</td></tr>";
}
If you want a fairly advanced tool to do some serious poking around, look at the Memory Analyzer project at Eclipse, contributed to them by SAP.
Some of what you can do is mind-blowingly good for finding memory leaks etc -- including running a form of limited SQL (OQL) against the in-memory objects, i.e.
SELECT toString(firstName) FROM com.yourcompany.somepackage.User
Totally brilliant.
Is your type really arbitrary? If you know it is just going to be a int float or string you could just do
if val.dtype == float and np.isnan(val):
assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN
A virtual constructor is not possible but virtual destructor is possible. Let us experiment.......
#include <iostream>
using namespace std;
class Base
{
public:
Base(){
cout << "Base Constructor Called\n";
}
~Base(){
cout << "Base Destructor called\n";
}
};
class Derived1: public Base
{
public:
Derived1(){
cout << "Derived constructor called\n";
}
~Derived1(){
cout << "Derived destructor called\n";
}
};
int main()
{
Base *b = new Derived1();
delete b;
}
The above code output the following:
Base Constructor Called
Derived constructor called
Base Destructor called
The construction of derived object follow the construction rule but when we delete the "b" pointer(base pointer) we have found that only the base destructor is called. But this must not happen. To do the appropriate thing, we have to make the base destructor virtual. Now let see what happens in the following:
#include <iostream>
using namespace std;
class Base
{
public:
Base(){
cout << "Base Constructor Called\n";
}
virtual ~Base(){
cout << "Base Destructor called\n";
}
};
class Derived1: public Base
{
public:
Derived1(){
cout << "Derived constructor called\n";
}
~Derived1(){
cout << "Derived destructor called\n";
}
};
int main()
{
Base *b = new Derived1();
delete b;
}
The output changed as following:
Base Constructor Called
Derived Constructor called
Derived destructor called
Base destructor called
So the destruction of the base pointer (which takes an allocation on derived object!) follows the destruction rule, i.e first the Derived, then the Base. On the other hand, there is nothing like a virtual constructor.
To quote the help page (try ?integer
), bolded portion mine:
Integer vectors exist so that data can be passed to C or Fortran code which expects them, and so that (small) integer data can be represented exactly and compactly.
Note that current implementations of R use 32-bit integers for integer vectors, so the range of representable integers is restricted to about +/-2*10^9: doubles can hold much larger integers exactly.
Like the help page says, R's integer
s are signed 32-bit numbers so can hold between -2147483648 and +2147483647 and take up 4 bytes.
R's numeric
is identical to an 64-bit double
conforming to the IEEE 754 standard. R has no single precision data type. (source: help pages of numeric
and double
). A double can store all integers between -2^53 and 2^53 exactly without losing precision.
We can see the data type sizes, including the overhead of a vector (source):
> object.size(1:1000)
4040 bytes
> object.size(as.numeric(1:1000))
8040 bytes
To use await
/async
you need methods that return promises. The core API functions don't do that without wrappers like promisify
:
const fs = require('fs');
const util = require('util');
// Convert fs.readFile into Promise version of same
const readFile = util.promisify(fs.readFile);
function getStuff() {
return readFile('test');
}
// Can't use `await` outside of an async function so you need to chain
// with then()
getStuff().then(data => {
console.log(data);
})
As a note, readFileSync
does not take a callback, it returns the data or throws an exception. You're not getting the value you want because that function you supply is ignored and you're not capturing the actual return value.
You can't multiply string and float.instead of you try as below.it works fine
totalAmount = salesAmount * float(salesTax)
As @Brian Riley already said you should either remove 1 column in your select
select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;
or add it to your grouping
select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;
The [DisplayFormat] attribute is only used in EditorFor/DisplayFor, and not by the raw HTML APIs like TextBoxFor. I got it working by doing the following,
Model:
[Display(Name = "When was that document issued ?")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime? LiquorLicenceDocumentIssueDate { get; set; }
View:
<div id="IsLiquorLicenceDocumentOnPremisesYes" class="groupLongLabel">
@Html.LabelFor(m => m.LiquorLicenceDocumentIssueDate)
<span class="indicator"></span>
@Html.EditorFor(m => m.LiquorLicenceDocumentIssueDate)
<span id="validEmail"></span>
<br />
@Html.ValidationMessageFor(m => m.LiquorLicenceDocumentIssueDate)
</div>
Output: 30/12/2011
Related link:
Try this:
The problem here is your user doesn't have proper rights/permissions to open the file this means that you'd need to grant some administrative privileges to your python ide before you run that command.
As you are a windows user you just need to right click on python ide => select option 'Run as Administrator' and then run your command.
And if you are using the command line to run the codes, do the same open the command prompt with admin rights. Hope it helps
The databases are stored as SQLite files in /data/data/PACKAGE/databases/DATABASEFILE where:
You can see (copy from/to filesystem) the database file in the emulator selecting DDMS perspective, in the File Explorer tab.
You can define the drawables that are used for the background, and the switcher part like this:
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:thumb="@drawable/switch_thumb"
android:track="@drawable/switch_bg" />
Now you need to create a selector that defines the different states for the switcher drawable. Here the copies from the Android sources:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" />
<item android:state_pressed="true" android:drawable="@drawable/switch_thumb_pressed_holo_light" />
<item android:state_checked="true" android:drawable="@drawable/switch_thumb_activated_holo_light" />
<item android:drawable="@drawable/switch_thumb_holo_light" />
</selector>
This defines the thumb drawable, the image that is moved over the background. There are four ninepatch images used for the slider:
The deactivated version (xhdpi version that Android is using)
The pressed slider:
The activated slider (on state):
The default version (off state):
There are also three different states for the background that are defined in the following selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" />
<item android:state_focused="true" android:drawable="@drawable/switch_bg_focused_holo_dark" />
<item android:drawable="@drawable/switch_bg_holo_dark" />
</selector>
The deactivated version:
The focused version:
And the default version:
To have a styled switch just create this two selectors, set them to your Switch View and then change the seven images to your desired style.
You can use colMeans
:
### Sample data
set.seed(1)
m <- data.frame(matrix(sample(100, 20, replace = TRUE), ncol = 4))
### Your error
mean(m)
# [1] NA
# Warning message:
# In mean.default(m) : argument is not numeric or logical: returning NA
### The result using `colMeans`
colMeans(m)
# X1 X2 X3 X4
# 47.0 64.4 44.8 67.8
You can use Git GUI on Windows, see instructions:
Not possible without iterating to build a new list. You can wrap the list in a container that implements IList.
You can use LINQ to get a lazy evaluated version of IEnumerable<string>
from an object list like this:
var stringList = myList.OfType<string>();
Replace a Fragment using following code:
Fragment fragment = new AddPaymentFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, fragment, "Tag_AddPayment")
.addToBackStack("Tag_AddPayment")
.commit();
Activity's onBackPressed() is :
@Override
public void onBackPressed() {
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 1) {
fm.popBackStack();
} else {
finish();
}
Log.e("popping BACKSTRACK===> ",""+fm.getBackStackEntryCount());
}
Objects will be cleaned up when they are no longer being used and when the garbage collector sees fit. Sometimes, you may need to set an object to null
in order to make it go out of scope (such as a static field whose value you no longer need), but overall there is usually no need to set to null
.
Regarding disposing objects, I agree with @Andre. If the object is IDisposable
it is a good idea to dispose it when you no longer need it, especially if the object uses unmanaged resources. Not disposing unmanaged resources will lead to memory leaks.
You can use the using
statement to automatically dispose an object once your program leaves the scope of the using
statement.
using (MyIDisposableObject obj = new MyIDisposableObject())
{
// use the object here
} // the object is disposed here
Which is functionally equivalent to:
MyIDisposableObject obj;
try
{
obj = new MyIDisposableObject();
}
finally
{
if (obj != null)
{
((IDisposable)obj).Dispose();
}
}
If you don't want to change the strings, then you could simply do
const char *a[2];
a[0] = "blah";
a[1] = "hmm";
When you do it like this you will allocate an array of two pointers to const char
. These pointers will then be set to the addresses of the static strings "blah"
and "hmm"
.
If you do want to be able to change the actual string content, the you have to do something like
char a[2][14];
strcpy(a[0], "blah");
strcpy(a[1], "hmm");
This will allocate two consecutive arrays of 14 char
s each, after which the content of the static strings will be copied into them.
Try out the following which did work for me.
Method 1:
Tested on AT&T Fusion working fine.
Method 2:
Use the method given by shkschneider
adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings
adb shell input keyevent 20 & adb shell input keyevent 23
This works only if you have USB debugging turned on. If you do not have USB debugging turned on under Development do the following.
Tested on AT&T fusion working fine.
The location of the $_SESSION
variable storage is determined by PHP's session.save_path
configuration. Usually this is /tmp
on a Linux/Unix system. Use the phpinfo()
function to view your particular settings if not 100% sure by creating a file with this content in the DocumentRoot
of your domain:
<?php
phpinfo();
?>
Here is the link to the PHP documentation on this configuration setting:
http://php.net/manual/en/session.configuration.php#ini.session.save-path
You split the string entry of the list. l[0].strip()
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
Map:
Map transformation.
The map works on a single Row at a time.
Map returns after each input Row.
The map doesn’t hold the output result in Memory.
Map no way to figure out then to end the service.
// map example
val dfList = (1 to 100) toList
val df = dfList.toDF()
val dfInt = df.map(x => x.getInt(0)+2)
display(dfInt)
MapPartition:
MapPartition transformation.
MapPartition works on a partition at a time.
MapPartition returns after processing all the rows in the partition.
MapPartition output is retained in memory, as it can return after processing all the rows in a particular partition.
MapPartition service can be shut down before returning.
// MapPartition example
Val dfList = (1 to 100) toList
Val df = dfList.toDF()
Val df1 = df.repartition(4).rdd.mapPartition((int) => Iterator(itr.length))
Df1.collec()
//display(df1.collect())
For more details, please refer to the Spark map vs mapPartitions transformation article.
Hope this is helpful!
I had the same problem. It works perfectly fine when you add this:
android:inputType="textFilter"
to your EditText
.
In order to checkout a git tag , you would execute the following command
git checkout tags/tag-name -b branch-name
eg as mentioned below.
git checkout tags/v1.0 -b v1.0-branch
To fetch the all tags use the command
git fetch --all --tags
Correct permissions for the file is 644 Correct permissions for the folder is 755
To change the permissions , use terminal and following commands.
find foldername -type d -exec chmod 755 {} \;
find foldername -type f -exec chmod 644 {} \;
755 for folders and 644 for files.
@Simple-Solution
I use a simple Python HTTP server. When in the directory of the Angular app in question (using a MBP with Mavericks 10.9 and Python 2.x) I simply run
python -m SimpleHTTPServer 8080
And that sets up the simple server on port 8080 letting you visit localhost:8080
on your browser to view the app in development.
Hope that helped!
This is concerning "Build Solution" option only.
I got totally fed up with Visual Studio's inability to really clean solutions and wrote this little tool that will do it for you.
Close your solution in VS first and drag its folder from Windows Explorer into this app or into its icon. Depending on the setting at the bottom of its window, it can also remove additional stuff, that will help if you try to manually upload your solution to GitHub or share it with someone else:
In a nutshell, it will place all "Debug" folders, Intellisense, and other caches that can be rebuilt by VS into Recycle Bin for you.
Finally, Anaconda3-2020.07 is out and its core is Python 3.8!
You can now download Anaconda packed with Python 3.8 goodness at:
From the use of 8080 I'm assuming you are using a tomcat servlet container to serve your rest api. If this is the case you can also consider to have your webserver proxy the requests to the servlet container.
With apache you would typically use mod_jk (although there are other alternatives) to serve the api trough the web server behind port 80 instead of 8080 which would solve the cross domain issue.
This is common practice, have the 'static' content in the webserver and dynamic content in the container, but both served from behind the same domain.
The url for the rest api would be http://localhost/restws/json/product/get
Here a description on how to use mod_jk to connect apache to tomcat: http://tomcat.apache.org/connectors-doc/webserver_howto/apache.html
I deployed Facebook Android SDK to Sonatype repository.
You can include this library as Gradle dependency:
repositories {
maven {
url 'https://oss.sonatype.org/content/groups/public'
}
}
dependencies {
compile 'com.shamanland:facebook-android-sdk:3.15.0-SNAPSHOT'
}
Original post here.
You can use d6tstack which creates the table for you and is faster than pd.to_sql() because it uses native DB import commands. It supports Postgres as well as MYSQL and MS SQL.
import pandas as pd
df = pd.read_csv('table.csv')
uri_psql = 'postgresql+psycopg2://usr:pwd@localhost/db'
d6tstack.utils.pd_to_psql(df, uri_psql, 'table')
It is also useful for importing multiple CSVs, solving data schema changes and/or preprocess with pandas (eg for dates) before writing to db, see further down in examples notebook
d6tstack.combine_csv.CombinerCSV(glob.glob('*.csv'),
apply_after_read=apply_fun).to_psql_combine(uri_psql, 'table')
I was thrown aback by what was possible in python2 vs python3. I will answer it based on what I ended up doing for python3. My objective was simple: check if a json response in dictionary format gave an error or not. My dictionary is called "token" and my key that I am looking for is "error". I am looking for key "error" and if it was not there setting it to value of None, then checking is the value is None, if so proceed with my code. An else statement would handle if I do have the key "error".
if ((token.get('error', None)) is None):
do something
In fedora you can use following command to install wx
pip install -U \
-f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-16.04 \
wxPython
You can use Class#getDeclaredFields()
to get all declared fields of the class. You can use Field#get()
to get the value.
In short:
Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
field.setAccessible(true); // You might want to set modifier to public first.
Object value = field.get(someObject);
if (value != null) {
System.out.println(field.getName() + "=" + value);
}
}
To learn more about reflection, check the Sun tutorial on the subject.
That said, the fields does not necessarily all represent properties of a VO. You would rather like to determine the public methods starting with get
or is
and then invoke it to grab the real property values.
for (Method method : someObject.getClass().getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers())
&& method.getParameterTypes().length == 0
&& method.getReturnType() != void.class
&& (method.getName().startsWith("get") || method.getName().startsWith("is"))
) {
Object value = method.invoke(someObject);
if (value != null) {
System.out.println(method.getName() + "=" + value);
}
}
}
That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans.
If you know the second string is part of the first:
String s1 = "/var/data/stuff/xyz.dat";
String s2 = "/var/data";
String s3 = s1.substring(s2.length());
or if you really want the period at the beginning as in your example:
String s3 = ".".concat(s1.substring(s2.length()));
I used this command and it worked fine with me:
>git push -f origin master
But notice, that may delete some files you already have on the remote repo. That came in handy with me as the scenario was different; I was pushing my local project to the remote repo which was empty but the READ.ME
I extracted the code and put into one single method, hope it would help others.
#import <SystemConfiguration/SystemConfiguration.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
...
- (BOOL)isInternetReachable
{
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
SCNetworkReachabilityFlags flags;
if(reachability == NULL)
return false;
if (!(SCNetworkReachabilityGetFlags(reachability, &flags)))
return false;
if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
// if target host is not reachable
return false;
BOOL isReachable = false;
if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
{
// if target host is reachable and no connection is required
// then we'll assume (for now) that your on Wi-Fi
isReachable = true;
}
if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
{
// ... and the connection is on-demand (or on-traffic) if the
// calling application is using the CFSocketStream or higher APIs
if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
{
// ... and no [user] intervention is needed
isReachable = true;
}
}
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
// ... but WWAN connections are OK if the calling application
// is using the CFNetwork (CFSocketStream?) APIs.
isReachable = true;
}
return isReachable;
}
You can create a function in your ~/.bashrc
file, so you get a ping command ping-t
on your console:
function ping-t { ping "$1" | while read pong; do echo "$(date): $pong"; done; }
Now you can call this on the console:
ping-t example.com
Sa 31. Mär 12:58:31 CEST 2018: PING example.com (93.184.216.34) 56(84) bytes of data.
Sa 31. Mär 12:58:31 CEST 2018: 64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=1 ttl=48 time=208 ms
Sa 31. Mär 12:58:32 CEST 2018: 64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=2 ttl=48 time=233 ms
On Mac OSX 10.15, Even after installing gpg, i was getting gpg2 command not found
$ brew install gnupg gnupg2
Warning: gnupg 2.2.23 is already installed and up-to-date
To reinstall 2.2.23, run `brew reinstall gnupg`
$ gpg2 --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
-bash: gpg2: command not found
Instead, this worked for me
$ gpg --keyserver hkp://pool.sks-keyservers.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
Which is a JavaScript library that provides a whole mess of useful functional programming
helpers without extending any built-in objects.
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
var item = _.findWhere(data.items, {
id: 2
});
if (!_.isUndefined(item)) {
console.log('NAME =>', item.name);
}
//using find -
var item = _.find(data.items, function(item) {
return item.id === 2;
});
if (!_.isUndefined(item)) {
console.log('NAME =>', item.name);
}
If there are test failures just skip them with
mvn install -DskipTests
but i strongly recomend fixing your test first.
You can do it using the "collapse" directive: http://jsfiddle.net/iscrow/Es4L3/ (check the two "Note" in the HTML).
<!-- Note: set the initial collapsed state and change it when clicking -->
<a ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed" class="btn btn-navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Title</a>
<!-- Note: use "collapse" here. The original "data-" settings are not needed anymore. -->
<div collapse="navCollapsed" class="nav-collapse collapse navbar-responsive-collapse">
<ul class="nav">
That is, you need to store the collapsed state in a variable, and changing the collapsed also by (simply) changing the value of that variable.
Release 0.14 added a uib-
prefix to components:
https://github.com/angular-ui/bootstrap/wiki/Migration-guide-for-prefixes
Change: collapse
to uib-collapse
.
Microsoft Access is another option. You could have a Access database locally on your machine that you import the excel spreadsheets into (wizards available) and link to the the SQL Server database tables via ODBC.
You could then design a query in access that appends data from the Excel spreadsheet to the SQL Server Tables.
Single Liner to Drop, Create and Seed from Package Manager Console:
update-database -TargetMigration:0 | update-database -force
Kaboom.
I've found none of the suggestions to really work. Here's a more robust one that normalizes spacing when finding classes.
//Inside closure so that the inner functions don't need regeneration on every call.
const getCssClasses = (function () {
function normalize(str) {
if (!str) return '';
str = String(str).replace(/\s*([>~+])\s*/g, ' $1 '); //Normalize symbol spacing.
return str.replace(/(\s+)/g, ' ').trim(); //Normalize whitespace
}
function split(str, on) { //Split, Trim, and remove empty elements
return str.split(on).map(x => x.trim()).filter(x => x);
}
function containsAny(selText, ors) {
return selText ? ors.some(x => selText.indexOf(x) >= 0) : false;
}
return function (selector) {
const logicalORs = split(normalize(selector), ',');
const sheets = Array.from(window.document.styleSheets);
const ruleArrays = sheets.map((x) => Array.from(x.rules || x.cssRules || []));
const allRules = ruleArrays.reduce((all, x) => all.concat(x), []);
return allRules.filter((x) => containsAny(normalize(x.selectorText), logicalORs));
};
})();
Here's it in action from the Chrome console.
I have used for getting route name in larvel 5.3
Request::path()
Steps for MIUI 9 and Above:
Settings -> Additional Settings -> Developer options ->
Turn off "MIUI optimization" and Restart
Turn On "USB Debugging"
Turn On "Install via USB"
Set USB Configuration to Charging
Turn On "install via USB
MTP(Media Transfer Protocol) is the default mode.
Works even in MTP in some cases
If you define words as "sequences of characters delimited by space"... Use strrpos()
to find the last space in the string, shorten to that position, trim the result.
C# 7.0 now has binary literals, which is awesome.
[Flags]
enum Days
{
None = 0,
Sunday = 0b0000001,
Monday = 0b0000010, // 2
Tuesday = 0b0000100, // 4
Wednesday = 0b0001000, // 8
Thursday = 0b0010000, // 16
Friday = 0b0100000, // etc.
Saturday = 0b1000000,
Weekend = Saturday | Sunday,
Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}
Since the topic seems to have turned to declaring bit-based flag values in enums, I thought it would be worth pointing out a handy trick for this sort of thing. The left-shift operator (<<
) will allow you to push a bit to a specific binary position. Combine that with the ability to declare enum values in terms of other values in the same class, and you have a very easy-to-read declarative syntax for bit flag enums.
[Flags]
enum Days
{
None = 0,
Sunday = 1,
Monday = 1 << 1, // 2
Tuesday = 1 << 2, // 4
Wednesday = 1 << 3, // 8
Thursday = 1 << 4, // 16
Friday = 1 << 5, // etc.
Saturday = 1 << 6,
Weekend = Saturday | Sunday,
Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}
(edited Dec 2018: Android Studio 3.2.1 on Mac too)
For Android Studio 3.1.3 on a Mac, it was under
Android Studio -> Preferences -> Build, Execution, Deployment -> Compiler
and then, to view the stack trace, press this button
This is using dataframes from the pandas
package. The "index" part can be either a single index, a list of indices, or a list of booleans. This can be read about in the documentation: https://pandas.pydata.org/pandas-docs/stable/indexing.html
So the index
part specifies a subset of the rows to pull out, and the (optional) column_name
specifies the column you want to work with from that subset of the dataframe. So if you want to update the 'class' column but only in rows where the class is currently set as 'versicolor', you might do something like what you list in the question:
iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
Another option is to use
$_SERVER['REQUEST_METHOD'] == 'POST'
I didn't see it mentioned here, but this appears to be case sensitive. Once I changed to /Bin the files were ignored as expected.
The difference is exactly what the name implies: a group by performs a grouping operation, and an order by sorts.
If you do SELECT * FROM Customers ORDER BY Name
then you get the result list sorted by the customers name.
If you do SELECT IsActive, COUNT(*) FROM Customers GROUP BY IsActive
you get a count of active and inactive customers. The group by aggregated the results based on the field you specified.
I realized the permissions for the files and folders in your server also matter. I uploaded my files from a linux operating system and usually the permissions are limited for read and write. So when uploaded, the permission are still same as in the local machine.
I had the same error and i just changed the permissions for the folder i had uploaded and the error was gone.
Hope it helps someone.
The shortest way to write a selector that accesses that specific div is to simply use
[role=main] {
/* CSS goes here */
}
The previous answers are not wrong, but they rely on you using either a div or using the specific id. With this selector, you'll be able to have all kinds of crazy markup and it would still work and you avoid problems with specificity.
[role=main] {_x000D_
background: rgba(48, 96, 144, 0.2);_x000D_
}_x000D_
div,_x000D_
span {_x000D_
padding: 5px;_x000D_
margin: 5px;_x000D_
display: inline-block;_x000D_
}
_x000D_
<div id="content" role="main">_x000D_
<span role="main">Hello</span>_x000D_
</div>
_x000D_
In case anyone was wondering - it was probably my css...
@font-face
font-family: "bingo"
src: url('bingo.eot')
src: local('bingo')
src: url('bingo.svg#bingo') format('svg')
src: url('bingo.otf') format('opentype')
will render as
@font-face {
font-family: "bingo";
src: url('bingo.eot');
src: local('bingo');
src: url('bingo.svg#bingo') format('svg');
src: url('bingo.otf') format('opentype'); }
which seems to be close enough... just need to check the SVG rendering
The server_name
docs directive is used to identify virtual hosts, they're not used to set the binding.
netstat
tells you that nginx listens on 0.0.0.0:80
which means that it will accept connections from any IP.
If you want to change the IP nginx binds on, you have to change the listen
docs rule.
So, if you want to set nginx to bind to localhost
, you'd change that to:
listen 127.0.0.1:80;
In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).
I'm going on a bit of an assumption here, but I'm assuming the logic inside the procedure gets split up via task. And you cant have nullable parameters as @Yuck suggested because of the dynamics of the parameters?
So going by my assumption
If TaskName = "Path1" Then Something
If TaskName = "Path2" Then Something Else
My initial thought is, if you have separate functions with business-logic you need to create, and you can determine that you have say 5-10 different scenarios, rather write individual stored procedures as needed, instead of trying one huge one solution fits all approach. Might get a bit messy to maintain.
But if you must...
Why not try dynamic SQL, as suggested by @E.J Brennan (Forgive me, i haven't touched SQL in a while so my syntax might be rusty) That being said i don't know if its the best approach, but could this could possibly meet your needs?
CREATE PROCEDURE GetTaskEvents
@TaskName varchar(50)
@Values varchar(200)
AS
BEGIN
DECLARE @SQL VARCHAR(MAX)
IF @TaskName = 'Something'
BEGIN
@SQL = 'INSERT INTO.....' + CHAR(13)
@SQL += @Values + CHAR(13)
END
IF @TaskName = 'Something Else'
BEGIN
@SQL = 'DELETE SOMETHING WHERE' + CHAR(13)
@SQL += @Values + CHAR(13)
END
PRINT(@SQL)
EXEC(@SQL)
END
(The CHAR(13) adds a new line.. an old habbit i picked up somewhere, used to help debugging/reading dynamic procedures when running SQL profiler.)
Try:
try
{
int cnt= m.getSmartPhoneCount("HTC",true);
System.out.println("total count of HTC="+cnt);
}
catch (NoSuchBrandSmartPhoneAvailableException e)
{
// TODO Auto-generated catch
e.printStackTrace();
}
After testing different proposals, I found that the easiest way is often the best.
If you use angular ui-router and that you need a button to go back best is this:
<button onclick="history.back()">Back</button>
or
<a onclick="history.back()>Back</a>
// Warning don't set the href or the path will be broken.
Explanation: Suppose a standard management application. Search object -> View object -> Edit object
Using the angular solutions From this state :
Search -> View -> Edit
To :
Search -> View
Well that's what we wanted except if now you click the browser back button you'll be there again :
Search -> View -> Edit
And that is not logical
However using the simple solution
<a onclick="history.back()"> Back </a>
from :
Search -> View -> Edit
after click on button :
Search -> View
after click on browser back button :
Search
Consistency is respected. :-)
This ORA-01461 does not occur only while inserting into a Long column. This error can occur when binding a long string for insert into a VARCHAR2 column and most commonly occurs when there is a multi byte(means single char can take more than one byte space in oracle) character conversion issue.
If the database is UTF-8 then, because of the fact that each character can take up to 3 bytes, conversion of 3 applied to check and so actually limited to use 1333 characters to insert into varchar2(4000).
Another solution would be change the datatype from varchar2(4000) to CLOB.
To install font-awesome you first should install it with npm. So in your project root directory type:
npm install font-awesome --save
(Of course I assume you have node.js and npm already installed. And you've done npm install
in your projects root directory)
Then edit the resources/assets/sass/app.scss
file and add at the top this line:
@import "node_modules/font-awesome/scss/font-awesome.scss";
Now you can do for example:
npm run dev
This builds unminified versions of the resources in the correct folders. If you wanted to minify them, you would instead run:
npm run production
And then you can use the font.
If you want to use text word wrap in your Visual Studio Code editor, you have to press button Alt + Z for text word wrap. Its word wrap is toggled between text wrap or unwrap.
You can install SideBarEnhancements plugin, which among other things will give you ability to open file in browser just by clicking F12.
To open exactly in Chrome, you will need to fix up “Side Bar.sublime-settings” file and set "default_browser"
to be "chrome"
.
I also recommend to learn this video tutorial on Sublime Text 2.
According to https://docs.docker.com/engine/reference/builder/#run the default [Linux] shell for RUN
is /bin/sh -c
. You appear to be expecting bashisms, so you should use the "exec form" of RUN
to specify your shell.
RUN ["/bin/bash", "-c", "source /usr/local/bin/virtualenvwrapper.sh"]
Otherwise, using the "shell form" of RUN and specifying a different shell results in nested shells.
# don't do this...
RUN /bin/bash -c "source /usr/local/bin/virtualenvwrapper.sh"
# because it is the same as this...
RUN ["/bin/sh", "-c", "/bin/bash" "-c" "source /usr/local/bin/virtualenvwrapper.sh"]
If you have more than 1 command that needs a different shell, you should read https://docs.docker.com/engine/reference/builder/#shell and change your default shell by placing this before your RUN commands:
SHELL ["/bin/bash", "-c"]
Finally, if you have placed anything in the root user's .bashrc
file that you need, you can add the -l
flag to the SHELL
or RUN
command to make it a login shell and ensure that it gets sourced.
Note: I have intentionally ignored the fact that it is pointless to source a script as the only command in a RUN.
I use the get_queried_object function to get the current category on a category.php template page.
$current_category = get_queried_object();
Jordan Eldredge is right, get_the_category is not suitable here.
This fixed issues for me:
<style>
.super-centered {
position:absolute;
width:100%;
height:100%;
text-align:center;
vertical-align:middle;
z-index: 9999;
}
</style>
<table class="super-centered"><tr><td style="width:100%;height:100%;" align="center" valign="middle" >
<img alt="Loading ..." src="/ALHTheme/themes/html/ALHTheme/images/loading.gif">
</td></tr></table>
Construct the first parameter as an instance of Action
, e.g.
var inputID = 123;
var col = new BlockingDataCollection();
var task = Task.Factory.StartNew(
() => CheckFiles(inputID, col),
cancelCheckFile.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
Try:
using System.Diagnostics;
ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
string processpathfilename;
string processmodulename;
if (modules.Count > 0) {
processpathfilename = modules[0].FileName;
processmodulename= modules[0].ModuleName;
} else {
throw new ExecutionEngineException("Something critical occurred with the running process.");
}
There is no WPF equivalent. System.Windows.Forms.Screen
is still part of the .NET framework and can be used from WPF though.
See this question for more details, but you can use the calls relating to screens by using the WindowInteropHelper
class to wrap your WPF control.
You have set #slider
as absolute
, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content
div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.
You can read about CSS positioning here
If you set both to relative
, the divs will be one after the other, as shown here:
#slider {
position:relative;
left:0;
height:400px;
border-style:solid;
border-width:5px;
}
#slider img {
width:100%;
}
#content {
position:relative;
}
#content #text {
position:relative;
width:950px;
height:215px;
color:red;
}
ldapConnection is the server adres: ldap.example.com Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.
OU=Your_OU,OU=other_ou,dc=example,dc=com
You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain
Now i miss a parameter to authenticate, this works the same as the path for the username
CN=username,OU=users,DC=example,DC=com
sudo is a command for Linux so it cant be used in windows so you will get that error
May be below approach will be helpful for someone TS with reactjs
interface Event {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent<T> extends Event<T> {
UserId: string;
}
httpListener.Prefixes.Add("http://*:4444/");
you use "*" so you execute following cmd as admin
netsh http add urlacl url=http://*:4444/ user=username
no use +, must use *, because you spec *:4444~.
https://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx
When you get this vague error message, you can find out the more specific error by running
SHOW ENGINE INNODB STATUS;
The most common reasons are that when creating a foreign key, both the referenced field and the foreign key field need to match:
Another cause of this error is:
You have defined a SET NULL condition though some of the columns are defined as NOT NULL.
Convert hashmap to a ArrayList with a pair class
Hashmap<Object,Object> items = new HashMap<>();
to
List<Pair<Object,Object>> items = new ArrayList<>();
so you can sort it as you want, or list sorted by adding order.
Simple solution by Underscore.js
For example: Get all links text who's parents have class someClass
_.pluck($('.someClass').find('a'), 'text');
@Harris's answer is great, I've implemented it as a separate subclass of EditText, which can make it easier to use if your code already adds TextChangedListeners.
Also, I've tweaked it so that, if you already use any Compound Drawables, it leaves them intact.
Code is here, for anyone who needs it:
package com.companyname.your
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
public class ClearableEditText extends EditText {
public String defaultValue = "";
final Drawable imgX = getResources().getDrawable(android.R.drawable.presence_offline ); // X image
public ClearableEditText(Context context) {
super(context);
init();
}
public ClearableEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public ClearableEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
void init() {
// Set bounds of our X button
imgX.setBounds(0, 0, imgX.getIntrinsicWidth(), imgX.getIntrinsicHeight());
// There may be initial text in the field, so we may need to display the button
manageClearButton();
this.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
ClearableEditText et = ClearableEditText.this;
// Is there an X showing?
if (et.getCompoundDrawables()[2] == null) return false;
// Only do this for up touches
if (event.getAction() != MotionEvent.ACTION_UP) return false;
// Is touch on our clear button?
if (event.getX() > et.getWidth() - et.getPaddingRight() - imgX.getIntrinsicWidth()) {
et.setText("");
ClearableEditText.this.removeClearButton();
}
return false;
}
});
this.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ClearableEditText.this.manageClearButton();
}
@Override
public void afterTextChanged(Editable arg0) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
}
void manageClearButton() {
if (this.getText().toString().equals("") )
removeClearButton();
else
addClearButton();
}
void addClearButton() {
this.setCompoundDrawables(this.getCompoundDrawables()[0],
this.getCompoundDrawables()[1],
imgX,
this.getCompoundDrawables()[3]);
}
void removeClearButton() {
this.setCompoundDrawables(this.getCompoundDrawables()[0],
this.getCompoundDrawables()[1],
null,
this.getCompoundDrawables()[3]);
}
}
Most likely you need to use this trick:
dbms_output.put_line('Hi' || chr(10) ||
'good' || chr(10) ||
'morning' || chr(10) ||
'friends' || chr(10));
Change your import in test.py to:
from .hello import hello1
You will have to install the "Developer Tools" that are provided as optional packages in OS X installation disks.
from the man page
linux$ man -S 5 crontab
cron(8) examines cron entries once every minute.
The time and date fields are:
field allowed values
----- --------------
minute 0-59
hour 0-23
day of month 1-31
month 1-12 (or names, see below)
day of week 0-7 (0 or 7 is Sun, or use names)
...
# run five minutes after midnight, every day
5 0 * * * $HOME/bin/daily.job >> $HOME/tmp/out 2>&1
...
It is good to note the special "nicknames" that can be used (documented in the man page), particularly "@reboot" which has no time and date alternative.
# Run once after reboot.
@reboot /usr/local/sbin/run_only_once_after_reboot.sh
You can also use this trick to run your cron job multiple times per minute.
# Run every minute at 0, 20, and 40 second intervals
* * * * * sleep 00; /usr/local/sbin/run_3times_per_minute.sh
* * * * * sleep 20; /usr/local/sbin/run_3times_per_minute.sh
* * * * * sleep 40; /usr/local/sbin/run_3times_per_minute.sh
To add a cron job, you can do one of three things:
add a command to a user's crontab, as shown above (and from the crontab, section 5, man page).
crontab -e -u <username>
crontab -e
EDITOR
environment variable
env EDITOR=nano crontab -e -u <username>
export EDITOR=vim
crontab -e
chmod a+x <file>
create a script/program as a cron job, and add it to the system's anacron /etc/cron.*ly
directories
chmod a+x /etc/cron.daily/script_runs_daily.sh
-- make it executableman anacron
chmod a+x <file>
/etc/crontab
or /etc/anacrontab
to run at a set time/etc/anacrontab
, and define cron.hourly in /etc/cron.d/0hourly
Or, One can create system crontables in /etc/cron.d
.
/etc/cron.d
do not need to be executable.someuser
, and the use of /bin/bash
as the shell is forced. File: /etc/cron.d/myapp-cron
# use /bin/bash to run commands, no matter what /etc/passwd says
SHELL=/bin/bash
# Execute a nightly (11:00pm) cron job to scrub application records
00 23 * * * someuser /opt/myapp/bin/scrubrecords.php
I feel we had a related discussion earlier: How to upload preview image before upload through JavaScript
Use online service http://www.extractpdf.com. No need to install anything.
based on @CanalDoMestre's answer. I added support for the blank filter case, fixed a typo and prevented hiding the rows so I can still see the column headers.
$("#filterby").on('keyup', function() {
if (this.value.length < 1) {
$("#list tr").css("display", "");
} else {
$("#list tbody tr:not(:contains('"+this.value+"'))").css("display", "none");
$("#list tbody tr:contains('"+this.value+"')").css("display", "");
}
});
CSS3 has a pseudo-class called :not()
input:not([type='checkbox']) {
visibility: hidden;
}
_x000D_
<p>If <code>:not()</code> is supported, you'll only see the checkbox.</p>
<ul>
<li>text: (<input type="text">)</li>
<li>password (<input type="password">)</li>
<li>checkbox (<input type="checkbox">)</li>
</ul>
_x000D_
As Vincent mentioned, it's possible to string multiple :not()
s together:
input:not([type='checkbox']):not([type='submit'])
CSS4, which is supported in many of the latest browser releases, allows multiple selectors in a :not()
input:not([type='checkbox'],[type='submit'])
All modern browsers support the CSS3 syntax. At the time this question was asked, we needed a fall-back for IE7 and IE8. One option was to use a polyfill like IE9.js. Another was to exploit the cascade in CSS:
input {
// styles for most inputs
}
input[type=checkbox] {
// revert back to the original style
}
input.checkbox {
// for completeness, this would have worked even in IE3!
}
I'm not suggested this as the best answer, just an alternative but you can also do something like:
flag = reader[0] == "True"
flag will be True
id reader[0] is "True", otherwise it will be False
.
While this is sort of a follow up to the previous answer, it adds a little (hopefully).
Mainly what I want to clarify is that usually we think of drawing things like draw a rectangle at 10, 3
.
So if we think about that like this: move origin to 10, 3
, then draw rectangle at 0, 0
.
Then all we have to do is add a rotate in between.
Another big point is the alignment of the text. It's easiest to draw the text at 0, 0, so using the correct alignment can allow us to do that without measuring the text width.
We should still move the text by an amount to get it centered vertically, and unfortunately canvas does not have great line height support, so that's a guess and check thing ( correct me if there is something better ).
I've created 3 examples that provide a point and a text with 3 alignments, to show what the actual point on the screen is where the font will go.
var font, lineHeight, x, y;
x = 100;
y = 100;
font = 20;
lineHeight = 15; // this is guess and check as far as I know
this.context.font = font + 'px Arial';
// Right Aligned
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'right';
this.context.fillText('right', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
// Center
this.context.fillStyle = 'black';
x = 150;
y = 100;
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'center';
this.context.fillText('center', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
// Left
this.context.fillStyle = 'black';
x = 200;
y = 100;
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'left';
this.context.fillText('left', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
The line this.context.fillText('right', 0, lineHeight / 2);
is basically 0, 0
, except we move slightly for the text to be centered near the point
I don't know if you fixed it, but I did had the same issue, finally it was a dumb thing, I had:
<script src="jquery-ui/jquery-ui.min.css" rel="stylesheet">
but it should be:
<link href="jquery-ui/jquery-ui.min.css" rel="stylesheet">
Just change <scrip>
to <link>
and src
to href
<?php
class Test {
function MethodA(){
echo __FUNCTION__ ;
}
}
$test = new Test;
echo $test->MethodA();
?>
Result: "MethodA";
From cran, you can install directly from a github repository address. So if you want the package at https://github.com/twitter/AnomalyDetection
:
library(devtools)
install_github("twitter/AnomalyDetection")
does the trick.
If you are looking for a way to pass additional URL parameters (not controller, action, id, etc), here's a robust method for doing so:
object_path(@object, params: request.query_parameters)
That will pass along utm parameters or any other additional params you don't want to lose.
In .NET 4.5 it's possible to bind to static properties, read more
You can use static properties as the source of a data binding. The data binding engine recognizes when the property's value changes if a static event is raised. For example, if the class SomeClass defines a static property called MyProperty, SomeClass can define a static event that is raised when the value of MyProperty changes. The static event can use either of the following signatures:
public static event EventHandler MyPropertyChanged;
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
Note that in the first case, the class exposes a static event named PropertyNameChanged that passes EventArgs to the event handler. In the second case, the class exposes a static event named StaticPropertyChanged that passes PropertyChangedEventArgs to the event handler. A class that implements the static property can choose to raise property-change notifications using either method.
You could explicitly set where you want to tick marks with plt.xticks
:
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
For example,
import numpy as np
import matplotlib.pyplot as plt
x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
plt.show()
(np.arange
was used rather than Python's range
function just in case min(x)
and max(x)
are floats instead of ints.)
The plt.plot
(or ax.plot
) function will automatically set default x
and y
limits. If you wish to keep those limits, and just change the stepsize of the tick marks, then you could use ax.get_xlim()
to discover what limits Matplotlib has already set.
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, stepsize))
The default tick formatter should do a decent job rounding the tick values to a sensible number of significant digits. However, if you wish to have more control over the format, you can define your own formatter. For example,
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
Here's a runnable example:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, 0.712123))
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
plt.show()
So many problems in so few lines. I probably forget some:
So
#include <stdio.h>
int main(int argc, char* argv[])
{
char const* const fileName = argv[1]; /* should check that argc > 1 */
FILE* file = fopen(fileName, "r"); /* should check the result */
char line[256];
while (fgets(line, sizeof(line), file)) {
/* note that fgets don't strip the terminating \n, checking its
presence would allow to handle lines longer that sizeof(line) */
printf("%s", line);
}
/* may check feof here to make a difference between eof and io failure -- network
timeout for instance */
fclose(file);
return 0;
}
I wanted to preserve the index, so I adapted the original answer to this solution:
list_df = df.reset_index().values.tolist()
Now you can paste it somewhere else (e.g. to paste into a Stack Overflow question) and latter recreate it:
pd.Dataframe(list_df, columns=['name1', ...])
pd.set_index(['name1'], inplace=True)
For multiple keys which have equal lowest value, you can use a list comprehension:
d = {320:1, 321:0, 322:3, 323:0}
minval = min(d.values())
res = [k for k, v in d.items() if v==minval]
[321, 323]
An equivalent functional version:
res = list(filter(lambda x: d[x]==minval, d))
function poll(){
$("ajax.php", function(data){
//do stuff
});
}
setInterval(function(){ poll(); }, 5000);
If you actually want to sort the dictionary instead of just obtaining a sorted list use collections.OrderedDict
>>> from collections import OrderedDict
>>> from operator import itemgetter
>>> data = {1: 'b', 2: 'a'}
>>> d = OrderedDict(sorted(data.items(), key=itemgetter(1)))
>>> d
OrderedDict([(2, 'a'), (1, 'b')])
>>> d.values()
['a', 'b']
You need to escape the backslash \
:
println yourString.replace("\\", "/")
Although its very old, but I thought of sharing another idea to do this:
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
password = ("anything")
hash_obj = SHA256.new(password.encode('utf-8'))
hkey = hash_obj.digest()
def encrypt(info):
msg = info
BLOCK_SIZE = 16
PAD = "{"
padding = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PAD
cipher = AES.new(hkey, AES.MODE_ECB)
result = cipher.encrypt(padding(msg).encode('utf-8'))
return result
msg = "Hello stackoverflow!"
cipher_text = encrypt(msg)
print(cipher_text)
def decrypt(info):
msg = info
PAD = "{"
decipher = AES.new(hkey, AES.MODE_ECB)
pt = decipher.decrypt(msg).decode('utf-8')
pad_index = pt.find(PAD)
result = pt[: pad_index]
return result
plaintext = decrypt(cipher_text)
print(plaintext)
Outputs:
> b'\xcb\x0b\x8c\xdc#\n\xdd\x80\xa6|\xacu\x1dEg;\x8e\xa2\xaf\x80\xea\x95\x80\x02\x13\x1aem\xcb\xf40\xdb'
> Hello stackoverflow!
You should be able to access the document in the IFRAME using the following code:
document.getElementById('myframe').contentWindow.document
However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). THis is because of the browser's Same Origin Policy.
t
refers to the text mode. There is no difference between r
and rt
or w
and wt
since text mode is the default.
Documented here:
Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newlines mode (deprecated)
The default mode is 'r'
(open for reading text, synonym of 'rt'
).
Oddly enough we worked around this error by using the same casing the Path and OperationContract name used. Apparently it was case-sensitive. If anyone knows why, please comment. Thank you!
You can update your jquery typings version like so
npm install --save @types/jquery@latest
I had this same error and I've been at if for 5 days surfing the net for a solution.it worked for me and it should work for you
For me the .crash file was enough. Without .dSYM file and .app file.
I ran these two commands on the mac where I build the archive and it worked:
export DEVELOPER_DIR="/Applications/Xcode.app/Contents/Developer"
/Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/symbolicatecrash /yourPath/crash1.crash > /yourPath/crash1_symbolicated.crash
=COUNTIFS(H5:H21000,">=100", H5:H21000,"<999")
Although I have not worked C++ at a professional level, in my opinion, it is OK to throw exceptions from the constructors. I do that(if needed) in .Net. Check out this and this link. It might be of your interest.
(source: jfrog.com)
or
Just use Maven repository servers like Sonatype Nexus http://www.sonatype.org/nexus/ or JFrog Artifactory https://www.jfrog.com/artifactory/.
After one developer builds a project, build by next developers or Jenkins CI will not require Internet access.
Maven repository server also can have proxies configured to access Maven Central (or more needed public repositories), and they can have cynch'ed list of artifacts in remote repositories.
You can read it from the input stream:
public ActionResult ManagePhotos(ManagePhotos model)
{
if (ModelState.IsValid)
{
byte[] image = new byte[model.File.ContentLength];
model.File.InputStream.Read(image, 0, image.Length);
// TODO: Do something with the byte array here
}
...
}
And if you intend to directly save the file to the disk you could use the model.File.SaveAs
method. You might find the following blog post useful.
bool is a primitive type, meaning that the value (true/false in this case) is stored directly in the variable. Boolean is an object. A variable of type Boolean stores a reference to a Boolean object. The only real difference is storage. An object will always take up more memory than a primitive type, but in reality, changing all your Boolean values to bool isn't going to have any noticeable impact on memory usage.
I was wrong; that's how it works in java with boolean and Boolean. In C#, bool and Boolean are both reference types. Both of them store their value directly in the variable, both of them cannot be null, and both of them require a "convertTO" method to store their values in another type (such as int). It only matters which one you use if you need to call a static function defined within the Boolean class.
Run the below query against the database
select distinct local_net_address, local_tcp_port from sys.dm_exec_connections where local_net_address is not null
The above query shows the local IP as well as the listening Port number
Another way: The Iterator has an optional remove()-method, that is implemented for ArrayList. You can use it while iterating.
I don't know though, which variant is the most performant, you should measure it.
starblue commented, that the complexity isn't good, and that's true (for removeAll() too), because ArrayList has to copy all elements, if in the middle is an element added or removed. For that cases should a LinkedList work better. But, as we all don't know your real use-cases the best is too measure all variants, to pick the best solution.
@DSchmdit answer worked for me. I would like to add on that. So my requirement was to filter a file based on some configurations stored in the table. The file is first retrieved and collected as list of dtos. I receive the configurations from the db and store it as another list. This is how I made the filtering work with streams
List<FPRSDeferralModel> modelList = Files
.lines(Paths.get("src/main/resources/rootFiles/XXXXX.txt")).parallel().parallel()
.map(line -> {
FileModel fileModel= new FileModel();
line = line.trim();
if (line != null && !line.isEmpty()) {
System.out.println("line" + line);
fileModel.setPlanId(Long.parseLong(line.substring(0, 5)));
fileModel.setDivisionList(line.substring(15, 30));
fileModel.setRegionList(line.substring(31, 50));
Map<String, String> newMap = new HashedMap<>();
newMap.put("other", line.substring(51, 80));
fileModel.setOtherDetailsMap(newMap);
}
return fileModel;
}).collect(Collectors.toList());
for (FileModel model : modelList) {
System.out.println("model:" + model);
}
DbConfigModelList respList = populate();
System.out.println("after populate");
List<DbConfig> respModelList = respList.getFeedbackResponseList();
Predicate<FileModel> somePre = s -> respModelList.stream().anyMatch(respitem -> {
System.out.println("sinde respitem:"+respitem.getPrimaryConfig().getPlanId());
System.out.println("s.getPlanid()"+s.getPlanId());
System.out.println("s.getPlanId() == respitem.getPrimaryConfig().getPlanId():"+
(s.getPlanId().compareTo(respitem.getPrimaryConfig().getPlanId())));
return s.getPlanId().compareTo(respitem.getPrimaryConfig().getPlanId()) == 0
&& (s.getSsnId() != null);
});
final List<FileModel> finalList = modelList.stream().parallel().filter(somePre).collect(Collectors.toList());
finalList.stream().forEach(item -> {
System.out.println("filtered item is:"+item);
});
The details are in the implementation of filter predicates. This proves much more perfomant over iterating over loops and filtering out
When you read from a binary file, a data type called bytes is used. This is a bit like list or tuple, except it can only store integers from 0 to 255.
Try:
file_size = fin.read(4)
file_size0 = file_size[0]
file_size1 = file_size[1]
file_size2 = file_size[2]
file_size3 = file_size[3]
Or:
file_size = list(fin.read(4))
Instead of:
file_size = int(fin.read(4))
No, you can not add background color to SVG elements. You can do it programmatically with d3.
var text = d3.select("text");
var bbox = text.node().getBBox();
var padding = 2;
var rect = self.svg.insert("rect", "text")
.attr("x", bbox.x - padding)
.attr("y", bbox.y - padding)
.attr("width", bbox.width + (padding*2))
.attr("height", bbox.height + (padding*2))
.style("fill", "red");
The fastest way I found is that:
import java.lang.reflect.Method;
public class TraceHelper {
// save it static to have it available on every call
private static Method m;
static {
try {
m = Throwable.class.getDeclaredMethod("getStackTraceElement",
int.class);
m.setAccessible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getMethodName(final int depth) {
try {
StackTraceElement element = (StackTraceElement) m.invoke(
new Throwable(), depth + 1);
return element.getMethodName();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
It accesses the native method getStackTraceElement(int depth) directly. And stores the accessible Method in a static variable.
$base_url="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"].'?').'/';
Usage:
print "<script src='{$base_url}js/jquery.min.js'/>";
You can add parameter columns or use dict
with key which is converted to column name:
np.random.seed(123)
e = np.random.normal(size=10)
dataframe=pd.DataFrame(e, columns=['a'])
print (dataframe)
a
0 -1.085631
1 0.997345
2 0.282978
3 -1.506295
4 -0.578600
5 1.651437
6 -2.426679
7 -0.428913
8 1.265936
9 -0.866740
e_dataframe=pd.DataFrame({'a':e})
print (e_dataframe)
a
0 -1.085631
1 0.997345
2 0.282978
3 -1.506295
4 -0.578600
5 1.651437
6 -2.426679
7 -0.428913
8 1.265936
9 -0.866740
What you want is actually possible now. If you can run the asynchronous code in a service worker, and the synchronous code in a web worker, then you can have the web worker send a synchronous XHR to the service worker, and while the service worker does the async things, the web worker's thread will wait. This is not a great approach, but it could work.
Try the PowerShell PowerToy... It adds a context menu item for Open PowerShell Here.
Or you could create a shortcut that opens PowerShell with the Start In folder being your Projects folder.
It behaves the way you want if called as a function:
>>> def test():
... a = iter(list(range(10)))
... for i in a:
... print(i)
... next(a)
...
>>> test()
0
2
4
6
8
Try this code:
For Each aSheet In Worksheets
Select Case aSheet.Name
Case "ID Sheet", "Summary"
Application.DisplayAlerts = False
aSheet.Delete
Application.DisplayAlerts = True
End Select
Next aSheet
MY SOLUTION!!!!!!! I fixed this problem when I was trying to install business objects. When the installer failed to register .dll's I inputted the MSVCR71.dll into both system32 and sysWOW64 then clicked retry. Installation finished. I did try adding this in before and after install but, install still failed.
Normally svn add *
works. But if you get message like svn: warning: W150002:
due to mix off versioned and non-versioned files in working copy. Use this command:
svn add <path to directory> --force
or
svn add * --force
In the discipline of speech recognition, users are divided into goats and sheeps.
For instance, here on page 89:
Sheeps are people for whom speech recognition works exceptionally well, and goats are people for whom it works exceptionally poorly. Only the voice recognizer knows what separates them. People can't predict whose voice will be recognized easily and whose won't. The best policy is to design the interface so it can handle all kinds of voices in all kinds of environments
Maybe, it is planned to mark Android users as goats in the future to be able to configure the speech recognition engine for goats' needs. ;-)
The relevel()
command is a shorthand method to your question. What it does is reorder the factor so that whatever is the ref level is first. Therefore, reordering your factor levels will also have the same effect but gives you more control. Perhaps you wanted to have levels 3,4,0,1,2. In that case...
bFactor <- factor(b, levels = c(3,4,0,1,2))
I prefer this method because it's easier for me to see in my code not only what the reference was but the position of the other values as well (rather than having to look at the results for that).
NOTE: DO NOT make it an ordered factor. A factor with a specified order and an ordered factor are not the same thing. lm()
may start to think you want polynomial contrasts if you do that.
You should be able to use Windows "UNC" paths with robocopy. For example:
robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder
Robocopy has the ability to recover from certain types of network hiccups automatically.
Not sure if this is valid but it worked for me.
The code :
<div style='position:relative;background-color:#000000;width:600px;height:30px;border:solid;'>_x000D_
<p style='display:inline;color:#ffffff;float:left;'> Whatever </p> _x000D_
<a style='position:absolute;top:0px;left:0px;width:100%;height:100%;display:inline;' href ='#'></a>_x000D_
</div>
_x000D_
From this docs
I understood that you should use:
Try using the context-application instead of a context-activity
BundleConfig
is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)
To add this file, first you need to add the Microsoft.AspNet.Web.Optimization
nuget package to your web project:
Install-Package Microsoft.AspNet.Web.Optimization
Then under the App_Start folder create a new cs file called BundleConfig.cs
. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):
using System.Web;
using System.Web.Optimization;
namespace CodeRepository.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
Then modify your Global.asax and add a call to RegisterBundles()
in Application_Start()
:
using System.Web.Optimization;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app
Just adding this for reference in case anybody needs to restart and immediatly run a command.
I'm using this approach just to clear RAM from the system. Make sure you have deleted all objects no longer required. Maybe gc()
can also help before hand. But nothing will clear RAM better as restarting the R session.
library(rstudioapi)
restartSession(command = "print('x')")
In case somebody wants to do this, using Play Framework (and using LogBack http://logback.qos.ch/), then you can configure the application-logger.xml with this line:
<logger name="org.apache.cxf" level="DEBUG"/>
For me, it did the trick ;)
FWIW - Here's a directive I've used for a basic confirm/alert bootstrap modal, without the need for a <form>
(just switch out the jQuery click action for whatever you like, and add data-easy-dismiss
to your modal tag)
app.directive('easyDismiss', function() {
return {
restrict: 'A',
link: function ($scope, $element) {
var clickSubmit = function (e) {
if (e.which == 13) {
$element.find('[type="submit"]').click();
}
};
$element.on('show.bs.modal', function() {
$(document).on('keypress', clickSubmit);
});
$element.on('hide.bs.modal', function() {
$(document).off('keypress', clickSubmit);
});
}
};
});
I had problems with this following:
on Android Studio version: 3.3.2
until I killed the .idea/workspace.xml file.
$ cp -rv Testcopysource/ TestCopyDest
$ rm TestCopyDest/.idea/workspace.xml
$ stdio.sh & # Run Android Studio on Linux
Prior to doing that Android Studio would still point to the original source folder and all renames were applied to the original source files (within Testcopysource in my example above).
Joey mentioned that Format-*
is for human consumption. If you're writing to a file for machine consumption, maybe you want to use Export-*
? Some good ones are
Export-Csv
- Comma separated value. Great for when you know what the columns are going to beExport-Clixml
- You can export whole objects and collections. This is great for serialization.If you want to read back in, you can use Import-Csv
and Import-Clixml
. I find that I like this better than inventing my own data formats (also it's pretty easy to whip up an Import-Ini
if that's your preference).
In your custom view pager adapter, override those methods in ViewPager
.
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
And to enable, just return each super
method:
super.onInterceptTouchEvent(event)
and super.onTouchEvent(event)
.
[object Object]
This means somewhere the object is being converted to a string.
Converted to a string:
//Copy and paste in the browser console to see result
var product = {'name':'test'};
JSON.stringify(product + '');
Not converted to a string:
//Copy and paste in the browser console to see result
var product = {'name':'test'};
JSON.stringify(product);
try setting this
CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
in {$tomcat-folder}\bin\setenv.sh
(create it if necessary).
See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.
In my cases, for windows, if you have multiple python versions installed, if PYTHONPATH
is pointing to one version the other ones didn't work. I found that if you just remove PYTHONPATH
, they all work fine
In Case of not considering '0' or 'NULL' in average function. Simply use
AVG(NULLIF(your_column_name,0))