If you just want to execute the shell command in your c program, you could use,
#include <stdlib.h>
int system(const char *command);
In your case,
system("pwd");
The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.
What do you mean by this? You should be able to find the mentioned packages in /bin/
sudo find / -executable -name pwd
sudo find / -executable -name echo
I can't set "UTF-8 with BOM" in the corner button either, but I can change it from the menu bar.
"File"->"Save with encoding"->"UTF-8 with BOM"
Answering this old question (for others which may help)
Configuring your httpd conf correctly will make the problem solved. Install any httpd server, if you don't have one.
Listing my config here.
[smilyface@box002 ~]$ cat /etc/httpd/conf/httpd.conf | grep shirts | grep -v "#"
ProxyPass /shirts-service http://local.box002.com:16743/shirts-service
ProxyPassReverse /shirts-service http://local.box002.com:16743/shirts-service
ProxyPass /shirts http://local.box002.com:16443/shirts
ProxyPassReverse /shirts http://local.box002.com:16443/shirts
...
...
...
edit the file as above and then restart httpd as below
[smilyface@box002 ~]$ sudo service httpd restart
And then request with with https
will work without exception.
Also request with http
will forward to https
! No worries.
If you don't want to show controls then try this code
<audio autoplay>
<source src="song.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
Assume that you've defined do_something as a function, and you'd like to perform it N times. Maybe you can try the following:
todos = [do_something] * N
for doit in todos:
doit()
first()
if:If there are zero emissions and you are not explicitly handling it (with catchError
) then that error will get propagated up, possibly cause an unexpected problem somewhere else and can be quite tricky to track down - especially if it's coming from an end user.
You're safer off using take(1)
for the most part provided that:
take(1)
not emitting anything if the source completes without an emission.first(x => x > 10)
)Note: You can use a predicate with take(1)
like this: .pipe( filter(x => x > 10), take(1) )
. There is no error with this if nothing is ever greater than 10.
single()
If you want to be even stricter, and disallow two emissions you can use single()
which errors if there are zero or 2+ emissions. Again you'd need to handle errors in that case.
Tip: Single
can occasionally be useful if you want to ensure your observable chain isn't doing extra work like calling an http service twice and emitting two observables. Adding single
to the end of the pipe will let you know if you made such a mistake. I'm using it in a 'task runner' where you pass in a task observable that should only emit one value, so I pass the response through single(), catchError()
to guarantee good behavior.
first()
instead of take(1)
?aka. How can first
potentially cause more errors?
If you have an observable that takes something from a service and then pipes it through first()
you should be fine most of the time. But if someone comes along to disable the service for whatever reason - and changes it to emit of(null)
or NEVER
then any downstream first()
operators would start throwing errors.
Now I realize that might be exactly what you want - hence why this is just a tip. The operator first
appealed to me because it sounded slightly less 'clumsy' than take(1)
but you need to be careful about handling errors if there's ever a chance of the source not emitting. Will entirely depend on what you're doing though.
Consider also .pipe(defaultIfEmpty(42), first())
if you have a default value that should be used if nothing is emitted. This would of course not raise an error because first
would always receive a value.
Note that defaultIfEmpty
is only triggered if the stream is empty, not if the value of what is emitted is null
.
Use a DataTrigger
:
<DataGrid ItemsSource="{Binding YourItemsSource}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="State1">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="State2">
<Setter Property="Background" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
CSS is used for applying styling i.e. the visual aspects of an interface.
That clicking an anchor element causes an action to be performed is a behavioural aspect of an interface, not a stylistic aspect.
You cannot achieve what you want using only CSS.
JavaScript is used for applying behaviours to an interface. You can use JavaScript to modify the behaviour of a link.
In my case, the request was getting timed out. So all you need to do is to increase the time out while creating the HttpClient.
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromMinutes(5);
In Java 8 you can use CompletableFuture. Here's an example I had in my code where I'm using it to fetch users from my user service, map them to my view objects and then update my view or show an error dialog (this is a GUI application):
CompletableFuture.supplyAsync(
userService::listUsers
).thenApply(
this::mapUsersToUserViews
).thenAccept(
this::updateView
).exceptionally(
throwable -> { showErrorDialogFor(throwable); return null; }
);
It executes asynchronously. I'm using two private methods: mapUsersToUserViews
and updateView
.
IMO, you should have a look at the Observer Pattern, and this is how most of the listeners work
Use this CSS (jsFiddle example):
input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
color: green
}
You have to write the most outer element on the left and the most inner element on the right.
.btn:hover input:disabled
would select any disabled input elements contained in an element with a class btn
which is currently hovered by the user.
I would prefer :disabled
over [disabled]
, see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?
By the way, Laravel (PHP) generates the HTML - not the browser.
The !important rule is a way to make your CSS cascade but also have the rules you feel are most crucial always be applied. A rule that has the !important property will always be applied no matter where that rule appears in the CSS document.
So, if you have the following:
.class {
color: red !important;
}
.outerClass .class {
color: blue;
}
the rule with the important will be the one applied (not counting specificity)
I believe !important
appeared in CSS1 so every browser supports it (IE4 to IE6 with a partial implementation, IE7+ full)
Also, it's something that you don't want to use pretty often, because if you're working with other people you can override other properties.
Just add @pause
at the end.
Example:
@echo off
ipconfig
@pause
Or you can also use:
cmd /k ipconfig
The loop only breaks if you return literally false
. Ex:
// this is how jquery calls your function
// notice hard comparison (===) against false
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
This means you can return anything else, including undefined
, which is what you return if you return nothing, so you can simply use an empty return statement:
$.each(collection, function (index, item) {
if (!someTestCondition)
return; // go to next iteration
// otherwise do something
});
It's possible this might vary by version; this is applicable for jquery 1.12.4. But really, when you exit out the bottom of the function, you are also returning nothing, and that's why the loop continues, so I would expect that there is no possibility whatsoever that returning nothing could not continue the loop. Unless they want to force everyone to start returning something to keep the loop going, returning nothing has to be a way to keep it going.
The way to do this is via the bracket notation.
var test = {_x000D_
"id": "109",_x000D_
"No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
For more info read out here:
Change your code
word-wrap: break-word;
to
word-break:break-all;
Example
<table style="width: 100%;">_x000D_
<tr>_x000D_
<td>_x000D_
<div style="word-break:break-all;">longtextwithoutspacelongtextwithoutspace Long Content, Long Content, Long Content, Long Content, Long Content, Long Content, Long Content, Long Content, Long Content, Long Content</div>_x000D_
</td>_x000D_
<td><span style="display: inline;">Short Content</span>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
In addition to MR Chandru"s answer above, do these steps after configuring XAMPP:
C:\xampp
xampp-control.exe
, the XAMPP Control PanelC:\Users\User-Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
or
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
The XAMPP Control Panel should now auto-start whenever you reboot Windows.
If you are using Jersey (which I was, my server component needs to make outbound HTTP requests) it contains the following public method:
var multiValueMap = UriComponent.decodeQuery(uri, true);
It is part of org.glassfish.jersey.uri.UriComponent
, and the javadoc is here. Whilst you may not want all of Jersey, it is part of the Jersey common package which isn't too bad on dependencies...
You don't want use PreparedStatment with dynamic queries using IN clause at least your sure you're always under 5 variable or a small value like that but even like that I think it's a bad idea ( not terrible, but bad ). As the number of elements is large, it will be worse ( and terrible ).
Imagine hundred or thousand possibilities in your IN clause :
It's counter-productive, you lost performance and memory because you cache every time a new request, and PreparedStatement are not just for SQL injection, it's about performance. In this case, Statement is better.
Your pool have a limit of PreparedStatment ( -1 defaut but you must limit it ), and you will reach this limit ! and if you have no limit or very large limit you have some risk of memory leak, and in extreme case OutofMemory errors. So if it's for your small personnal project used by 3 users it's not dramatic, but you don't want that if you're in a big company and that you're app is used by thousand people and million request.
Some reading. IBM : Memory utilization considerations when using prepared statement caching
Check Below Codes :
1. SynchonousRequest
Swift 1.2
let urlPath: String = "YOUR_URL_HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
var err: NSError
println(response)
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary
println("Synchronous\(jsonResult)")
Swift 2.0 +
let urlPath: String = "YOUR_URL_HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSURLRequest = NSURLRequest(URL: url)
let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
do{
let dataVal = try NSURLConnection.sendSynchronousRequest(request1, returningResponse: response)
print(response)
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
print("Synchronous\(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}catch let error as NSError
{
print(error.localizedDescription)
}
2. AsynchonousRequest
Swift 1.2
let urlPath: String = "YOUR_URL_HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("Asynchronous\(jsonResult)")
})
Swift 2.0 +
let urlPath: String = "YOUR_URL_HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSURLRequest = NSURLRequest(URL: url)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("ASynchronous\(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
})
3. As usual URL connection
Swift 1.2
var dataVal = NSMutableData()
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()
Then
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.dataVal?.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!)
{
var error: NSErrorPointer=nil
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary
println(jsonResult)
}
Swift 2.0 +
var dataVal = NSMutableData()
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()
Then
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
dataVal.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!)
{
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
4. Asynchonous POST Request
Swift 1.2
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "POST"
var stringPost="deviceToken=123456" // Key and Value
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request1.timeoutInterval = 60
request1.HTTPBody=data
request1.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("AsSynchronous\(jsonResult)")
})
Swift 2.0 +
let urlPath: String = "YOUR URL HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "POST"
let stringPost="deviceToken=123456" // Key and Value
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request1.timeoutInterval = 60
request1.HTTPBody=data
request1.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("ASynchronous\(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
})
5. Asynchonous GET Request
Swift 1.2
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "GET"
request1.timeoutInterval = 60
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("AsSynchronous\(jsonResult)")
})
Swift 2.0 +
let urlPath: String = "YOUR URL HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "GET"
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("ASynchronous\(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
})
6. Image(File) Upload
Swift 2.0 +
let mainURL = "YOUR_URL_HERE"
let url = NSURL(string: mainURL)
let request = NSMutableURLRequest(URL: url!)
let boundary = "78876565564454554547676"
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST" // POST OR PUT What you want
let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)
let imageData = UIImageJPEGRepresentation(UIImage(named: "Test.jpeg")!, 1)
var body = NSMutableData()
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// Append your parameters
body.appendData("Content-Disposition: form-data; name=\"name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("PREMKUMAR\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"description\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("IOS_DEVELOPER\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// Append your Image/File Data
var imageNameval = "HELLO.jpg"
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"profile_photo\"; filename=\"\(imageNameval)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData!)
body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
//handle error
}
else {
let outputString : NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)!
print("Response:\(outputString)")
}
}
dataTask.resume()
Here's an example that you could use :
var myDateVariable= moment("01/01/2019").format("dddd Do MMMM YYYY")
dddd : Full day Name
Do : day of the Month
MMMM : Full Month name
YYYY : 4 digits Year
For more informations :
React hook - useRef
const MyComponent = ({myRef}) => {
const handleClick = () => alert('hello world')
myRef.current.handleClick = handleClick
return (<button onClick={handleClick}>Original Button</button>)
}
MyComponent.defaultProps = {
myRef: {current: {}}
}
const MyParentComponent = () => {
const myRef = React.useRef({})
return (
<>
<MyComponent
myRef={myRef}
/>
<button onClick={myRef.current.handleClick}>
Additional Button
</button>
</>
)
}
Good Luck...
The question is correctly answered here Center a column using Twitter Bootstrap 3
For odd rows: i.e., col-md-7 or col-large-9 use this
Add col-centered to the column you want centered.
<div class="col-lg-11 col-centered">
And add this to your stylesheet:
.col-centered{
float: none;
margin: 0 auto;
}
For even rows: i.e., col-md-6 or col-large-10 use this
Simply use bootstrap 3's offset col class. i.e.,
<div class="col-lg-10 col-lg-offset-1">
I just had this exact same problem. My solution was to use temporary files since I was generating a bunch of temporary files already. The form is submitted with:
var microBox = {
show : function(content) {
$(document.body).append('<div id="microBox_overlay"></div><div id="microBox_window"><div id="microBox_frame"><div id="microBox">' +
content + '</div></div></div>');
return $('#microBox_overlay');
},
close : function() {
$('#microBox_overlay').remove();
$('#microBox_window').remove();
}
};
$.fn.bgForm = function(content, callback) {
// Create an iframe as target of form submit
var id = 'bgForm' + (new Date().getTime());
var $iframe = $('<iframe id="' + id + '" name="' + id + '" style="display: none;" src="about:blank"></iframe>')
.appendTo(document.body);
var $form = this;
// Submittal to an iframe target prevents page refresh
$form.attr('target', id);
// The first load event is called when about:blank is loaded
$iframe.one('load', function() {
// Attach listener to load events that occur after successful form submittal
$iframe.load(function() {
microBox.close();
if (typeof(callback) == 'function') {
var iframe = $iframe[0];
var doc = iframe.contentWindow.document;
var data = doc.body.innerHTML;
callback(data);
}
});
});
this.submit(function() {
microBox.show(content);
});
return this;
};
$('#myForm').bgForm('Please wait...');
At the end of the script that generates the file I have:
header('Refresh: 0;url=fetch.php?token=' . $token);
echo '<html></html>';
This will cause the load event on the iframe to be fired. Then the wait message is closed and the file download will then start. Tested on IE7 and Firefox.
Create a function calling it as the command you want to invoke. In this case, I need to use the ruok command.
Then, call the function and assign its result into a variable. In this case, I am assigning the result to the variable health.
function ruok {
echo ruok | nc *ip* 2181
}
health=echo ruok *ip*
This one is not bad too :
public static String join(String delimitor,String ... subkeys) {
String result = null;
if(null!=subkeys && subkeys.length>0) {
StringBuffer joinBuffer = new StringBuffer(subkeys[0]);
for(int idx=1;idx<subkeys.length;idx++) {
joinBuffer.append(delimitor).append(subkeys[idx]);
}
result = joinBuffer.toString();
}
return result;
}
if (Enum.IsDefined(typeof(foo), value))
{
return (Foo)Enum.Parse(typeof(foo), value);
}
Hope this helps
Edit This answer got down voted as value in my example is a string, where as the question asked for an int. My applogies; the following should be a bit clearer :-)
Type fooType = typeof(foo);
if (Enum.IsDefined(fooType , value.ToString()))
{
return (Foo)Enum.Parse(fooType , value.ToString());
}
The best way is to change any setting you want in your code.
Check out the below example:
using(WCFServiceClient client = new WCFServiceClient ())
{
client.Endpoint.Binding.SendTimeout = new TimeSpan(0, 1, 30);
}
Any solution work only if List a list(of string)
If you have a generic list of your own Objects like list(of car) where car has n properties, you must loop the PropertiesInfo of each car object.
Look at: http://www.csharptocsharp.com/generate-csv-from-generic-list
You can use the following generic method for your purpose. It should solve your issue.
//Called method
-(NSMutableArray*)sortArrayList:(NSMutableArray*)arrDeviceList filterKeyName:(NSString*)sortKeyName ascending:(BOOL)isAscending{
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:sortKeyName ascending:isAscending];
[arrDeviceList sortUsingDescriptors:[NSArray arrayWithObject:sorter]];
return arrDeviceList;
}
//Calling method
[self sortArrayList:arrSomeList filterKeyName:@"anything like date,name etc" ascending:YES];
Using some ES6 / ES2015:
If you don't like to create an extra function and remove the items 'inline'.
Object.keys(obj).forEach(k => (!obj[k] && obj[k] !== undefined) && delete obj[k]);
Same, written as a function.
const removeEmpty = (obj) => {
Object.keys(obj).forEach((k) => (!obj[k] && obj[k] !== undefined) && delete obj[k]);
return obj;
};
This function uses recursion to delete items from nested objects as well:
const removeEmpty = (obj) => {
Object.keys(obj).forEach(k =>
(obj[k] && typeof obj[k] === 'object') && removeEmpty(obj[k]) ||
(!obj[k] && obj[k] !== undefined) && delete obj[k]
);
return obj;
};
Same as function before but with ES7 / 2016 Object.entries
:
const removeEmpty = (obj) => {
Object.entries(obj).forEach(([key, val]) =>
(val && typeof val === 'object') && removeEmpty(val) ||
(val === null || val === "") && delete obj[key]
);
return obj;
};
Same as third example but in plain ES5:
function removeEmpty(obj) {
Object.keys(obj).forEach(function(key) {
(obj[key] && typeof obj[key] === 'object') && removeEmpty(obj[key]) ||
(obj[key] === '' || obj[key] === null) && delete obj[key]
});
return obj;
};
I would advise against restricting the SecurityProtocol to TLS 1.1.
The recommended solution is to use
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls
Another option is add the following Registry key:
Key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319
Value: SchUseStrongCrypto
It is worth noting that .NET 4.6 will use the correct protocol by default and does not require either solution.
The simplest way is using HTML META tag like this:
<meta http-equiv="refresh" content="3;url=http://example.com/" />
This routine will search for a path\ or file.ext in the path variable
it returns 0 if found. Path\ or file may contain spaces if quoted.
If a variable is passed as the last argument it will be set to d:\path\file
.
@echo off&goto :PathCheck
:PathCheck.CMD
echo.PathCheck.CMD: Checks for existence of a path or file in %%PATH%% variable
echo.Usage: PathCheck.CMD [Checkpath] or [Checkfile] [PathVar]
echo.Checkpath must have a trailing \ but checkfile must not
echo.If Checkpath contains spaces use quotes ie. "C:\Check path\"
echo.Checkfile must not include a path, just the filename.ext
echo.If Checkfile contains spaces use quotes ie. "Check File.ext"
echo.Returns 0 if found, 1 if not or -1 if checkpath does not exist at all
echo.If PathVar is not in command line it will be echoed with surrounding quotes
echo.If PathVar is passed it will be set to d:\path\checkfile with no trailing \
echo.Then %%PathVar%% will be set to the fully qualified path to Checkfile
echo.Note: %%PathVar%% variable set will not be surrounded with quotes
echo.To view the path listing line by line use: PathCheck.CMD /L
exit/b 1
:PathCheck
if "%~1"=="" goto :PathCheck.CMD
setlocal EnableDelayedExpansion
set "PathVar=%~2"
set "pth="
set "pcheck=%~1"
if "%pcheck:~-1%" equ "\" (
if not exist %pcheck% endlocal&exit/b -1
set/a pth=1
)
for %%G in ("%path:;=" "%") do (
set "Pathfd=%%~G\"
set "Pathfd=!Pathfd:\\=\!"
if /i "%pcheck%" equ "/L" echo.!Pathfd!
if defined pth (
if /i "%pcheck%" equ "!Pathfd!" endlocal&exit/b 0
) else (
if exist "!Pathfd!%pcheck%" goto :CheckfileFound
)
)
endlocal&exit/b 1
:CheckfileFound
endlocal&(
if not "%PathVar%"=="" (
call set "%~2=%Pathfd%%pcheck%"
) else (echo."%Pathfd%%pcheck%")
exit/b 0
)
The best way to accomplish this is by simply adding "href" to the link button like below.
<asp:LinkButton runat="server" id="SomeLinkButton" href="url" CssClass="btn btn-primary btn-sm">Button Text</asp:LinkButton>
Using javascript, or doing this programmatically in the page_load, will work as well but is not the best way to go about doing this.
You will get this result:
<a id="MainContent_ctl00_SomeLinkButton" class="btn btn-primary btn-sm" href="url" href="javascript:__doPostBack('ctl00$MainContent$ctl00$lSomeLinkButton','')">Button Text</a>
You can also get the same results by using using a regular
<a href="" class=""></a>
.
You need to specify an offset to addr2line, not a virtual address (VA). Presumably if you had address space randomization turned off, you could use a full VA, but in most modern OSes, address spaces are randomized for a new process.
Given the VA 0x4005BDC
by valgrind, find the base address of your process or library in memory. Do this by examining the /proc/<PID>/maps
file while your program is running. The line of interest is the text
segment of your process, which is identifiable by the permissions r-xp
and the name of your program or library.
Let's say that the base VA is 0x0x4005000
. Then you would find the difference between the valgrind supplied VA and the base VA: 0xbdc
. Then, supply that to add2line:
addr2line -e a.out -j .text 0xbdc
And see if that gets you your line number.
private void button5_Click(object sender, EventArgs e)
{
this.Visible = false;
Form2 login = new Form2();
login.ShowDialog();
}
Save the following code as a file: cygwin_bash.reg
This will add opening Cygwin in the current directory and opening Cygwin in the specified folder at the same time.
Use ".bashrc
" instead of ".bash_profile
" configuration. Because of exec bash
. .bashrc
is executed for interactive non-login shells. see: https://apple.stackexchange.com/questions/51036/what-is-the-difference-between-bash-profile-and-bashrc
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\Background\shell\z_cygwin_bash]
@="Cygwin Here"
"Icon"="C:\\cygwin64\\Cygwin.ico"
[HKEY_CLASSES_ROOT\Directory\Background\shell\z_cygwin_bash\command]
@="C:\\cygwin64\\bin\\mintty.exe /bin/sh -lc 'cd \"`cygpath \"%V\"`\"; exec bash'"
[HKEY_CLASSES_ROOT\Directory\shell\z_cygwin_bash]
@="Cygwin Here"
"Icon"="C:\\cygwin64\\Cygwin.ico"
[HKEY_CLASSES_ROOT\Directory\shell\z_cygwin_bash\command]
@="C:\\cygwin64\\bin\\mintty.exe /bin/sh -lc 'cd \"`cygpath \"%V\"`\"; exec bash'"
Code Runner Extension will only let you "run" java files.
To truly debug 'Java' files follow the quick one-time setup:
.vscode
in the same folder..vscode
folder: tasks.json
and launch.json
tasks.json
:{ "version": "2.0.0", "type": "shell", "presentation": { "echo": true, "reveal": "always", "focus": false, "panel": "shared" }, "isBackground": true, "tasks": [ { "taskName": "build", "args": ["-g", "${file}"], "command": "javac" } ] }
launch.json
:{ "version": "0.2.0", "configurations": [ { "name": "Debug Java", "type": "java", "request": "launch", "externalConsole": true, //user input dosen't work if set it to false :( "stopOnEntry": true, "preLaunchTask": "build", // Runs the task created above before running this configuration "jdkPath": "${env:JAVA_HOME}/bin", // You need to set JAVA_HOME enviroment variable "cwd": "${workspaceRoot}", "startupClass": "${workspaceRoot}${file}", "sourcePath": ["${workspaceRoot}"], // Indicates where your source (.java) files are "classpath": ["${workspaceRoot}"], // Indicates the location of your .class files "options": [], // Additional options to pass to the java executable "args": [] // Command line arguments to pass to the startup class } ], "compounds": [] }
You are all set to debug java files, open any java file and press F5 (Debug->Start Debugging).
Tip: *To hide .class files in the side explorer of VS code, open settings
of VS code and paste the below config:
"files.exclude": {
"*.class": true
}
Try something like this:
public class test
{
public static void main(String a[])
{
long tmp = 1346524199000;
Date d = new Date(tmp);
System.out.println(d);
}
}
If you want to style only the colors of the tooltips do as follow:
.tooltip-inner { background-color: #000; color: #fff; }
.tooltip.top .tooltip-arrow { border-top-color: #000; }
.tooltip.right .tooltip-arrow { border-right-color: #000; }
.tooltip.bottom .tooltip-arrow { border-bottom-color: #000; }
.tooltip.left .tooltip-arrow { border-left-color: #000; }
If you can't find what process is running elasticsearch on windows machine you can try running in console:
netstat -a -n -o
Look for port elasticsearch is running, default is 9200
. Last column is PID for process that is using that port. You can shutdown it with simple command in console
taskkill /PID here_goes_PID /F
Here's a simple class that will accomplish what you want
import java.util.HashMap;
public class QuickHash extends HashMap<String,String> {
public QuickHash(String...KeyValuePairs) {
super(KeyValuePairs.length/2);
for(int i=0;i<KeyValuePairs.length;i+=2)
put(KeyValuePairs[i], KeyValuePairs[i+1]);
}
}
And then to use it
Map<String, String> Foo=QuickHash(
"a", "1",
"b", "2"
);
This yields {a:1, b:2}
There are several ways that you can transform data from multiple rows into columns.
PIVOT
In SQL Server you can use the PIVOT
function to transform the data from rows to columns:
select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
select value, columnname
from yourtable
) d
pivot
(
max(value)
for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;
See Demo.
columnnames
If you have an unknown number of columnnames
that you want to transpose, then you can use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName)
from yourtable
group by ColumnName, id
order by id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ' + @cols + N' from
(
select value, ColumnName
from yourtable
) x
pivot
(
max(value)
for ColumnName in (' + @cols + N')
) p '
exec sp_executesql @query;
See Demo.
If you do not want to use the PIVOT
function, then you can use an aggregate function with a CASE
expression:
select
max(case when columnname = 'FirstName' then value end) Firstname,
max(case when columnname = 'Amount' then value end) Amount,
max(case when columnname = 'PostalCode' then value end) PostalCode,
max(case when columnname = 'LastName' then value end) LastName,
max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable
See Demo.
This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:
select fn.value as FirstName,
a.value as Amount,
pc.value as PostalCode,
ln.value as LastName,
an.value as AccountNumber
from yourtable fn
left join yourtable a
on fn.somecol = a.somecol
and a.columnname = 'Amount'
left join yourtable pc
on fn.somecol = pc.somecol
and pc.columnname = 'PostalCode'
left join yourtable ln
on fn.somecol = ln.somecol
and ln.columnname = 'LastName'
left join yourtable an
on fn.somecol = an.somecol
and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'
There are a few ways to escape everything in HTML, none of them nice.
Or you could put in an iframe
that loads a plain old text file.
I used Brendan Bullen's answer as a starting point for a similar issue I had which was to retrive the value of a specific field in a JSON string. However, like I commented on his answer, it is not entirely accurate. If your left boundary isn't just a space like in the original question, then the discrepancy increases.
Corrected solution:
SUBSTRING(
sentence,
LOCATE(' ', sentence) + 1,
LOCATE(' ', sentence, (LOCATE(' ', sentence) + 1)) - LOCATE(' ', sentence) - 1
)
The two differences are the +1 in the SUBSTRING index parameter and the -1 in the length parameter.
For a more general solution to "find the first occurence of a string between two provided boundaries":
SUBSTRING(
haystack,
LOCATE('<leftBoundary>', haystack) + CHAR_LENGTH('<leftBoundary>'),
LOCATE(
'<rightBoundary>',
haystack,
LOCATE('<leftBoundary>', haystack) + CHAR_LENGTH('<leftBoundary>')
)
- (LOCATE('<leftBoundary>', haystack) + CHAR_LENGTH('<leftBoundary>'))
)
Open a basic text editor and type out your html. Save it as .html If you type in file:///C:/ into the address bar you can then navigate to your chosen file and run it. If you want to open a file that is on a server type in file:/// and instead of C:/ the first letter of the server followed by :/.
List<"classname"> getreport = cs.getcompletionreport();
var getreported = getreport.Select(c => new { demographic = c.rName);
where cs.getcompletionreport()
reference class file is Business Layer for App
I hope this helps.
You can't, but you can print 0 or 1
_Bool b = 1;
printf("%d\n", b);
replace one string to
$("#form-dialog").dialog('close');
$(this) here means another object $("#btnDone")
<script type="text/javascript">
$(document).ready(function () {
$("#form-dialog").dialog({
autoOpen: true,
modal: true,
width: 200,
draggable: true,
resizable: true
});
});
</script>
<div id="form-dialog" title="Form Submit">
<form action="default.aspx" method="post">
<input type="text" name="name" value=" " />
<input type="submit" value="submit" />
<a href="#" id="btnDone">CLOSE</a>
<script type="text/javascript">
$(document).ready(function () {
$("#btnDone").click(function () {
//I've replaced next string
// $(this) here means another object $("#btnDone")
$("#form-dialog").dialog('close');
});
});
</script>
</form>
</div>
Fixed it by reinstalling the Xampp.
If you don't want to go through all the technical stuff that the other proposes.
Back up the htdocs folder then uninstall Xampp, it will ask you if you want to retain the htdocs folder, opt-out. Completely uninstall, remove the remains. The install again, copy back your backed-up htdocs folder.
you're done.
An array type is denoted as T[n]
where T
is the element type and n
is a positive size, the number of elements in the array. The array type is a product type of the element type and the size. If one or both of those ingredients differ, you get a distinct type:
#include <type_traits>
static_assert(!std::is_same<int[8], float[8]>::value, "distinct element type");
static_assert(!std::is_same<int[8], int[9]>::value, "distinct size");
Note that the size is part of the type, that is, array types of different size are incompatible types that have absolutely nothing to do with each other. sizeof(T[n])
is equivalent to n * sizeof(T)
.
The only "connection" between T[n]
and T[m]
is that both types can implicitly be converted to T*
, and the result of this conversion is a pointer to the first element of the array. That is, anywhere a T*
is required, you can provide a T[n]
, and the compiler will silently provide that pointer:
+---+---+---+---+---+---+---+---+
the_actual_array: | | | | | | | | | int[8]
+---+---+---+---+---+---+---+---+
^
|
|
|
| pointer_to_the_first_element int*
This conversion is known as "array-to-pointer decay", and it is a major source of confusion. The size of the array is lost in this process, since it is no longer part of the type (T*
). Pro: Forgetting the size of an array on the type level allows a pointer to point to the first element of an array of any size. Con: Given a pointer to the first (or any other) element of an array, there is no way to detect how large that array is or where exactly the pointer points to relative to the bounds of the array. Pointers are extremely stupid.
The compiler will silently generate a pointer to the first element of an array whenever it is deemed useful, that is, whenever an operation would fail on an array but succeed on a pointer. This conversion from array to pointer is trivial, since the resulting pointer value is simply the address of the array. Note that the pointer is not stored as part of the array itself (or anywhere else in memory). An array is not a pointer.
static_assert(!std::is_same<int[8], int*>::value, "an array is not a pointer");
One important context in which an array does not decay into a pointer to its first element is when the &
operator is applied to it. In that case, the &
operator yields a pointer to the entire array, not just a pointer to its first element. Although in that case the values (the addresses) are the same, a pointer to the first element of an array and a pointer to the entire array are completely distinct types:
static_assert(!std::is_same<int*, int(*)[8]>::value, "distinct element type");
The following ASCII art explains this distinction:
+-----------------------------------+
| +---+---+---+---+---+---+---+---+ |
+---> | | | | | | | | | | | int[8]
| | +---+---+---+---+---+---+---+---+ |
| +---^-------------------------------+
| |
| |
| |
| | pointer_to_the_first_element int*
|
| pointer_to_the_entire_array int(*)[8]
Note how the pointer to the first element only points to a single integer (depicted as a small box), whereas the pointer to the entire array points to an array of 8 integers (depicted as a large box).
The same situation arises in classes and is maybe more obvious. A pointer to an object and a pointer to its first data member have the same value (the same address), yet they are completely distinct types.
If you are unfamiliar with the C declarator syntax, the parenthesis in the type int(*)[8]
are essential:
int(*)[8]
is a pointer to an array of 8 integers.int*[8]
is an array of 8 pointers, each element of type int*
.C++ provides two syntactic variations to access individual elements of an array. Neither of them is superior to the other, and you should familiarize yourself with both.
Given a pointer p
to the first element of an array, the expression p+i
yields a pointer to the i-th element of the array. By dereferencing that pointer afterwards, one can access individual elements:
std::cout << *(x+3) << ", " << *(x+7) << std::endl;
If x
denotes an array, then array-to-pointer decay will kick in, because adding an array and an integer is meaningless (there is no plus operation on arrays), but adding a pointer and an integer makes sense:
+---+---+---+---+---+---+---+---+
x: | | | | | | | | | int[8]
+---+---+---+---+---+---+---+---+
^ ^ ^
| | |
| | |
| | |
x+0 | x+3 | x+7 | int*
(Note that the implicitly generated pointer has no name, so I wrote x+0
in order to identify it.)
If, on the other hand, x
denotes a pointer to the first (or any other) element of an array, then array-to-pointer decay is not necessary, because the pointer on which i
is going to be added already exists:
+---+---+---+---+---+---+---+---+
| | | | | | | | | int[8]
+---+---+---+---+---+---+---+---+
^ ^ ^
| | |
| | |
+-|-+ | |
x: | | | x+3 | x+7 | int*
+---+
Note that in the depicted case, x
is a pointer variable (discernible by the small box next to x
), but it could just as well be the result of a function returning a pointer (or any other expression of type T*
).
Since the syntax *(x+i)
is a bit clumsy, C++ provides the alternative syntax x[i]
:
std::cout << x[3] << ", " << x[7] << std::endl;
Due to the fact that addition is commutative, the following code does exactly the same:
std::cout << 3[x] << ", " << 7[x] << std::endl;
The definition of the indexing operator leads to the following interesting equivalence:
&x[i] == &*(x+i) == x+i
However, &x[0]
is generally not equivalent to x
. The former is a pointer, the latter an array. Only when the context triggers array-to-pointer decay can x
and &x[0]
be used interchangeably. For example:
T* p = &array[0]; // rewritten as &*(array+0), decay happens due to the addition
T* q = array; // decay happens due to the assignment
On the first line, the compiler detects an assignment from a pointer to a pointer, which trivially succeeds. On the second line, it detects an assignment from an array to a pointer. Since this is meaningless (but pointer to pointer assignment makes sense), array-to-pointer decay kicks in as usual.
An array of type T[n]
has n
elements, indexed from 0
to n-1
; there is no element n
. And yet, to support half-open ranges (where the beginning is inclusive and the end is exclusive), C++ allows the computation of a pointer to the (non-existent) n-th element, but it is illegal to dereference that pointer:
+---+---+---+---+---+---+---+---+....
x: | | | | | | | | | . int[8]
+---+---+---+---+---+---+---+---+....
^ ^
| |
| |
| |
x+0 | x+8 | int*
For example, if you want to sort an array, both of the following would work equally well:
std::sort(x + 0, x + n);
std::sort(&x[0], &x[0] + n);
Note that it is illegal to provide &x[n]
as the second argument since this is equivalent to &*(x+n)
, and the sub-expression *(x+n)
technically invokes undefined behavior in C++ (but not in C99).
Also note that you could simply provide x
as the first argument. That is a little too terse for my taste, and it also makes template argument deduction a bit harder for the compiler, because in that case the first argument is an array but the second argument is a pointer. (Again, array-to-pointer decay kicks in.)
When I have added/modified/deleted many files (since the last commit), I like to look at those modifications in chronological order.
For that I use:
To list all non-staged files:
git ls-files --other --modified --exclude-standard
To get the last modified date for each file:
while read filename; do echo -n "$(stat -c%y -- $filename 2> /dev/null) "; echo $filename; done
Although ruvim suggests in the comments:
xargs -0 stat -c '%y %n' --
To sort them from oldest to more recent:
sort
An alias makes it easier to use:
alias gstlast='git ls-files --other --modified --exclude-standard|while read filename; do echo -n "$(stat -c%y -- $filename 2> /dev/null) "; echo $filename; done|sort'
Or (shorter and more efficient, thanks to ruvim)
alias gstlast='git ls-files --other --modified --exclude-standard|xargs -0 stat -c '%y %n' --|sort'
For example:
username@hostname:~> gstlast
2015-01-20 11:40:05.000000000 +0000 .cpl/params/libelf
2015-01-21 09:02:58.435823000 +0000 .cpl/params/glib
2015-01-21 09:07:32.744336000 +0000 .cpl/params/libsecret
2015-01-21 09:10:01.294778000 +0000 .cpl/_deps
2015-01-21 09:17:42.846372000 +0000 .cpl/params/npth
2015-01-21 12:12:19.002718000 +0000 sbin/git-rcd
I now can review my modifications, from oldest to more recent.
There is a very handy function in R edit
new_optim <- edit(optim)
It will open the source code of optim
using the editor specified in R's options
, and then you can edit it and assign the modified function to new_optim
. I like this function very much to view code or to debug the code, e.g, print some messages or variables or even assign them to a global variables for further investigation (of course you can use debug
).
If you just want to view the source code and don't want the annoying long source code printed on your console, you can use
invisible(edit(optim))
Clearly, this cannot be used to view C/C++ or Fortran source code.
BTW, edit
can open other objects like list, matrix, etc, which then shows the data structure with attributes as well. Function de
can be used to open an excel like editor (if GUI supports it) to modify matrix or data frame and return the new one. This is handy sometimes, but should be avoided in usual case, especially when you matrix is big.
Building on @rocksportrocker solution, It would make sense to dill when sending and RECVing the results.
import dill
import itertools
def run_dill_encoded(payload):
fun, args = dill.loads(payload)
res = fun(*args)
res = dill.dumps(res)
return res
def dill_map_async(pool, fun, args_list,
as_tuple=True,
**kw):
if as_tuple:
args_list = ((x,) for x in args_list)
it = itertools.izip(
itertools.cycle([fun]),
args_list)
it = itertools.imap(dill.dumps, it)
return pool.map_async(run_dill_encoded, it, **kw)
if __name__ == '__main__':
import multiprocessing as mp
import sys,os
p = mp.Pool(4)
res = dill_map_async(p, lambda x:[sys.stdout.write('%s\n'%os.getpid()),x][-1],
[lambda x:x+1]*10,)
res = res.get(timeout=100)
res = map(dill.loads,res)
print(res)
If you want to search as string, you can cast to text like this:
SELECT * FROM books WHERE price::TEXT LIKE '123%'
You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..
string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call
but still, it would not be found by the getElementById
because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.
You would need to use append
or appendTo
or after
etc.. to put it in the dom first..
Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..
Adding this just as an addition to @jimt's excellent answer:
one common way to define it all at initialization time is using an anonymous struct:
var opts = []struct {
shortnm byte
longnm, help string
needArg bool
}{
{'a', "multiple", "Usage for a", false},
{
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
}
This is commonly used for testing as well to define few test cases and loop through them.
Guys you are making things complicated ... it's really simple
from pprint import pprint
Dict={'B':1,'A':2,'C':3}
pprint(Dict)
The output is:
{'A':2,'B':1,'C':3}
This does and will do: :)
# python... 3.x
import operator
...
# line: line of text
return " ".join(filter(lambda a: operator.is_not(a, ""), line.strip().split(" ")))
Personally I am not sure how anything using regular expressions in python can be described as elegant. Most answers here are just doing "code golf" type RE tricks. Elegant coding is supposed to be easily understood.
def to_snake_case(not_snake_case):
final = ''
for i in xrange(len(not_snake_case)):
item = not_snake_case[i]
if i < len(not_snake_case) - 1:
next_char_will_be_underscored = (
not_snake_case[i+1] == "_" or
not_snake_case[i+1] == " " or
not_snake_case[i+1].isupper()
)
if (item == " " or item == "_") and next_char_will_be_underscored:
continue
elif (item == " " or item == "_"):
final += "_"
elif item.isupper():
final += "_"+item.lower()
else:
final += item
if final[0] == "_":
final = final[1:]
return final
>>> to_snake_case("RegularExpressionsAreFunky")
'regular_expressions_are_funky'
>>> to_snake_case("RegularExpressionsAre Funky")
'regular_expressions_are_funky'
>>> to_snake_case("RegularExpressionsAre_Funky")
'regular_expressions_are_funky'
It could be that one or two of your columns may have a factor in them, or what is more likely is that your columns may be formatted as factors. Please would you give str(col1) and str(col2) a try? That should tell you what format those columns are in.
I am unsure if you're trying to add the rows of a column to produce a new column or simply all of the numbers in both columns to get a single number.
Follow this tutorial Tensorflow GPU I did it and it works perfect.
Attention! - install version 9.0! newer version is not supported by Tensorflow-gpu
Steps:
pip install tensorflow-gpu
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
If got your question right you want to do something like
update table
set identity_column_name = some value
Let me tell you, it is not an easy process and it is not advisable to use it, as there may be some foreign key
associated on it.
But here are steps to do it, Please take a back-up
of table
Step 1- Select design view of the table
Step 2- Turn off the identity column
Now you can use the update
query.
Now redo
the step 1 and step 2 and Turn on the identity column
i tried this clean easy method and seems to work in all browsers. Inside the svg file:
<svg>_x000D_
<a id="anchor" xlink:href="http://www.google.com" target="_top">_x000D_
_x000D_
<!--your graphic-->_x000D_
_x000D_
</a>_x000D_
</svg>_x000D_
_x000D_
This method would work for a list implementation and could be implemented as an extension method.
public void TestMethod()
{
var first = new List<int> {1, 2, 3, 4, 5};
var second = new List<string> {"One", "Two", "Three", "Four", "Five"};
foreach(var value in this.Zip(first, second, (x, y) => new {Number = x, Text = y}))
{
Console.WriteLine("{0} - {1}",value.Number, value.Text);
}
}
public IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(List<TFirst> first, List<TSecond> second, Func<TFirst, TSecond, TResult> selector)
{
if (first.Count != second.Count)
throw new Exception();
for(var i = 0; i < first.Count; i++)
{
yield return selector.Invoke(first[i], second[i]);
}
}
what about using the official API?
According to the API doc:
DESTROY: Removes the datepicker functionality completely. This will return the element back to its pre-init state.
Use:
$("#txtSearch").datepicker("destroy");
to restore the input to its normal behaviour and
$("#txtSearch").datepicker(/*options*/);
again to show the datapicker again.
Install python version 3.6+
and open you text editor
or ide
write sample code like this:
from tkinter import *
root = Tk()
root.title("Answer")
root.mainloop()
SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.
$('img.conversation_img[alt="example"]')
.each(function(){
alert($(this).attr('src'))
});
This will display src attributes of all images of class 'conversation_img' with alt='example'
You can do this program in this way. The range is in between 0 to 99,999
def num_to_word(num):
word_num = { "0": "zero", "00": "", "1" : "One" , "2" : "Two", "3" : "Three", "4" : "Four", "5" : "Five","6" : "Six", "7": "Seven", "8" : "eight", "9" : "Nine","01" : "One" , "02" : "Two", "03" : "Three", "04" : "Four", "05" : "Five","06" : "Six", "07": "Seven", "08" : "eight", "09" : "Nine", "10" : "Ten", "11": "Eleven", "12" :"Twelve", "13" : "Thirteen", "14" : "Fourteen", "15" : "Fifteen", "17":"Seventeen", "18" :"Eighteen", "19": "Nineteen", "20" : "Twenty", "30" : "Thirty", "40" : "Forty", "50" : "Fifty", "60" : "Sixty", "70": "seventy", "80" : "eighty", "90" : "ninety"}
keys = []
for k in word_num.keys():
keys.append(k)
if len(num) == 1:
return(word_num[num[0]])
elif len(num) == 2:
c = 0
for k in keys:
if k == num[0] + num[1]:
c += 1
if c == 1:
return(word_num[num[0] + num[1]])
else:
return(word_num[str(int(num[0]) * 10)] + " " + word_num[num[1]])
elif len(num) == 3:
c = 0
for k in keys:
if k == num[1] + num[2]:
c += 1
if c == 1:
return(word_num[num[0]]+ " Hundred " + word_num[num[1] + num[2]])
else:
return(word_num[num[0]]+ " Hundred " + word_num[str(int(num[1]) * 10)] + " " + word_num[num[2]])
elif len(num) == 4:
c = 0
for k in keys:
if k == num[2] + num[3]:
c += 1
if c == 1:
if num[1] == '0' :
return(word_num[num[0]]+ " Thousand " + word_num[num[2] + num[3]])
else:
return(word_num[num[0]]+ " Thousand " + word_num[num[1]]+ " Hundred " + word_num[num[2] + num[3]])
else:
if num[1] == '0' :
return(word_num[num[0]]+ " Thousand " + word_num[str(int(num[2]) * 10)] + " " + word_num[num[3]])
else:
return(word_num[num[0]]+ " Thousand " + word_num[num[1]]+ " Hundred " + word_num[str(int(num[2]) * 10)] + " " + word_num[num[3]])
elif len(num) == 5:
c = 0
d = 0
for k in keys:
if k == num[3] + num[4]:
c += 1
for k in keys:
if k == num[0] + num[1]:
d += 1
if d == 1:
val = word_num[num[0] + num[1]]
else:
val = word_num[str(int(num[0]) * 10)] + " " + word_num[num[1]]
if c == 1:
if num[1] == '0' :
return(val + " Thousand " + word_num[num[3] + num[4]])
else:
return(val + " Thousand " + word_num[num[2]]+ " Hundred " + word_num[num[3] + num[4]])
else:
if num[1] == '0' :
return(val + " Thousand " + word_num[str(int(num[3]) * 10)] + " " + word_num[num[4]])
else:
return(val + " Thousand " + word_num[num[2]]+ " Hundred " + word_num[str(int(num[3]) * 10)] + " " + word_num[num[4]])
num = [str(d) for d in input("Enter number: ")]
print(num_to_word(num).upper())
The virtual keyword gives C++ its' ability to support polymorphism. When you have a pointer to an object of some class such as:
class Animal
{
public:
virtual int GetNumberOfLegs() = 0;
};
class Duck : public Animal
{
public:
int GetNumberOfLegs() { return 2; }
};
class Horse : public Animal
{
public:
int GetNumberOfLegs() { return 4; }
};
void SomeFunction(Animal * pAnimal)
{
cout << pAnimal->GetNumberOfLegs();
}
In this (silly) example, the GetNumberOfLegs() function returns the appropriate number based on the class of the object that it is called for.
Now, consider the function 'SomeFunction'. It doesn't care what type of animal object is passed to it, as long as it is derived from Animal. The compiler will automagically cast any Animal-derived class to a Animal as it is a base class.
If we do this:
Duck d;
SomeFunction(&d);
it'd output '2'. If we do this:
Horse h;
SomeFunction(&h);
it'd output '4'. We can't do this:
Animal a;
SomeFunction(&a);
because it won't compile due to the GetNumberOfLegs() virtual function being pure, which means it must be implemented by deriving classes (subclasses).
Pure Virtual Functions are mostly used to define:
a) abstract classes
These are base classes where you have to derive from them and then implement the pure virtual functions.
b) interfaces
These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.
I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser
which is doing most of the work. Where he puts req.body.name
, I believe he/she is using body-parser
to get the contents of the name attribute(s) received when the form is submitted.
If you do not want to use Express, use querystring
which is a built-in Node module. See the answers in the link below for an example of how to use querystring
.
It might help to look at this answer, which is very similar to your quest.
I refer few writings.
reference:
This getMemorySize() method is returned MemorySize that has total and free memory size.
I don't believe this code perfectly.
This code is testing on LG G3 cat.6 (v5.0.1)
private MemorySize getMemorySize() {
final Pattern PATTERN = Pattern.compile("([a-zA-Z]+):\\s*(\\d+)");
MemorySize result = new MemorySize();
String line;
try {
RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r");
while ((line = reader.readLine()) != null) {
Matcher m = PATTERN.matcher(line);
if (m.find()) {
String name = m.group(1);
String size = m.group(2);
if (name.equalsIgnoreCase("MemTotal")) {
result.total = Long.parseLong(size);
} else if (name.equalsIgnoreCase("MemFree") || name.equalsIgnoreCase("Buffers") ||
name.equalsIgnoreCase("Cached") || name.equalsIgnoreCase("SwapFree")) {
result.free += Long.parseLong(size);
}
}
}
reader.close();
result.total *= 1024;
result.free *= 1024;
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private static class MemorySize {
public long total = 0;
public long free = 0;
}
I know that Pattern.compile() is expensive cost so You may move its code to class member.
Run in command prompt.
pip list
Check what version you have installed on your system if you have an old version.
Try to uninstall the package...
pip uninstall requests
Try after to install it:
pip install requests
You can also test if pip does not do the job.
easy_install requests
Adding this script to my code fixed the dropdown menu.
<script>
$(document).ready(function () {
$('.dropdown-toggle').dropdown();
});
</script>
Array.prototype.map()
index:One can access the index Array.prototype.map()
via the second argument of the callback function. Here is an example:
const array = [1, 2, 3, 4];_x000D_
_x000D_
_x000D_
const map = array.map((x, index) => {_x000D_
console.log(index);_x000D_
return x + index;_x000D_
});_x000D_
_x000D_
console.log(map);
_x000D_
Array.prototype.map()
:Array.map()
is a object which will be the this
value for the callback function. Keep in mind that you have to use the regular function
keyword in order to declare the callback since an arrow function doesn't have its own binding to the this
keyword.For example:
const array = [1, 2, 3, 4];_x000D_
_x000D_
const thisObj = {prop1: 1}_x000D_
_x000D_
_x000D_
const map = array.map( function (x, index, array) {_x000D_
console.log(array);_x000D_
console.log(this)_x000D_
}, thisObj);
_x000D_
Hi was almost quitting this and go back to select 3.5.1. But finally I got the answer!
$('#test').select2({
placeholder: "Select a Country",
minimumResultsForSearch: 2,
ajax: {
url: '...',
dataType: 'json',
cache: false,
data: function (params) {
var queryParameters = {
q: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: data.items
};
}
}
});
var option1 = new Option("new",true, true);
$('#status').append(option1);
$('#status').trigger('change');
Just be sure that the new option is one of the select2 options. I get this by a json.
you can make a javascript object with key being name of the html snippet, and value being an array of html strings, that are joined together.
var html = {
top_crimes_template:
[
'<div class="top_crimes"><h3>Top Crimes</h3></div>',
'<table class="crimes-table table table-responsive table-bordered">',
'<tr>',
'<th>',
'<span class="list-heading">Crime:</span>',
'</th>',
'<th>',
'<span id="last_crime_span"># Arrests</span>',
'</th>',
'</tr>',
'</table>'
].join(""),
top_teams_template:
[
'<div class="top_teams"><h3>Top Teams</h3></div>',
'<table class="teams-table table table-responsive table-bordered">',
'<tr>',
'<th>',
'<span class="list-heading">Team:</span>',
'</th>',
'<th>',
'<span id="last_team_span"># Arrests</span>',
'</th>',
'</tr>',
'</table>'
].join(""),
top_players_template:
[
'<div class="top_players"><h3>Top Players</h3></div>',
'<table class="players-table table table-responsive table-bordered">',
'<tr>',
'<th>',
'<span class="list-heading">Players:</span>',
'</th>',
'<th>',
'<span id="last_player_span"># Arrests</span>',
'</th>',
'</tr>',
'</table>'
].join("")
};
Pitfall:
<my-directive></my-directive>
wont work on IE8 without workaround (https://docs.angularjs.org/guide/ie)<div data-my-directive="ValueOfTheFirstParameter"></div>
Instead of this:
<my-directive my-param="ValueOfTheFirstParameter"></my-directive>
We dont use custom html elements, because if this 2 facts.
Every directive by third party framework can be written in two ways:
<my-directive></my-directive>
or
<div data-my-directive></div>
does the same.
Other answers are correct -- whether a character is invisible or not depends on what font you use. This seems to be a pretty good list to me of characters that are truly invisible (not even space). It contains some chars that the other lists are missing.
'\u2060', // Word Joiner
'\u2061', // FUNCTION APPLICATION
'\u2062', // INVISIBLE TIMES
'\u2063', // INVISIBLE SEPARATOR
'\u2064', // INVISIBLE PLUS
'\u2066', // LEFT - TO - RIGHT ISOLATE
'\u2067', // RIGHT - TO - LEFT ISOLATE
'\u2068', // FIRST STRONG ISOLATE
'\u2069', // POP DIRECTIONAL ISOLATE
'\u206A', // INHIBIT SYMMETRIC SWAPPING
'\u206B', // ACTIVATE SYMMETRIC SWAPPING
'\u206C', // INHIBIT ARABIC FORM SHAPING
'\u206D', // ACTIVATE ARABIC FORM SHAPING
'\u206E', // NATIONAL DIGIT SHAPES
'\u206F', // NOMINAL DIGIT SHAPES
'\u200B', // Zero-Width Space
'\u200C', // Zero Width Non-Joiner
'\u200D', // Zero Width Joiner
'\u200E', // Left-To-Right Mark
'\u200F', // Right-To-Left Mark
'\u061C', // Arabic Letter Mark
'\uFEFF', // Byte Order Mark
'\u180E', // Mongolian Vowel Separator
'\u00AD' // soft-hyphen
You want your if
check to be:
{% if not loop.last %}
,
{% endif %}
Note that you can also shorten the code by using If Expression:
{{ ", " if not loop.last else "" }}
In my opinion the best approach to achieve this by using the filter
method as it's meaningless to return in a forEach
block; for an example on your snippet:
// Fetch all objects in SomeElements collection
var elementsCollection = SomeElements.find();
elementsCollection
.filter(function(element) {
return element.shouldBeProcessed;
})
.forEach(function(element){
doSomeLengthyOperation();
});
This will narrow down your elementsCollection
and just keep the filtred
elements that should be processed.
My 5 cents:
async/await
if and only if you do an IO operation, like DB or external service webservice.P.S. There are exceptional cases for point 1, but you need to have a good understanding of async internals for this.
As an additional advantage, you can do few IO calls in parallel if needed:
Task task1 = FooAsync(); // launch it, but don't wait for result
Task task2 = BarAsync(); // launch bar; now both foo and bar are running
await Task.WhenAll(task1, task2); // this is better in regard to exception handling
// use task1.Result, task2.Result
A generic piece of code that will work for multiple columns. This can also be used if there is a need to conditionally implement search functionality in the application.
search_key = "abc"
search_args = [col.ilike('%%%s%%' % search_key) for col in ['col1', 'col2', 'col3']]
query = Query(table).filter(or_(*search_args))
session.execute(query).fetchall()
Note: the %%
are important to skip % formatting the query.
I just published a command line interface utility to npm and github that allows you to copy keys that match a given pattern (even *) from one Redis database to another.
You can find the utility here:
Ok I found out the answer myself. Much like npm cache clean
, Yarn also has its own
yarn cache clean
I wrote a shell script called fullpath that contains this code, use it everyday:
#!/bin/sh
for i in $* ; do
echo $(pwd)/$i
done
Put it somewhere in your PATH, and make it executable(chmod 755 fullpath) then just use
fullpath file_or_directory
Still not cool enough to comment, but regarding @vladislav's comment the original article was fairly old. Here is an update document regarding DTU's, which would help answer the OP's question.
https://docs.microsoft.com/en-us/azure/sql-database/sql-database-what-is-a-dtu
You probably want to check the length of the string first and do something like this:
if (!myStr.empty())
{
char lastChar = *myStr.rbegin();
}
The \s
metacharacter matches whitespace characters.
You have to return
from the onbeforeunload
:
window.onbeforeunload = function() {
saveFormData();
return null;
}
function saveFormData() {
console.log('saved');
}
UPDATE
as per comments, alert does not seem to be working on newer versions anymore, anything else goes :)
FROM MDN
Since 25 May 2011, the HTML5 specification states that calls to
window.showModalDialog()
,window.alert()
,window.confirm()
, andwindow.prompt()
methods may be ignored during this event.
It is also suggested to use this through the addEventListener
interface:
You can and should handle this event through
window.addEventListener()
and thebeforeunload
event.
The updated code will now look like this:
window.addEventListener("beforeunload", function (e) {
saveFormData();
(e || window.event).returnValue = null;
return null;
});
Got better solution:
$('#element').resizable({
stop: function( event, ui ) {
$('#element').height(ui.originalSize.height);
}
});
import os
folder = '/Path/to/yourDir/'
fileList = os.listdir(folder)
for f in fileList:
filePath = folder + '/'+f
if os.path.isfile(filePath):
os.remove(filePath)
elif os.path.isdir(filePath):
newFileList = os.listdir(filePath)
for f1 in newFileList:
insideFilePath = filePath + '/' + f1
if os.path.isfile(insideFilePath):
os.remove(insideFilePath)
In my case it turns out my
new server was running MySQL 5.5
,
old server was running MySQL 5.6
.
So I got this error when trying to import the .sql
file I'd exported from my old server.
MySQL 5.5 does not support utf8mb4_unicode_520_ci
, but
MySQL 5.6 does.
Updating to MySQL 5.6
on the new server solved collation the error !
If you want to retain MySQL 5.5, you can:
- make a copy of your exported .sql
file
- replace instances of utf8mb4unicode520_ci
and utf8mb4_unicode_520_ci
...with utf8mb4_unicode_ci
- import your updated .sql
file.
My solution on UBUNTU (linux):
1.You have to delete the content from "known_hosts" file which is in "/home/YOUR_USERNAME/.ssh/known_hosts"
2.Generate a new ssh key like "ssh-keygen -t rsa -C "[email protected]" -b 4096"
3.Copy-paste your new ssh key in your git repository (gitlab in my case) SSH keys.
It works for me !
The Math.Sign method is one way to go. It will return -1 for negative numbers, 1 for positive numbers, and 0 for values equal to zero (i.e. zero has no sign). Double and single precision variables will cause an exception (ArithmeticException) to be thrown if they equal NaN.
"java.lang.NoClassDefFoundError: com.google.android.gms.R$styleable"
A had this error too, you need to: File -> import -> Existing Android Code Into Workspace -> Browse -> Android sdks -> extras -> google -> google_play_services -> lib_project -> google_play_services_lib and OK. Check the project and Finish.
The project goes to Package Explorer. Now go to your project (with error) -> properties -> Android and in Library click Add... the google_play_services_lib should be there! add and try again :)
Yes, it is not required and is usually omitted. It might be required for accessing variables after they have been overridden in the scope though:
Person::Person() {
int age;
this->age = 1;
}
Also, this:
Person::Person(int _age) {
age = _age;
}
It is pretty bad style; if you need an initializer with the same name use this notation:
Person::Person(int age) : age(age) {}
More info here: https://en.cppreference.com/w/cpp/language/initializer_list
In Numbers, click on the chart. Then in the BOTTOM LEFT corner there is the the option to either 'Plot Rows as Series'or 'Plot Columns as series'
This might be simplest way -
Collections.sort(listOfStudent,new Comparator<Student>(){
public int compare(Student s1,Student s2){
// Write your logic here.
}});
Using Java 8(lambda expression) -
listOfStudent.sort((s1, s2) -> s1.age - s2.age);
Series.apply(func, convert_dtype=True, args=(), **kwds)
args : tuple
x = my_series.apply(my_function, args = (arg1,))
Span is considered an in-line element. As such is basically constrains itself to the content within it. It more or less is transparent.
Think of it having the behavior of the 'b' tag.
It can be performed like <span style='font-weight: bold;'>bold text</span>
div is a block element.
Run time exactly where your code comes into life and you can see lot of important thing your code do.
Runtime has a responsibility of allocating memory , freeing memory , using operating system's sub system like (File Services, IO Services.. Network Services etc.)
Your code will be called "WORKING IN THEORY" until you practically run your code. and Runtime is a friend which helps in achiving this.
Try to Clean
your solution and then try once again.
It will definitely work. Because every thing in code seems to be ok.
Go through this link for cleaning solution>
http://social.msdn.microsoft.com/Forums/en-US/vsdebug/thread/e53aab69-75b9-434a-bde3-74ca0865c165/
The other response shows this, but essentially you just need to create a SqlParameter
, set the Direction
to Output
, and add it to the SqlCommand
's Parameters
collection. Then execute the stored procedure and get the value of the parameter.
Using your code sample:
// SqlConnection and SqlCommand are IDisposable, so stack a couple using()'s
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("sproc", conn))
{
// Create parameter with Direction as Output (and correct name and type)
SqlParameter outputIdParam = new SqlParameter("@ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(outputIdParam);
conn.Open();
cmd.ExecuteNonQuery();
// Some various ways to grab the output depending on how you would like to
// handle a null value returned from the query (shown in comment for each).
// Note: You can use either the SqlParameter variable declared
// above or access it through the Parameters collection by name:
// outputIdParam.Value == cmd.Parameters["@ID"].Value
// Throws FormatException
int idFromString = int.Parse(outputIdParam.Value.ToString());
// Throws InvalidCastException
int idFromCast = (int)outputIdParam.Value;
// idAsNullableInt remains null
int? idAsNullableInt = outputIdParam.Value as int?;
// idOrDefaultValue is 0 (or any other value specified to the ?? operator)
int idOrDefaultValue = outputIdParam.Value as int? ?? default(int);
conn.Close();
}
Be careful when getting the Parameters[].Value
, since the type needs to be cast from object
to what you're declaring it as. And the SqlDbType
used when you create the SqlParameter
needs to match the type in the database. If you're going to just output it to the console, you may just be using Parameters["@Param"].Value.ToString()
(either explictly or implicitly via a Console.Write()
or String.Format()
call).
EDIT: Over 3.5 years and almost 20k views and nobody had bothered to mention that it didn't even compile for the reason specified in my "be careful" comment in the original post. Nice. Fixed it based on good comments from @Walter Stabosz and @Stephen Kennedy and to match the update code edit in the question from @abatishchev.
I think, the best way to do it is this:
body {
font-family: Arial,Verdana,sans-serif;
background:url("/images/image.jpg") no-repeat fixed bottom right transparent;
}
In this way there's no need to do nothing more and it's quite simple.
At least, it works for me.
I hope it helps.
Based on the comments left above I ran this under sqlplus instead of SQL Developer and the UPDATE statement ran perfectly, leaving me to believe this is an issue in SQL Developer particularly as there was no ORA error number being returned. Thank you for leading me in the right direction.
The application is a server which simply runs until the system shuts down or it receives a Ctrl+C or the console window is closed.
Due to the extraordinary nature of the application, it is not feasible to "gracefully" exit. (It may be that I could code another application which would send a "server shutdown" message but that would be overkill for one application and still insufficient for certain circumstances like when the server (Actual OS) is actually shutting down.)
Because of these circumstances I added a "ConsoleCtrlHandler" where I stop my threads and clean up my COM objects etc...
Public Declare Auto Function SetConsoleCtrlHandler Lib "kernel32.dll" (ByVal Handler As HandlerRoutine, ByVal Add As Boolean) As Boolean
Public Delegate Function HandlerRoutine(ByVal CtrlType As CtrlTypes) As Boolean
Public Enum CtrlTypes
CTRL_C_EVENT = 0
CTRL_BREAK_EVENT
CTRL_CLOSE_EVENT
CTRL_LOGOFF_EVENT = 5
CTRL_SHUTDOWN_EVENT
End Enum
Public Function ControlHandler(ByVal ctrlType As CtrlTypes) As Boolean
.
.clean up code here
.
End Function
Public Sub Main()
.
.
.
SetConsoleCtrlHandler(New HandlerRoutine(AddressOf ControlHandler), True)
.
.
End Sub
This setup seems to work out perfectly. Here is a link to some C# code for the same thing.
This can happen for several reasons, including:
please check out this link for solution: https://developer.android.com/training/articles/security-ssl.html#CommonProblems
# A Simple Confusion Matrix Implementation
def confusionmatrix(actual, predicted, normalize = False):
"""
Generate a confusion matrix for multiple classification
@params:
actual - a list of integers or strings for known classes
predicted - a list of integers or strings for predicted classes
normalize - optional boolean for matrix normalization
@return:
matrix - a 2-dimensional list of pairwise counts
"""
unique = sorted(set(actual))
matrix = [[0 for _ in unique] for _ in unique]
imap = {key: i for i, key in enumerate(unique)}
# Generate Confusion Matrix
for p, a in zip(predicted, actual):
matrix[imap[p]][imap[a]] += 1
# Matrix Normalization
if normalize:
sigma = sum([sum(matrix[imap[i]]) for i in unique])
matrix = [row for row in map(lambda i: list(map(lambda j: j / sigma, i)), matrix)]
return matrix
The approach here is to pair up the unique classes found in the actual
vector into a 2-dimensional list. From there, we simply iterate through the zipped actual
and predicted
vectors and populate the counts using the indices to access the matrix positions.
Usage
cm = confusionmatrix(
[1, 1, 2, 0, 1, 1, 2, 0, 0, 1], # actual
[0, 1, 1, 0, 2, 1, 2, 2, 0, 2] # predicted
)
# And The Output
print(cm)
[[2, 1, 0], [0, 2, 1], [1, 2, 1]]
Note: the actual
classes are along the columns and the predicted
classes are along the rows.
# Actual
# 0 1 2
# # #
[[2, 1, 0], # 0
[0, 2, 1], # 1 Predicted
[1, 2, 1]] # 2
Class Names Can be Strings or Integers
cm = confusionmatrix(
["B", "B", "C", "A", "B", "B", "C", "A", "A", "B"], # actual
["A", "B", "B", "A", "C", "B", "C", "C", "A", "C"] # predicted
)
# And The Output
print(cm)
[[2, 1, 0], [0, 2, 1], [1, 2, 1]]
You Can Also Return The Matrix With Proportions (Normalization)
cm = confusionmatrix(
["B", "B", "C", "A", "B", "B", "C", "A", "A", "B"], # actual
["A", "B", "B", "A", "C", "B", "C", "C", "A", "C"], # predicted
normalize = True
)
# And The Output
print(cm)
[[0.2, 0.1, 0.0], [0.0, 0.2, 0.1], [0.1, 0.2, 0.1]]
Since writing this post, I've updated my library implementation to be a class that uses a confusion matrix representation internally to compute statistics, in addition to pretty printing the confusion matrix itself. See this Gist.
Example Usage
# Actual & Predicted Classes
actual = ["A", "B", "C", "C", "B", "C", "C", "B", "A", "A", "B", "A", "B", "C", "A", "B", "C"]
predicted = ["A", "B", "B", "C", "A", "C", "A", "B", "C", "A", "B", "B", "B", "C", "A", "A", "C"]
# Initialize Performance Class
performance = Performance(actual, predicted)
# Print Confusion Matrix
performance.tabulate()
With the output:
===================================
A? B? C?
A? 3 2 1
B? 1 4 1
C? 1 0 4
Note: class? = Predicted, class? = Actual
===================================
And for the normalized matrix:
# Print Normalized Confusion Matrix
performance.tabulate(normalized = True)
With the normalized output:
===================================
A? B? C?
A? 17.65% 11.76% 5.88%
B? 5.88% 23.53% 5.88%
C? 5.88% 0.00% 23.53%
Note: class? = Predicted, class? = Actual
===================================
The following command worked for me. Docker file was placed in my-app-master folder.
docker build -f my-app-master/Dockerfile -t my-app-master .
os.path.abspath(__file__)
will give you an absolute path (relpath()
available as well).
sys.argv[-1]
will give you a relative path.
Maybe you should try removing "new" keyword and see if works.
Because last time I got this error when I tried creating Typeface
something like this:
Typeface typeface = new Typeface().create("Arial",Typeface.BOLD);
Try the Currency Format Specifier ("C"). It automatically takes the current UI culture into account and displays currency values accordingly.
You can use it with either String.Format
or the overloaded ToString
method for a numeric type.
For example:
double value = 12345.6789;
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));
Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));
Console.WriteLine(value.ToString("C3", CultureInfo.CreateSpecificCulture("da-DK")));
// The example displays the following output on a system whose
// current culture is English (United States):
// $12,345.68
// $12,345.679
// kr 12.345,679
Write someMethod()
in this way:
public void someMethod() {
SomeClass.AnotherClass.MyEnum enumExample = SomeClass.AnotherClass.MyEnum.VALUE_A;
switch (enumExample) {
case VALUE_A:
break;
}
}
In switch statement you must use the constant name only.
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
if you want to call controller from form action that time used following code:
<form action="{{ action('SchoolController@getSchool') }}" >
Here SchoolController
is a controller name and getSchool
is a method name, you must use get
or post
before method name which should be same as in form tag.
A method you can use is itertuples()
, it iterates over DataFrame rows as namedtuples, with index value as first element of the tuple. And it is much much faster compared with iterrows()
. For itertuples()
, each row
contains its Index
in the DataFrame, and you can use loc
to set the value.
for row in df.itertuples():
if <something>:
df.at[row.Index, 'ifor'] = x
else:
df.at[row.Index, 'ifor'] = x
df.loc[row.Index, 'ifor'] = x
Under most cases, itertuples()
is faster than iat
or at
.
Thanks @SantiStSupery, using .at
is much faster than loc
.
Let's say that I want to create the following URL:
https://www.myawesomesite.com/turtles/types?type=1&sort=relevance#section-name
To build this with the Uri.Builder
I would do the following.
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority("www.myawesomesite.com")
.appendPath("turtles")
.appendPath("types")
.appendQueryParameter("type", "1")
.appendQueryParameter("sort", "relevance")
.fragment("section-name");
String myUrl = builder.build().toString();
Late to the game, but I found this method is extremely intuitive. https://codepen.io/adamchenwei/pen/BRNxJr
CSS
.imageContainer {
border: 1px black solid;
width: 450px;
height: 200px;
overflow: hidden;
}
.imageHolder {
border: 1px red dotted;
height: 100%;
display:flex;
align-items: center;
}
.imageItself {
height: auto;
width: 100%;
align-self: center;
}
HTML
<div class="imageContainer">
<div class="imageHolder">
<img class="imageItself" src="http://www.fiorieconfetti.com/sites/default/files/styles/product_thumbnail__300x360_/public/fiore_viola%20-%202.jpg" />
</div>
</div>
Going with what you've started:
row = [[]]
crimefile = open(fileName, 'r')
for line in crimefile.readlines():
tmp = []
for element in line[0:-1].split(','):
tmp.append(element)
row.append(tmp)
By the way guys, (int)Decimal.MaxValue will overflow. You can't get the "int" part of a decimal because the decimal is too friggen big to put in the int box. Just checked... its even too big for a long (Int64).
If you want the bit of a Decimal value to the LEFT of the dot, you need to do this:
Math.Truncate(number)
and return the value as... A DECIMAL or a DOUBLE.
edit: Truncate is definitely the correct function!
I same thing happen with me, If your code is correct and then also give 405 error. this error due to some authorization problem. go to authorization menu and change to "Inherit auth from parent".
For two rounding digits. Very simple and you are basically updating the variable instead of just display purposes which DecimalFormat does.
x = Math.floor(x * 100) / 100;
Use mixins
@mixin sentence-case() {_x000D_
text-transform: lowercase;_x000D_
&:first-letter {_x000D_
text-transform: uppercase;_x000D_
}_x000D_
}_x000D_
_x000D_
// USAGE:_x000D_
.title {_x000D_
@include sentence-case();_x000D_
}
_x000D_
the style is:
<style type="text/css">
.topcorner{
position:absolute;
top:0;
right:0;
}
</style>
hope it will work. Thanks
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray + anotherarray
In case you're already using the transform property for positioning your element (as I currently am), you can also animate the top margin:
.ball {
animation: bounce 1s infinite alternate;
-webkit-animation: bounce 1s infinite alternate;
}
@keyframes bounce {
from {
margin-top: 0;
}
to {
margin-top: -15px;
}
}
According to the javadoc a Scanner
does not seem to be intended for reading single characters. You attach a Scanner
to an InputStream
(or something else) and it parses the input for you. It also can strip of unwanted characters. So you can read numbers, lines, etc. easily. When you need only the characters from your input, use a InputStreamReader for example.
Maybe you have your NGINX setup for HTTPS but your certificates are invalid? I've had a similar problem in the past and redirecting from http to https solved the problem
They are largely the same, except that:
The alias declaration is compatible with templates, whereas the C style typedef is not.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
let touch : UITouch = touches.anyObject() as UITouch
if touch.view.isKindOfClass(UIPickerView)
{
}
}
Edit
As pointed out in @Kevin's answer, the correct way would be to use optional type cast operator as?
. You can read more about it on the section Optional Chaining
sub section Downcasting
.
Edit 2
As pointed on the other answer by user @KPM, using the is
operator is the right way to do it.
the proper way is:
.attr({target:'nw', title:'Opens in a new window'})
I think your port is probably open, but you don't have anything that listens on it.
The Apple Mac OS X operating system has SSH installed by default but the SSH daemon is not enabled. This means you can’t login remotely or do remote copies until you enable it.
To enable it, go to ‘System Preferences’. Under ‘Internet & Networking’ there is a ‘Sharing’ icon. Run that. In the list that appears, check the ‘Remote Login’ option. In OS X Yosemite and up, there is no longer an 'Internet & Networking' menu; it was moved to Accounts. The Sharing menu now has its own icon on the main System Preferences menu. (thx @AstroCB)
This starts the SSH daemon immediately and you can remotely login using your username. The ‘Sharing’ window shows at the bottom the name and IP address to use. You can also find this out using ‘whoami’ and ‘ifconfig’ from the Terminal application.
These instructions are copied from Enable SSH in Mac OS X, but I wanted to make sure they won't go away and to provide quick access.
my problem (git on macOS) was solved by using
sudo git
instead of just git
in all add
and commit
commands
I had this issue occurring with mailto:
and tel:
links inside an iframe (in Chrome, not a webview). Clicking the links would show the grey "page not found" page and inspecting the page showed it had a ERR_UNKNOWN_URL_SCHEME error.
Adding target="_blank"
, as suggested by this discussion of the issue fixed the problem for me.
// Initiate set interval and assign it to intervalListener
var intervalListener = self.setInterval(function () {someProcess()}, 1000);
function someProcess() {
console.log('someProcess() has been called');
// If some condition is true clear the interval
if (stopIntervalIsTrue) {
window.clearInterval(intervalListener);
}
}
String currentString = "Fruit: they taste good";
String[] separated = currentString.split(":");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"
You may want to remove the space to the second String:
separated[1] = separated[1].trim();
If you want to split the string with a special character like dot(.) you should use escape character \ before the dot
Example:
String currentString = "Fruit: they taste good.very nice actually";
String[] separated = currentString.split("\\.");
separated[0]; // this will contain "Fruit: they taste good"
separated[1]; // this will contain "very nice actually"
There are other ways to do it. For instance, you can use the StringTokenizer
class (from java.util
):
StringTokenizer tokens = new StringTokenizer(currentString, ":");
String first = tokens.nextToken();// this will contain "Fruit"
String second = tokens.nextToken();// this will contain " they taste good"
// in the case above I assumed the string has always that syntax (foo: bar)
// but you may want to check if there are tokens or not using the hasMoreTokens method
#######################
### the img page ###
#######################
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#f').live('change' ,function(){
$('#fo').ajaxForm({target: '#d'}).submit();
});
});
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
<input type="file" name="f" id="f" value="start upload" />
<input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>
#############################
### the nextimg page ###
#############################
<?php
$name=$_FILES['f']['name'];
$tmp=$_FILES['f']['tmp_name'];
$new=time().$name;
$new="upload/".$new;
move_uploaded_file($tmp,$new);
if($_FILES['f']['error']==0)
{
?>
<h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
}
?>
Actually, in VS Code 1.48.1, there is a toggleTerminal
command; I don't know if it was available in previous versions ;) You can utilize it in the keybindings.json
file.
This worked for me on Windows, and should also works on Linux.
{
"key": "ctrl+alt+right",
"command": "workbench.action.terminal.toggleTerminal",
"when": "editorTextFocus || terminalFocus"
}
There's a bug here: currently cannot pass arguments to str.lstrip
and str.rstrip
:
http://github.com/pydata/pandas/issues/2411
EDIT: 2012-12-07 this works now on the dev branch:
In [8]: df['result'].str.lstrip('+-').str.rstrip('aAbBcC')
Out[8]:
1 52
2 62
3 44
4 30
5 110
Name: result
In the "disable" script, the order by clause should be that:
ORDER BY c.constraint_type DESC, c.last_change DESC
The goal of this clause is disable the constraints in the right order.
Swift 3.0+
Left padding String
extension similar to padding(toLength:withPad:startingAt:)
in Foundation
extension String {
func leftPadding(toLength: Int, withPad: String = " ") -> String {
guard toLength > self.characters.count else { return self }
let padding = String(repeating: withPad, count: toLength - self.characters.count)
return padding + self
}
}
Usage:
let s = String(123)
s.leftPadding(toLength: 8, withPad: "0") // "00000123"
Make an exception handler like this,
private int ConvertIntoNumeric(String xVal)
{
try
{
return Integer.parseInt(xVal);
}
catch(Exception ex)
{
return 0;
}
}
.
.
.
.
int xTest = ConvertIntoNumeric("N/A"); //Will return 0
Worth mentioning: you should download the x64 version!
From the main download page (https://www.iis.net/downloads/microsoft/url-rewrite) click "additional downloads" (under the main download button) and download the x64 version (because for some reason - the default download version is x86)
You can use either [[
or ((
keyword. When you use [[
keyword, you have to use string operators such as -eq
, -lt
. I think, ((
is most preferred for arithmetic, because you can directly use operators such as ==
, <
and >
.
Using [[
operator
a=$1
b=$2
if [[ a -eq 1 || b -eq 2 ]] || [[ a -eq 3 && b -eq 4 ]]
then
echo "Error"
else
echo "No Error"
fi
Using ((
operator
a=$1
b=$2
if (( a == 1 || b == 2 )) || (( a == 3 && b == 4 ))
then
echo "Error"
else
echo "No Error"
fi
Do not use -a
or -o
operators Since it is not Portable.
Set the position of the stream to the 0 before copying it to the zip stream.
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
var demoFile = archive.CreateEntry("foo.txt");
using (var entryStream = demoFile.Open())
using (var streamWriter = new StreamWriter(entryStream))
{
streamWriter.Write("Bar!");
}
}
using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
{
memoryStream.Position=0;
memoryStream.WriteTo(fileStream);
}
}
even better, this will measure the average of n iterations of your query! Great for a more accurate reading.
declare @tTOTAL int = 0
declare @i integer = 0
declare @itrs integer = 100
while @i < @itrs
begin
declare @t0 datetime = GETDATE()
--your query here
declare @t1 datetime = GETDATE()
set @tTotal = @tTotal + DATEDIFF(MICROSECOND,@t0,@t1)
set @i = @i + 1
end
select @tTotal/@itrs
Create a new repository
git clone <url>
cd "repositoryName"
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master
Existing folder
cd existing_folder
git init
git remote add origin <url>
git add .
git commit -m "Initial commit"
git push -u origin master
Existing Git repository
cd existing_repo
git remote rename origin old-origin
git remote add origin <url>
git push -u origin --all
git push -u origin --tags
I faced a similar problem. I am using Anaconda on windows and I resolved it as follows: 1) search for "Anaconda prompt" from the start menu 2) Right click and select "Run as administrator" 3) The follow the installation steps...
This takes care of the permission issues
old question, new verb in tidyverse:
library(tidyr) # version >= 0.8.0
df <- data.frame(var1=c('a', 'b', 'c'), var2=c('d', 'e', 'f'), freq=1:3)
df %>%
uncount(freq)
var1 var2
1 a d
2 b e
2.1 b e
3 c f
3.1 c f
3.2 c f
Date range between 12/31/1996 and 12/31/2020
SELECT dt, to_char(dt, 'MM/DD/YYYY') as date_name,
EXTRACT(year from dt) as year,
EXTRACT(year from fiscal_dt) as fiscal_year,
initcap(to_char(dt, 'MON')) as month,
to_char(dt, 'YYYY') || ' ' || initcap(to_char(dt, 'MON')) as year_month,
to_char(fiscal_dt, 'YYYY') || ' ' || initcap(to_char(dt, 'MON')) as fiscal_year_month,
EXTRACT(year from dt)*100 + EXTRACT(month from dt) as year_month_id,
EXTRACT(year from fiscal_dt)*100 + EXTRACT(month from fiscal_dt) as fiscal_year_month_id,
to_char(dt, 'YYYY') || ' Q' || to_char(dt, 'Q') as quarter,
to_char(fiscal_dt, 'YYYY') || ' Q' || to_char(fiscal_dt, 'Q') as fiscal_quarter
--, EXTRACT(day from dt) as day_of_month, to_char(dt, 'YYYY-WW') as week_of_year, to_char(dt, 'D') as day_of_week
FROM (
SELECT dt, add_months(dt, 6) as fiscal_dt --starts July 1st
FROM (
SELECT TO_DATE('12/31/1996', 'mm/dd/yyyy') + ROWNUM as dt
FROM DUAL CONNECT BY ROWNUM < 366 * 30 --30 years
)
WHERE dt <= TO_DATE('12/31/2020', 'mm/dd/yyyy')
)
dumpbin
from the Visual Studio command prompt:
dumpbin /exports csp.dll
Example of output:
Microsoft (R) COFF/PE Dumper Version 10.00.30319.01
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file csp.dll
File Type: DLL
Section contains the following exports for CSP.dll
00000000 characteristics
3B1D0B77 time date stamp Tue Jun 05 12:40:23 2001
0.00 version
1 ordinal base
25 number of functions
25 number of names
ordinal hint RVA name
1 0 00001470 CPAcquireContext
2 1 000014B0 CPCreateHash
3 2 00001520 CPDecrypt
4 3 000014B0 CPDeriveKey
5 4 00001590 CPDestroyHash
6 5 00001590 CPDestroyKey
7 6 00001560 CPEncrypt
8 7 00001520 CPExportKey
9 8 00001490 CPGenKey
10 9 000015B0 CPGenRandom
11 A 000014D0 CPGetHashParam
12 B 000014D0 CPGetKeyParam
13 C 00001500 CPGetProvParam
14 D 000015C0 CPGetUserKey
15 E 00001580 CPHashData
16 F 000014F0 CPHashSessionKey
17 10 00001540 CPImportKey
18 11 00001590 CPReleaseContext
19 12 00001580 CPSetHashParam
20 13 00001580 CPSetKeyParam
21 14 000014F0 CPSetProvParam
22 15 00001520 CPSignHash
23 16 000015A0 CPVerifySignature
24 17 00001060 DllRegisterServer
25 18 00001000 DllUnregisterServer
Summary
1000 .data
1000 .rdata
1000 .reloc
1000 .rsrc
1000 .text
To script this:
pid=$(lsof -ti tcp:8080)
if [[ $pid ]]; then
kill -9 $pid
fi
The -t
argument makes the output of lsof "terse" which means that it only returns the PID.
I believe, you need to change your code little bit like follows alongside with your database filed type.
mysql_query("INSERT INTO table (`dateposted`) VALUES ($datetime)");
Hope, will work perfectly.
do this in two steps:
and use preg_replace
:
$stringWithoutNonLetterCharacters = preg_replace("/[\/\&%#\$]/", "_", $yourString);
$stringWithQuotesReplacedWithSpaces = preg_replace("/[\"\']/", " ", $stringWithoutNonLetterCharacters);
I had to transfer texts from an Excel file to an xliff file. We had some texts that were originally in uppercase but those translators didn't use uppercase so I used notepad++ as intermediate to do the conversion.
Since I had the mouse in one hand (to mark in Excel and activate the different windows) I disliked the predefined shortcut (Ctrl+Shift+U) as "U" is too far away for my left hand. I first switched it to Ctrl+Shift+X which worked.
Then I realized, that you can create macros easily, so I recorded one doing:
That macro got assigned that very shortcut (Ctrl+Shift+X) and made my life easy :)
The example below shows the basic usage of the FileReader
to read the contents of an uploaded file. Here is a working Plunker of this example.
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body onload="init()">
<input id="fileInput" type="file" name="file" />
<pre id="fileContent"></pre>
</body>
</html>
script.js
function init(){
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event){
const reader = new FileReader()
reader.onload = handleFileLoad;
reader.readAsText(event.target.files[0])
}
function handleFileLoad(event){
console.log(event);
document.getElementById('fileContent').textContent = event.target.result;
}
I was having a similar or the same certification validation problem. I read that OpenSSL versions less than 1.0.2, which requests depends upon sometimes have trouble validating strong certificates (see here). CentOS 7 seems to use 1.0.1e which seems to have the problem.
I wasn't sure how to get around this problem on CentOS, so I decided to allow weaker 1024bit CA certificates.
import certifi # This should be already installed as a dependency of 'requests'
requests.get("https://example.com", verify=certifi.old_where())
All the error 80020101 means is that there was an error, of some sort, while evaluating JavaScript. If you load that JavaScript via Ajax, the evaluation process is particularly strict.
Sometimes removing // will fix the issue, but the inverse is not true... the issue is not always caused by //.
Look at the exact JavaScript being returned by your Ajax call and look for any issues in that script. For more details see a great writeup here
http://mattwhite.me/blog/2010/4/21/tracking-down-error-80020101-in-internet-exploder.html
To get the definition of the SQL codes, the easiest way is to use db2 cli!
at the unix or dos command prompt, just type
db2 "? SQL302"
this will give you the required explanation of the particular SQL code that you normally see in the java exception or your db2 sql output :)
hope this helped.
RecyclerView
is, by default, unaware of your dataset changes.
This means that whenever you make a deletion/addition on your data list, those changes won't be reflected to your RecyclerView directly. (i.e. you remove the item at index 5, but the 6th element remains in your recycler view).
RecyclerView
exposes some methods for you to communicate your dataset changes, reflecting those changes directly on your list items.
The standard Android APIs allow you to bind the process of data removal (for the purpose of the question) with the process of View removal.
The methods we talked about are:
notifyItemChanged(index: Int)
notifyItemInserted(index: Int)
notifyItemRemoved(index: Int)
notifyItemRangeChanged(startPosition: Int, itemCount: Int)
notifyItemRangeInserted(startPosition: Int, itemCount: Int)
notifyItemRangeRemoved(startPosition: Int, itemCount: Int)
If you don't properly specify what happens on each addition, change or removal of items, RecyclerView
children are animated unresponsively because of a lack of information about how to move the different views around the list.
Instead, the following code will precisely play the animation, just on the child that is being removed (And as a side note, it fixed any IndexOutOfBoundException
s, marked by the stacktrace as "data inconsistency").
void remove(position: Int) {
dataset.removeAt(position)
notifyItemChanged(position)
notifyItemRangeRemoved(position, 1)
}
Under the hood, if we look into RecyclerView
we can find documentation explaining that the second parameter we pass to notifyItemRangeRemoved
is the number of items that are removed from the dataset, not the total number of items (As wrongly reported in some others information sources).
/**
* Notify any registered observers that the <code>itemCount</code> items previously
* located at <code>positionStart</code> have been removed from the data set. The items
* previously located at and after <code>positionStart + itemCount</code> may now be found
* at <code>oldPosition - itemCount</code>.
*
* <p>This is a structural change event. Representations of other existing items in the data
* set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param positionStart Previous position of the first item that was removed
* @param itemCount Number of items removed from the data set
*/
public final void notifyItemRangeRemoved(int positionStart, int itemCount) {
mObservable.notifyItemRangeRemoved(positionStart, itemCount);
}
Do not use any of those functions. That's my personal view. They are counterintuitive, error-prone and they feel really verbose and unnecessary. Let a library like FastAdapter, Epoxy or Groupie take care of this business, or use an observable recycler view with data binding.
File type handling is new with iPhone OS 3.2, and is different than the already-existing custom URL schemes. You can register your application to handle particular document types, and any application that uses a document controller can hand off processing of these documents to your own application.
For example, my application Molecules (for which the source code is available) handles the .pdb and .pdb.gz file types, if received via email or in another supported application.
To register support, you will need to have something like the following in your Info.plist:
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeIconFiles</key>
<array>
<string>Document-molecules-320.png</string>
<string>Document-molecules-64.png</string>
</array>
<key>CFBundleTypeName</key>
<string>Molecules Structure File</string>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>com.sunsetlakesoftware.molecules.pdb</string>
<string>org.gnu.gnu-zip-archive</string>
</array>
</dict>
</array>
Two images are provided that will be used as icons for the supported types in Mail and other applications capable of showing documents. The LSItemContentTypes
key lets you provide an array of Uniform Type Identifiers (UTIs) that your application can open. For a list of system-defined UTIs, see Apple's Uniform Type Identifiers Reference. Even more detail on UTIs can be found in Apple's Uniform Type Identifiers Overview. Those guides reside in the Mac developer center, because this capability has been ported across from the Mac.
One of the UTIs used in the above example was system-defined, but the other was an application-specific UTI. The application-specific UTI will need to be exported so that other applications on the system can be made aware of it. To do this, you would add a section to your Info.plist like the following:
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.plain-text</string>
<string>public.text</string>
</array>
<key>UTTypeDescription</key>
<string>Molecules Structure File</string>
<key>UTTypeIdentifier</key>
<string>com.sunsetlakesoftware.molecules.pdb</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<string>pdb</string>
<key>public.mime-type</key>
<string>chemical/x-pdb</string>
</dict>
</dict>
</array>
This particular example exports the com.sunsetlakesoftware.molecules.pdb
UTI with the .pdb file extension, corresponding to the MIME type chemical/x-pdb
.
With this in place, your application will be able to handle documents attached to emails or from other applications on the system. In Mail, you can tap-and-hold to bring up a list of applications that can open a particular attachment.
When the attachment is opened, your application will be started and you will need to handle the processing of this file in your -application:didFinishLaunchingWithOptions:
application delegate method. It appears that files loaded in this manner from Mail are copied into your application's Documents directory under a subdirectory corresponding to what email box they arrived in. You can get the URL for this file within the application delegate method using code like the following:
NSURL *url = (NSURL *)[launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];
Note that this is the same approach we used for handling custom URL schemes. You can separate the file URLs from others by using code like the following:
if ([url isFileURL])
{
// Handle file being passed in
}
else
{
// Handle custom URL scheme
}
You didn't say what you needed this list for. If something used as a blacklist for password checks is enough cracklib might be good for you. It contains over 1.5M words.
ScheduledThreadPoolExecutor
has this ability, but it's quite heavyweight.
Timer
also has this ability but opens several thread even if used only once.
Here's a simple implementation with a test (signature close to Android's Handler.postDelayed()):
public class JavaUtil {
public static void postDelayed(final Runnable runnable, final long delayMillis) {
final long requested = System.currentTimeMillis();
new Thread(new Runnable() {
@Override
public void run() {
// The while is just to ignore interruption.
while (true) {
try {
long leftToSleep = requested + delayMillis - System.currentTimeMillis();
if (leftToSleep > 0) {
Thread.sleep(leftToSleep);
}
break;
} catch (InterruptedException ignored) {
}
}
runnable.run();
}
}).start();
}
}
Test:
@Test
public void testRunsOnlyOnce() throws InterruptedException {
long delay = 100;
int num = 0;
final AtomicInteger numAtomic = new AtomicInteger(num);
JavaUtil.postDelayed(new Runnable() {
@Override
public void run() {
numAtomic.incrementAndGet();
}
}, delay);
Assert.assertEquals(num, numAtomic.get());
Thread.sleep(delay + 10);
Assert.assertEquals(num + 1, numAtomic.get());
Thread.sleep(delay * 2);
Assert.assertEquals(num + 1, numAtomic.get());
}
My favoured technique:
signal clk : std_logic := '0'; -- make sure you initialise!
...
clk <= not clk after half_period;
I usually extend this with a finished
signal to allow me to stop the clock:
clk <= not clk after half_period when finished /= '1' else '0';
Gotcha alert:
Care needs to be taken if you calculate half_period
from another constant by dividing by 2. The simulator has a "time resolution" setting, which often defaults to nanoseconds... In which case, 5 ns / 2
comes out to be 2 ns
so you end up with a period of 4ns! Set the simulator to picoseconds and all will be well (until you need fractions of a picosecond to represent your clock time anyway!)
Assuming that they are in the same server, try this:
SELECT *
INTO SecondDB.TableName
FROM FirstDatabase.TableName
This will create a new table and just copy the data from FirstDatabase.TableName
to SecondDB.TableName
and won't create foreign keys or indexes.
I don't think that you really want an iframe, do you?
Unless you're doing something weird, you should be getting your results back as JSON or (in the worst case) XML, right?
For your white box / extra space issue, try
style="display: none;"
instead of
style="visibility: hidden;"
You have to Download the driver for your Device just go to device manager-->> your device-->update driver-->choose the usb driver path from sdk extras folder and click next. You can get the correct driver and you can run on real device
you can make a function like this
function translateTo($language, $word) {
define('defaultLang','english');
if (isset($lang[$language][$word]) == FALSE)
return $lang[$language][$word];
else
return $lang[defaultLang][$word];
}
The examples above don't correctly apply this
or pass arguments
correctly to the function override. Underscore _.wrap() wraps existing functions, applies this
and passes arguments
correctly. See: http://underscorejs.org/#wrap
Can you change the if condition to this:
if (!is.na(comments[l])) print(comments[l]);
You can only check for NA values with is.na().
Found these docu on the google docu pages:
In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns
edit
Using the example on the docu:
// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);
The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G
So you come to the range: C2:G8
There is an important bit that is not mentioned in the article to which you linked and that is flex-basis
. By default flex-basis
is auto
.
From the spec:
If the specified flex-basis is auto, the used flex basis is the value of the flex item’s main size property. (This can itself be the keyword auto, which sizes the flex item based on its contents.)
Each flex item has a flex-basis
which is sort of like its initial size. Then from there, any remaining free space is distributed proportionally (based on flex-grow
) among the items. With auto
, that basis is the contents size (or defined size with width
, etc.). As a result, items with bigger text within are being given more space overall in your example.
If you want your elements to be completely even, you can set flex-basis: 0
. This will set the flex basis to 0 and then any remaining space (which will be all space since all basises are 0) will be proportionally distributed based on flex-grow
.
li {
flex-grow: 1;
flex-basis: 0;
/* ... */
}
This diagram from the spec does a pretty good job of illustrating the point.
And here is a working example with your fiddle.
File->Project Structure->Project pane->"Android plugin version".
Make sure you don't confuse the Gradle version with the Android plugin version. The former is the build system itself, the latter is the plugin to the build system that knows how to build Android projects
you can just do $scope.todo = Todo.get({ id: 123 })
. .get()
and .query()
on a Resource return an object immediately and fill it with the result of the promise later (to update your template). It's not a typical promise which is why you need to either use a callback or the $promise property if you have some special code you want executed after the call. But there is no need to assign it to your scope in a callback if you are only using it in the template.
The answer above suggests changing the function to echo data rather than return it so that it can be captured.
For a function or program that you can't modify where the return value needs to be saved to a variable (like test
/[
, which returns a 0/1 success value), echo $?
within the command substitution:
# Test if we're remote.
isRemote="$(test -z "$REMOTE_ADDR"; echo $?)"
# Or:
isRemote="$([ -z "$REMOTE_ADDR" ]; echo $?)"
# Additionally you may want to reverse the 0 (success) / 1 (error) values
# for your own sanity, using arithmetic expansion:
remoteAddrIsEmpty="$([ -z "$REMOTE_ADDR" ]; echo $((1-$?)))"
E.g.
$ echo $REMOTE_ADDR
$ test -z "$REMOTE_ADDR"; echo $?
0
$ REMOTE_ADDR=127.0.0.1
$ test -z "$REMOTE_ADDR"; echo $?
1
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
1
$ unset REMOTE_ADDR
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
0
For a program which prints data but also has a return value to be saved, the return value would be captured separately from the output:
# Two different files, 1 and 2.
$ cat 1
1
$ cat 2
2
$ diffs="$(cmp 1 2)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [1] Diffs: [1 2 differ: char 1, line 1]
$ diffs="$(cmp 1 1)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [0] Diffs: []
# Or again, if you just want a success variable, reverse with arithmetic expansion:
$ cmp -s 1 2; filesAreIdentical=$((1-$?))
$ echo $filesAreIdentical
0
also one of the popular reasons maybe you miss to include the service file in your page
<script src="myservice.js"></script>
If you are using Bearing Token Auth, the above samples do not return an Application User.
Instead, use this:
ClaimsPrincipal currentUser = this.User;
var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
ApplicationUser user = await _userManager.FindByNameAsync(currentUserName);
This works in apsnetcore 2.0. Have not tried in earlier versions.
<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>
That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em'
as the measurement, you may want to use other units, like 'px'
.
EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:
In your HTML page, containing the <p>
tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:
<head>
<style type="text/css">
p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>
So above, all <p>
elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:
<head>
<style type="text/css">
.container p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</div>
<p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>
In the example above, only the <p>
element inside the div, whose class name is 'container', will have the styles applied - and not the <p>
element outside the container.
In addition to the above, you can collect your styles together and remove the style element from the <head>
tag, replacing it with a <link>
tag, which points to an external CSS file. This external file is where you'd now put your <p>
tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.
Sql Server we can use %
select * from orders where ID % 2 = 0;
This can be used in both Mysql and oracle. It is more affection to use mod function that %.
select * from orders where mod(ID,2) = 0
For people passing by now, in 2017, the new best way to achieve what you want is by using ConstraintLayout like this:
<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintDimensionRatio="1:1" />
And don't forget to add constraints to all of the four directions as needed by your layout.
Build a Responsive UI with ConstraintLayout
Furthermore, by now, PercentRelativeLayout has been deprecated (see Android documentation).
Put them into a list
and use merge
with Reduce
Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
# id v1 v2 v3
# 1 1 1 NA NA
# 2 10 4 NA NA
# 3 2 3 4 NA
# 4 43 5 NA NA
# 5 73 2 NA NA
# 6 23 NA 2 1
# 7 57 NA 3 NA
# 8 62 NA 5 2
# 9 7 NA 1 NA
# 10 96 NA 6 NA
You can also use this more concise version:
Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))
tf.all_variables()
can get you the information you want.
Also, this commit made today in TensorFlow Learn that provides a function get_variable_names
in estimator that you can use to retrieve all variable names easily.
Each version has some improvements in certain technologies. For users the biggest difference is whether or not to execute certain plugins, because some were made only for a particular version of Eclipse.
public function variables($variable="")
{
return empty($variable) ? mysql_query("SHOW VARIABLES") : mysql_query("SELECT @@$variable");
}
/*get datadir*/
$res = variables("datadir");
/*or get all variables*/
$res = variables();
You can use as many colors and images as you desire.
Please note that the priority with which the background images are rendered is FILO, the first specified image is on the top layer, the last specified image is on the bottom layer (see the snippet).
#composition {_x000D_
width: 400px;_x000D_
height: 200px;_x000D_
background-image:_x000D_
linear-gradient(to right, #FF0000, #FF0000), /* gradient 1 as solid color */_x000D_
linear-gradient(to right, #00FF00, #00FF00), /* gradient 2 as solid color */_x000D_
linear-gradient(to right, #0000FF, #0000FF), /* gradient 3 as solid color */_x000D_
url('http://lorempixel.com/400/200/'); /* image */_x000D_
background-repeat: no-repeat; /* same as no-repeat, no-repeat, no-repeat */_x000D_
background-position:_x000D_
0 0, /* gradient 1 */_x000D_
20px 0, /* gradient 2 */_x000D_
40px 0, /* gradient 3 */_x000D_
0 0; /* image position */_x000D_
background-size:_x000D_
30px 30px,_x000D_
30px 30px,_x000D_
30px 30px,_x000D_
100% 100%;_x000D_
}
_x000D_
<div id="composition">_x000D_
</div>
_x000D_
There is lecture on this by Sebastien Thurn in the free Udacity course AI for Robotics. Basically he makes a circular array of the indexed weights using the mod operator %
, sets a variable beta to 0, randomly chooses an index,
for loops through N where N is the number of indices and in the for loop firstly increments beta by the formula:
beta = beta + uniform sample from {0...2* Weight_max}
and then nested in the for loop, a while loop per below:
while w[index] < beta:
beta = beta - w[index]
index = index + 1
select p[index]
Then on to the next index to resample based on the probabilities (or normalized probability in the case presented in the course).
The lecture link: https://classroom.udacity.com/courses/cs373/lessons/48704330/concepts/487480820923
I am logged into Udacity with my school account so if the link does not work, it is Lesson 8, video number 21 of Artificial Intelligence for Robotics where he is lecturing on particle filters.
In Python >=3.4 this has become much simpler. You can now use pathlib.Path.parts
to get all the parts of a path.
Example:
>>> from pathlib import Path
>>> Path('C:/path/to/file.txt').parts
('C:\\', 'path', 'to', 'file.txt')
>>> Path(r'C:\path\to\file.txt').parts
('C:\\', 'path', 'to', 'file.txt')
On a Windows install of Python 3 this will assume that you are working with Windows paths, and on *nix it will assume that you are working with posix paths. This is usually what you want, but if it isn't you can use the classes pathlib.PurePosixPath
or pathlib.PureWindowsPath
as needed:
>>> from pathlib import PurePosixPath, PureWindowsPath
>>> PurePosixPath('/path/to/file.txt').parts
('/', 'path', 'to', 'file.txt')
>>> PureWindowsPath(r'C:\path\to\file.txt').parts
('C:\\', 'path', 'to', 'file.txt')
>>> PureWindowsPath(r'\\host\share\path\to\file.txt').parts
('\\\\host\\share\\', 'path', 'to', 'file.txt')
Edit: There is also a backport to python 2 available: pathlib2
The CSS box model is rather complicated, particularly when it comes to scrolling content. While the browser uses the values from your CSS to draw boxes, determining all the dimensions using JS is not straight-forward if you only have the CSS.
That's why each element has six DOM properties for your convenience: offsetWidth
, offsetHeight
, clientWidth
, clientHeight
, scrollWidth
and scrollHeight
. These are read-only attributes representing the current visual layout, and all of them are integers (thus possibly subject to rounding errors).
Let's go through them in detail:
offsetWidth
, offsetHeight
: The size of the visual box incuding all borders. Can be calculated by adding width
/height
and paddings and borders, if the element has display: block
clientWidth
, clientHeight
: The visual portion of the box content, not including borders or scroll bars , but includes padding . Can not be calculated directly from CSS, depends on the system's scroll bar size.scrollWidth
, scrollHeight
: The size of all of the box's content, including the parts that are currently hidden outside the scrolling area. Can not be calculated directly from CSS, depends on the content.Since offsetWidth
takes the scroll bar width into account, we can use it to calculate the scroll bar width via the formula
scrollbarWidth = offsetWidth - clientWidth - getComputedStyle().borderLeftWidth - getComputedStyle().borderRightWidth
Unfortunately, we may get rounding errors, since offsetWidth
and clientWidth
are always integers, while the actual sizes may be fractional with zoom levels other than 1.
Note that this
scrollbarWidth = getComputedStyle().width + getComputedStyle().paddingLeft + getComputedStyle().paddingRight - clientWidth
does not work reliably in Chrome, since Chrome returns width
with scrollbar already substracted. (Also, Chrome renders paddingBottom to the bottom of the scroll content, while other browsers don't)
As described in the IPv6 Wikipedia article,
IPv6 addresses are normally written as eight groups of four hexadecimal digits, where each group is separated by a colon (:)
A typical IPv6 address:
2001:0db8:85a3:0000:0000:8a2e:0370:7334
This is 39 characters long. IPv6 addresses are 128 bits long, so you could conceivably use a binary(16) column, but I think I'd stick with an alphanumeric representation.
import java.util.Scanner;
public class Myapplication{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int a;
System.out.println("enter:");
a = in.nextInt();
System.out.println("Number is= " + a);
}
}
The fluent way:
public static String fileNameWithOutExt (String fileName) {
return Optional.of(fileName.lastIndexOf(".")).filter(i-> i >= 0)
.map(i-> fileName.substring(0, i)).orElse(fileName);
}
For me the only working solution was to add the android-support-v7-appcompat library as well. It seems that this library is also needed in order to get rid of that message. Since then my applications have been working fine!
I hope it helps!
Try:
To_Date (SESSION_START_DATE_TIME, 'MM/DD/YYYY hh24:mi') >
To_Date ('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi' )