Here are my working example
@RequestMapping(value = "/api/v1/files/upload", method =RequestMethod.POST)
public ResponseEntity<?> upload(@RequestParam("files") MultipartFile[] files) {
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
List<String> tempFileNames = new ArrayList<>();
String tempFileName;
FileOutputStream fo;
try {
for (MultipartFile file : files) {
tempFileName = "/tmp/" + file.getOriginalFilename();
tempFileNames.add(tempFileName);
fo = new FileOutputStream(tempFileName);
fo.write(file.getBytes());
fo.close();
map.add("files", new FileSystemResource(tempFileName));
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
String response = restTemplate.postForObject(uploadFilesUrl, requestEntity, String.class);
} catch (IOException e) {
e.printStackTrace();
}
for (String fileName : tempFileNames) {
File f = new File(fileName);
f.delete();
}
return new ResponseEntity<Object>(HttpStatus.OK);
}
ansible-playbook release.yml --extra-vars "username=hello password=bye"
#you can now use the above command anywhere in the playbook as an example below:
tasks:
- name: Create a new user in Linux
shell: useradd -m -p {{username}} {{password}}"
essentially the shadow is the box shape just offset behind the actual box. in order to hide portions of the shadow, you need to create additional divs and set their z-index above the shadowed box so that the shadow is not visible.
If you'd like to have extremely specific control over your shadows, build them as images and created container divs with the right amount of padding and margins.. then use the png fix to make sure the shadows render properly in all browsers
var text = File.ReadAllText(file, Encoding.GetEncoding(codePage));
List of codepages : http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx
Building on the solution provided I thought it might be helpful to show an example passing your own custom data object (which I've referenced here as 'message' as per question).
Class A (sender):
YourDataObject *message = [[YourDataObject alloc] init];
// set your message properties
NSDictionary *dict = [NSDictionary dictionaryWithObject:message forKey:@"message"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationMessageEvent" object:nil userInfo:dict];
Class B (receiver):
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(triggerAction:) name:@"NotificationMessageEvent" object:nil];
}
#pragma mark - Notification
-(void) triggerAction:(NSNotification *) notification
{
NSDictionary *dict = notification.userInfo;
YourDataObject *message = [dict valueForKey:@"message"];
if (message != nil) {
// do stuff here with your message data
}
}
Since Oracle 12C, you can fetch a specific number of rows with FETCH FIRST ROW ONLY
.
In your case this implies an ORDER BY
, so the performance should be considered.
SELECT A, col_date
FROM TABLENAME t_ext
ORDER BY col_date DESC NULLS LAST
FETCH FIRST 1 ROW ONLY;
The NULLS LAST
is just in case you may have null values in your field.
You really need to post a more complete example, so we can see what you're trying to do. From what you have posted, here's what I can see. First, there is no built-in round()
method. You need to either call Math.round(n)
, or statically import Math.round
, and then call it like you have.
You could also use a LEFT JOIN and IS NULL condition:
SELECT
mac,
creation_date
FROM
logs
LEFT JOIN consols ON logs.mac = consols.mac
WHERE
logs_type_id=11
AND
consols.mac IS NULL;
An index on the "mac" columns might improve performance.
Following is a dump of frameworks. It doesn't mean I actually used them:
Coeus. A traditional MVC web framework for Scala.
Unfiltered. A toolkit for servicing HTTP requests in Scala.
Amore. A Scala port of the Ruby web framework Sinatra
Scales XML. Flexible approach to XML handling and a simplified way of interacting with XML.
Belt. A Rack-like interface for web applications built on top of Scalaz-HTTP
MixedBits. A framework for the Scala progamming language to help build web sites
Circumflex. Unites several self-contained open source projects for application development using the Scala programming language.
Scala Webmachine. Port of Basho's webmachine in Scala, a REST-based system for building web applications
Bowler. A RESTful, multi-channel ready Scala web framework
The broken pipe error usually occurs if your request is blocked or takes too long and after request-side timeout, it'll close the connection and then, when the respond-side (server) tries to write to the socket, it will throw a pipe broken error.
A way that will fail if your input string isn't valid pairs of hex characters...:
>>> import binascii
>>> ' '.join(hex(ord(i)) for i in binascii.unhexlify('deadbeef'))
'0xde 0xad 0xbe 0xef'
This is just describing why I had this issue in case someone finds it helpful.
My problem was that I had upgraded php with homebrew and had forced at some point the variable PHP_INI_SCAN_DIR in my profile or bashrc file so it was pointing to the old php version. Removed that line and fixed.
You need to find the bin folder and then open a command prompt on that folder Then just type mongo.exe and press enter to start the shell
Or you can supply the full path to mongo.exe from any folder to start the shell:
c:\MongoDB\bin\mongo.exe
Then if you have multiple databases, you can do enter command >use <database_name>
to use that db
Let me know if it helps or have issues
You have problems with iOS 4.2? Use this Code:
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd.MM.YY HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(@"%@",dateString);
-->20.01.2011 10:36:02
run this
// you'll see that it prints Object
console.log(typeof document.location);
you want document.location.toString()
or document.location.href
close():- Suppose you have opened multiple browser windows with same driver instance, now calling close() on the driver instance will close the current window the driver instance is pointed to. But the driver instance still remain in memory and can be used to handle other open browser windows.
quit():- If you call quit() on the driver instance and there are one or more browser windows open, it will close all the open browser windows and the driver instance is garbage collected i.e. removed from the memory. So now you cannot use this driver instance to do other operation after calling quit() on it. If you do it will throw an Exception.
dispose():- I don't think there is a dispose method for a WebDriver instance.
You can go to the this selenium official java doc link for reference.
If looking for a unique list while grouping multiple columns this could probably help:
df.groupby('a').agg(lambda x: list(set(x))).reset_index()
In Java, you can escape quotes with \
:
String value = " \"ROM\" ";
if (StartDate < EndDate)
// code
if you just want the dates, and not the time
if (StartDate.Date < EndDate.Date)
// code
You can use the eq method or selector:
$('ul').find('li').eq(index).css({'background-color':'#343434'});
<input type="text" value="Your value">
Use the value
attribute for the pre filled in values.
Or you could just use this to find out if it is NOT a decimal:
string.indexOf(".") == -1;
You can try using FormulaLocal property instead of Formula. Then the semicolon should work.
log4j.rootLogger=OFF
I know an answer has already been accepted for this problem but someone asked in the comments if there was a solution that could be done outside the web.config. I had a ListView producing the exact same error and setting EnableViewState to false resolved this problem for me.
The following statement causes a user's password to expire:
ALTER USER user PASSWORD EXPIRE;
If you cause a database user's password to expire with PASSWORD EXPIRE, then the user (or the DBA) must change the password before attempting to log in to the database following the expiration. Tools such as SQL*Plus allow the user to change the password on the first attempted login following the expiration.
ALTER USER scott IDENTIFIED BY password;
Will set/reset the users password.
See the alter user doc for more info
will this work for macros using .Formula = "=THEFORMULAFUNCTION("STUFF")"
so it would be like:
will this work for macros using .Formula = "=THEFORMULAFUNCTION(CHAR(34) & STUFF & CHAR(34))"
You do not embed the images in the bundle. They are called through the browser. So its;
var imgSrc = './image/image1.jpg';
return <img src={imgSrc} />
There's a drop down just above the code window:
It's called Navigation bar and contains three drop downs: first drop down contains project, second type and third members (methods).
You can use the shortcut Ctrl + F2 (move focus to the project drop down) and press Tab twice (move focus to the third drop down) to focus it, down arrow will expand the list.
$ npm config delete prefix
$ npm config set prefix $NVM_DIR/versions/node/v6.11.1
Note: Change the version number with the one indicated in the error message.
nvm is not compatible with the npm config "prefix" option: currently set to "/usr/local" Run "npm config delete prefix" or "nvm use --delete-prefix v6.11.1 --silent" to unset it.
Credits to @gabfiocchi on Github - "You need to overwrite nvm prefix"
I want to collaborate a little with the solution for the server side. So, the server is saying it does not support DSA, this is because the openssh client does not activate it by default:
OpenSSH 7.0 and greater similarly disable the ssh-dss (DSA) public key algorithm. It too is weak and we recommend against its use.
So, to fix this this in the server side I should activate other Key algorithms like RSA o ECDSA. I just had this problem with a server in a lan. I suggest the following:
Update the openssh:
yum update openssh-server
Merge new configurations in the sshd_config if there is a sshd_config.rpmnew.
Verify there are hosts keys at /etc/ssh/. If not generate new ones, see man ssh-keygen
.
$ ll /etc/ssh/
total 580
-rw-r--r--. 1 root root 553185 Mar 3 2017 moduli
-rw-r--r--. 1 root root 1874 Mar 3 2017 ssh_config
drwxr-xr-x. 2 root root 4096 Apr 17 17:56 ssh_config.d
-rw-------. 1 root root 3887 Mar 3 2017 sshd_config
-rw-r-----. 1 root ssh_keys 227 Aug 30 15:33 ssh_host_ecdsa_key
-rw-r--r--. 1 root root 162 Aug 30 15:33 ssh_host_ecdsa_key.pub
-rw-r-----. 1 root ssh_keys 387 Aug 30 15:33 ssh_host_ed25519_key
-rw-r--r--. 1 root root 82 Aug 30 15:33 ssh_host_ed25519_key.pub
-rw-r-----. 1 root ssh_keys 1675 Aug 30 15:33 ssh_host_rsa_key
-rw-r--r--. 1 root root 382 Aug 30 15:33 ssh_host_rsa_key.pub
Verify in the /etc/ssh/sshd_config the HostKey configuration. It should allow the configuration of RSA and ECDSA. (If all of them are commented by default it will allow too the RSA, see in man sshd_config
the part of HostKey).
# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
For the client side, create a key for ssh (not a DSA like in the question) by just doing this:
ssh-keygen
After this, because there are more options than ssh-dss(DSA) the client openssh (>=v7) should connect with RSA or better algorithm.
This is my first question answered, I welcome suggestions :D .
Try to understand both by this example.
Suppose if you're buying a car from showroom.
The first thing you will check the car contains are for example if it's four tires, a staring, headlight, or all other basic things. This is called smoke testing.
If you're checking how much mileage the car is giving or what is max speed, then this is known as sanity testing.
I had the same error when running
npm start
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
I broke my head on several tabs and applying Solutions from other devs and nothing.
Until, even using Ubuntu, I closed my vscode and restarted my pc and all my problems were solved. (kkkk zueira) just this one.
maybe problem with margin?
width:auto;
padding: 0px;
margin: 0px
My problem has gone after I added this:
<system.webServer>
<security>
<requestFiltering>
<requestLimits
maxAllowedContentLength="104857600"
/>
</requestFiltering>
</security>
</system.webServer>
http://java.sun.com/docs/books/tutorial/jndi/ldap/auth_mechs.html
SASL mechanism supports Kerberos v4 and v5. http://java.sun.com/docs/books/tutorial/jndi/ldap/sasl.html
change the input boxes like
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
and js code as
function showMe (box) {
var chboxs = document.getElementsByName("c1");
var vis = "none";
for(var i=0;i<chboxs.length;i++) {
if(chboxs[i].checked){
vis = "block";
break;
}
}
document.getElementById(box).style.display = vis;
}
here is a demo fiddle
Check ASUI dialog which create at runtime. There is no need of hide and show logic. Simply service will create a component at runtime using AOT ASUI NPM
You can get country from IP address with this location API
Code
echo file_get_contents('https://ipapi.co/8.8.8.8/country/');
Response
US
Here's a fiddle. Response is text
when you query a specific field e.g. country
here. No decoding needed, just plug it into your code.
P.S. If you want all the fields e.g. https://ipapi.co/8.8.8.8/json/
, the response is JSON
.
You can use socket.io rooms. From the client side emit an event ("join" in this case, can be anything) with any unique identifier (email, id).
Client Side:
var socket = io.connect('http://localhost');
socket.emit('join', {email: [email protected]});
Now, from the server side use that information to create an unique room for that user
Server Side:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.on('join', function (data) {
socket.join(data.email); // We are using room of socket io
});
});
So, now every user has joined a room named after user's email. So if you want to send a specific user a message you just have to
Server Side:
io.sockets.in('[email protected]').emit('new_msg', {msg: 'hello'});
The last thing left to do on the client side is listen to the "new_msg" event.
Client Side:
socket.on("new_msg", function(data) {
alert(data.msg);
}
I hope you get the idea.
First of, please think long and hard if you really want to disable the Home
button or any other button for that matter (e.g. the Back
button), this is not something that should be done (at least most of the times, this is a bad design). I can speak only for myself, but if I downloaded an app that doesn't let me do something like clicking an OS button, the next thing I do is uninstall that app and leave a very bad review. I also believe that your app will not be featured on the App Store.
Now...
Notice that MX Player
is asking permission to draw on top of other applications:
Since you cannot override the Home
button on Android
device (at least no in the latest OS versions). MX Player
draws itself on top of your launcher when you "lock" the app and clicks on the Home
button.
To see an example of that is a bit more simple and straight forward to understand, you can see the Facebook Messenger App.
As I was asked to provide some more info about MX Player Status Bar
and Navigation Bar
"overriding", I'm editing my answer to include these topics too.
First thing first, MX Player is using Immersive Full-Screen Mode (DevBytes Video) on KitKat
.
Android 4.4 (API Level 19) introduces a new SYSTEM_UI_FLAG_IMMERSIVE flag for setSystemUiVisibility() that lets your app go truly "full screen." This flag, when combined with the SYSTEM_UI_FLAG_HIDE_NAVIGATION and SYSTEM_UI_FLAG_FULLSCREEN flags, hides the navigation and status bars and lets your app capture all touch events on the screen.
When immersive full-screen mode is enabled, your activity continues to receive all touch events. The user can reveal the system bars with an inward swipe along the region where the system bars normally appear. This clears the SYSTEM_UI_FLAG_HIDE_NAVIGATION flag (and the SYSTEM_UI_FLAG_FULLSCREEN flag, if applied) so the system bars become visible. This also triggers your View.OnSystemUiVisibilityChangeListener, if set. However, if you'd like the system bars to automatically hide again after a few moments, you can instead use the SYSTEM_UI_FLAG_IMMERSIVE_STICKY flag. Note that the "sticky" version of the flag doesn't trigger any listeners, as system bars temporarily shown in this mode are in a transient state.
Second: Hiding the Status Bar
Third: Hiding the Navigation Bar
Please note that although using immersive full screen is only for KitKat
, hiding the Status Bar
and Navigation Bar
is not only for KitKat
.
I don't have much to say about the 2nd and 3rd, You get the idea I believe, it's a fast read in any case. Just make sure you pay close attention to View.OnSystemUiVisibilityChangeListener.
I added a Gist that explains what I meant, it's not complete and needs some fixing but you'll get the idea. https://gist.github.com/Epsiloni/8303531
Good luck implementing this, and have fun!
This should answer that question, and then some.
The second line, if (obj.GetType() == typeof(ClassA)) {}
, is faster, for those that don't want to read the article.
(Be aware that they don't do the same thing)
Using C# 6.0 (which allows expression bodied functions and null propagation), for LINQ to Objects, it can be done in a single line like this (also checking for null):
public static bool ContainsInsensitive(this string str, string value) => str?.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0;
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\Users\NOLA BOOTHE\My Documents\operating system"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
Wscript.Echo objFile.Name
Next
One workaround that I have done is:
Ctrl
+ a
to select everything in the slideCtrl
+ c
to copy itCtrl
+ v
to paste all the vectors/text into the imageIt looks pretty much exactly the same as in Powerpoint, and the vectors/text are very clean with their transparency edges.
I had the same problem and I solved it like this, by taking the original data frame without row names and adding them later
SFIo <- as.matrix(apply(SFI[,-1],2,as.numeric))
row.names(SFIo) <- SFI[,1]
The method that you want to run must be a ThreadStart
Delegate. Please consult the Thread
documentation on MSDN. Note that you can sort of create your two-parameter start with a closure. Something like:
var t = new Thread(() => Startup(port, path));
Note that you may want to revisit your method accessibility. If I saw a class starting a thread on its own public method in this manner, I'd be a little surprised.
To add to this - it seems important to define the width & height of the drawable as per this post:
(his code works)
Working Demo Reading more Info
parseInt(x)
it will cast it into integer
x = parseInt(x);
x = parseInt(x,10); //the radix is 10 (decimal)
parseFloat(x)
it will cast it into float
Working Demo Reading more Info
x = parseFloat(x);
you can directly use prompt
var x = parseInt(prompt("Enter a Number", "1"), 10)
I've created a library that uses multipart uploads in the background to avoid buffering everything in memory and also doesn't write to disk: https://github.com/alexmojaki/s3-stream-upload
Python's csv module handles data row-wise, which is the usual way of looking at such data. You seem to want a column-wise approach. Here's one way of doing it.
Assuming your file is named myclone.csv
and contains
workers,constant,age
w0,7.334,-1.406
w1,5.235,-4.936
w2,3.2225,-1.478
w3,0,0
this code should give you an idea or two:
>>> import csv
>>> f = open('myclone.csv', 'rb')
>>> reader = csv.reader(f)
>>> headers = next(reader, None)
>>> headers
['workers', 'constant', 'age']
>>> column = {}
>>> for h in headers:
... column[h] = []
...
>>> column
{'workers': [], 'constant': [], 'age': []}
>>> for row in reader:
... for h, v in zip(headers, row):
... column[h].append(v)
...
>>> column
{'workers': ['w0', 'w1', 'w2', 'w3'], 'constant': ['7.334', '5.235', '3.2225', '0'], 'age': ['-1.406', '-4.936', '-1.478', '0']}
>>> column['workers']
['w0', 'w1', 'w2', 'w3']
>>> column['constant']
['7.334', '5.235', '3.2225', '0']
>>> column['age']
['-1.406', '-4.936', '-1.478', '0']
>>>
To get your numeric values into floats, add this
converters = [str.strip] + [float] * (len(headers) - 1)
up front, and do this
for h, v, conv in zip(headers, row, converters):
column[h].append(conv(v))
for each row instead of the similar two lines above.
Here is an equivalent optional declaration in Swift:
var middleName: String?
This declaration creates a variable named middleName of type String. The question mark (?) after the String variable type indicates that the middleName variable can contain a value that can either be a String or nil. Anyone looking at this code immediately knows that middleName can be nil. It's self-documenting!
If you don't specify an initial value for an optional constant or variable (as shown above) the value is automatically set to nil for you. If you prefer, you can explicitly set the initial value to nil:
var middleName: String? = nil
for more detail for optional read below link
http://www.iphonelife.com/blog/31369/swift-101-working-swifts-new-optional-values
You can use an HTTP Handler (.ashx) to download a file, like this:
DownloadFile.ashx:
public class DownloadFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition",
"attachment; filename=" + fileName + ";");
response.TransmitFile(Server.MapPath("FileDownload.csv"));
response.Flush();
response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Then you can call the HTTP Handler from the button click event handler, like this:
Markup:
<asp:Button ID="btnDownload" runat="server" Text="Download File"
OnClick="btnDownload_Click"/>
Code-Behind:
protected void btnDownload_Click(object sender, EventArgs e)
{
Response.Redirect("PathToHttpHandler/DownloadFile.ashx");
}
Passing a parameter to the HTTP Handler:
You can simply append a query string variable to the Response.Redirect()
, like this:
Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");
Then in the actual handler code you can use the Request
object in the HttpContext
to grab the query string variable value, like this:
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];
// Use the yourVariableValue here
Note - it is common to pass a filename as a query string parameter to suggest to the user what the file actually is, in which case they can override that name value with Save As...
If X
and beta
do not have the same shape as the second term in the rhs of your last line (i.e. nsample
), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the numpy broadcasting rules.
I was recently having trouble with this same thing and I found a really simple solution.
All you have to do is set the first option to disabled and selected. Like this:
<select id="select">_x000D_
<option disabled="disabled" selected="selected">select one option</option>_x000D_
<option>one</option>_x000D_
<option>two</option>_x000D_
<option>three</option>_x000D_
<option>four</option>_x000D_
<option>five</option>_x000D_
</select>
_x000D_
This will display the first option (grayed out) when the page is loaded. It also prevents the user from being able to select it once they click on the list.
It depends. If the main code is protected by an if
as in:
if __name__ == '__main__':
...main code...
then no, you can't make Python execute that because you can't influence the automatic variable __name__
.
But when all the code is in a function, then might be able to. Try
import myModule
myModule.main()
This works even when the module protects itself with a __all__
.
from myModule import *
might not make main
visible to you, so you really need to import the module itself.
It is important to read the HTML specifications to truly understand what behavior is to be expected:
The HTML5 spec explicitly states what happens in implicit submissions
:
A form element's default button is the first submit button in tree order whose form owner is that form element.
If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.
This was not made explicit in the HTML4 spec, however browsers have already been implementing what is described in the HTML5 spec (which is why it's included explicitly).
Edit to add:
The simplest answer I can think of is to put your submit button as the first [type="submit"]
item in the form, add padding to the bottom of the form with css, and absolutely position the submit button at the bottom where you'd like it.
Regex is not on the list of search features, and it was on (more or less, as Better message search functionality (i.e. Wildcard and partial word search)) the list of pre-canned feature requests, so the answer is "you cannot do this via the Gmail web UI" :-(
There are no current Labs features which offer this. SIEVE filters would be another way to do this, that too was not supported, there seems to no longer be any definitive statement on SIEVE support in the Gmail help.
Updated for link rot The pre-canned list of feature requests was, er canned, the original is on archive.org dated 2012, now you just get redirected to a dumbed down page telling you how to give feedback. Lack of SIEVE support was covered in answer 78761 Does Gmail support all IMAP features?, since some time in 2015 that answer silently redirects to the answer about IMAP client configuration, archive.org has a copy dated 2014.
With the current search facility brackets of any form () {} []
are used for grouping, they have no observable effect if there's just one term within. Using (aaa|bbb)
and [aaa|bbb]
are equivalent and will both find words aaa
or bbb
. Most other punctuation characters, including \
, are treated as a space or a word-separator, +
-
:
and "
do have special meaning though, see the help.
As of 2016, only the form "{term1 term2}
" is documented for this, and is equivalent to the search "term1 OR term2
".
You can do regex searches on your mailbox (within limits) programmatically via Google docs: http://www.labnol.org/internet/advanced-gmail-search/21623/ has source showing how it can be done (copy the document, then Tools > Script Editor
to get the complete source).
You could also do this via IMAP as described here: Python IMAP search for partial subject and script something to move messages to different folder. The IMAP SEARCH verb only supports substrings, not regex (Gmail search is further limited to complete words, not substrings), further processing of the matches to apply a regex would be needed.
For completeness, one last workaround is: Gmail supports plus addressing, if you can change the destination address to [email protected]
it will still be sent to your mailbox where you can filter by recipient address. Make sure to filter using the full email address to:[email protected]
. This is of course more or less the same thing as setting up a dedicated Gmail address for this purpose :-)
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.
just use -
if(!a) // if a is negative,undefined,null,empty value then...
{
// do whatever
}
else {
// do whatever
}
this works because of the == difference from === in javascript, which converts some values to "equal" values in other types to check for equality, as opposed for === which simply checks if the values equal. so basically the == operator know to convert the "", null, undefined to a false value. which is exactly what you need.
Use urllib2 and create a Request object which you then hand to urlopen. http://docs.python.org/library/urllib2.html
I dont really use the "old" urllib anymore.
req = urllib2.Request("http://google.com", None, {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'})
response = urllib2.urlopen(req).read()
untested....
It seems that your problem is simply a concurrency issue. The post function takes a callback argument to tell you when the post has been finished. You cannot make the alert in global scope like this and expect that the post has already been finished. You have to move it to the callback function.
To get the actual scrollable height of the areas scrolled by the window scrollbar, I used $('body').prop('scrollHeight')
. This seems to be the simplest working solution, but I haven't checked extensively for compatibility. Emanuele Del Grande notes on another solution that this probably won't work for IE below 8.
Most of the other solutions work fine for scrollable elements, but this works for the whole window. Notably, I had the same issue as Michael for Ankit's solution, namely, that $(document).prop('scrollHeight')
is returning undefined
.
{
"success": true,
"data": {
"BLR": {
"origin": "JAI",
"destination": "BLR",
"price": 127,
"transfers": 0,
"airline": "LB",
"flight_number": 655,
"departure_at": "2017-06-03T18:20:00Z",
"return_at": "2017-06-07T08:30:00Z",
"expires_at": "2017-03-05T08:40:31Z"
}
}
};
PEP 8 advises the first form for readability. You can find it here.
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
If you are sure you haven't messed the jar, then please clean the project and perform mvn clean install
. This should solve the problem.
My answer is late, but i want to add some information that is missed in all above answers.
1) If you want to select single value in chosen select.
$('#select-id').val("22").trigger('chosen:updated');
2) If you are using multiple chosen select, then may you need to set multiple values at single time.
$('#documents').val(["22", "25", "27"]).trigger('chosen:updated');
Information gathered from following links:
1) Chosen Docs
2) Chosen Github Discussion
To expand a little more, there are two kinds of constructors: instance initializers (.ctor), type initializers (.cctor). Build the code below, and explore the IL code in ildasm.exe. You will notice that the static field 'b' will be initialized through .cctor() whereas the instance field will be initialized through .ctor()
internal sealed class CtorExplorer
{
protected int a = 0;
protected static int b = 0;
}
Suggesting an alternative answer here:
Making a separate module for the Pipe is not required, but is definitely an alternative. Check the official docs footnote: https://angular.io/guide/pipes#custom-pipes
You use your custom pipe the same way you use built-in pipes.
You must include your pipe in the declarations array of the AppModule . If you choose to inject your pipe into a class, you must provide it in the providers array of your NgModule.
All you have to do is add your pipe to the declarations array, and the providers array in the module
where you want to use the Pipe.
declarations: [
...
CustomPipe,
...
],
providers: [
...
CustomPipe,
...
]
Being curious but still unable to find the answer to the performance topic of the question above, I wrote this gist for nodejs to test both the performance and reliability of all presented (and scored) solutions.
I've compared the wall times of a clone function creation and the execution of a clone. The results together with assertion errors are included in the gist's comment.
Plus my two cents (based on the author's suggestion):
clone0 cent (faster but uglier):
Function.prototype.clone = function() {
var newfun;
eval('newfun=' + this.toString());
for (var key in this)
newfun[key] = this[key];
return newfun;
};
clone4 cent (slower but for those who dislike eval() for purposes known only to them and their ancestors):
Function.prototype.clone = function() {
var newfun = new Function('return ' + this.toString())();
for (var key in this)
newfun[key] = this[key];
return newfun;
};
As for the performance, if eval/new Function is slower than wrapper solution (and it really depends on the function body size), it gives you bare function clone (and I mean the true shallow clone with properties but unshared state) without unnecessary fuzz with hidden properties, wrapper functions and problems with stack.
Plus there is always one important factor you need to take into consideration: the less code, the less places for mistakes.
The downside of using the eval/new Function is that the clone and the original function will operate in different scopes. It won't work well with functions that are using scoped variables. The solutions using bind-like wrapping are scope independent.
As many have already answered, mounting host volumes during the build is not possible. I just would like to add docker-compose
way, I think it'll be nice to have, mostly for development/testing usage
Dockerfile
FROM node:10
WORKDIR /app
COPY . .
RUN npm ci
CMD sleep 999999999
docker-compose.yml
version: '3'
services:
test-service:
image: test/image
build:
context: .
dockerfile: Dockerfile
container_name: test
volumes:
- ./export:/app/export
- ./build:/app/build
And run your container by docker-compose up -d --build
An alternative to using classes to mark the state of an element is the internal data store functionality.
P.S.: You are able to store booleans and whatever you desire using the data()
function. It's not just about strings :)
$("...").mouseover(function ()
{
// store state on element
}).mouseout(function ()
{
// remove stored state on element
});
And then it's just a matter of accessing the state of elements.
Here, I have coded using single loop. We are getting mode from a[j-1] because localCount was recently updated when j was j-1. Also N is size of the array & counts are initialized to 0.
//After sorting the array
i = 0,j=0;
while(i!=N && j!=N){
if(ar[i] == ar[j]){
localCount++;
j++;
}
else{
i++;
localCount = 0;
}
if(localCount > globalCount){
globalCount = localCount;
mode = ar[j-1];
}
}
Following on from the examples already given, I'd say, it's best practice to also wrap the response in a using like this
public bool IsValidUrl(string url)
{
try
{
var request = WebRequest.Create(url);
request.Timeout = 5000;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
response.Close();
return response.StatusCode == HttpStatusCode.OK;
}
}
catch (Exception exception)
{
return false;
}
}
If your markup is bound to a controller, directive or anything else with a $scope:
console.log($scope.movie);
Extending the Quote idea for Objective-C:
#define NSStringMultiline(...) [[NSString alloc] initWithCString:#__VA_ARGS__ encoding:NSUTF8StringEncoding]
NSString *sql = NSStringMultiline(
SELECT name, age
FROM users
WHERE loggedin = true
);
In order to not have the Cannot recover key
exception, I had to apply the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files to the installation of Java that was running my application. Version 8 of those files can be found here or the latest version should be listed on this page. The download includes a file that explains how to apply the policy files.
Since JDK 8u151 it isn't necessary to add policy files. Instead the JCE jurisdiction policy files are controlled by a Security property called crypto.policy
. Setting that to unlimited
with allow unlimited cryptography to be used by the JDK. As the release notes linked to above state, it can be set by Security.setProperty()
or via the java.security
file. The java.security
file could also be appended to by adding -Djava.security.properties=my_security.properties
to the command to start the program as detailed here.
Since JDK 8u161 unlimited cryptography is enabled by default.
You can have as many branches you want, just as a regular git repository, but according to heroku docs, any branch other than master
will be ignored.
http://devcenter.heroku.com/articles/git
Branches pushed to Heroku other than master will be ignored. If you’re working out of another branch locally, you can either merge to master before pushing, or specify that you want to push your local branch to a remote master.
This means that you can push anything you want, but you app at heroku will always point to the master branch.
But, if you question regards how to create branches and to work with git you should check this other question
Add one more simple solution
$(function() {
$('.monthYearPicker').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'M yy'
}).focus(function() {
var thisCalendar = $(this);
$('.ui-datepicker-calendar').detach();
$('.ui-datepicker-close').click(function() {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
thisCalendar.datepicker('setDate', new Date(year, month, 1));
});
});
});
http://jsfiddle.net/tmnasim/JLydp/
Features:
Via Google's webfontloader
var fontDownloadCount = 0;
WebFont.load({
custom: {
families: ['fontfamily1', 'fontfamily2']
},
fontinactive: function() {
fontDownloadCount++;
if (fontDownloadCount == 2) {
// all fonts have been loaded and now you can do what you want
}
}
});
My usual trick is to simply print sys.path
in the actual context where the import problem happens. In your case it'd seem that the place for the print is in /home/hughdbrown/.local/bin/pserve
. Then check dirs & files in the places that path shows..
You do that by first having:
import sys
and in python 2 with print expression:
print sys.path
or in python 3 with the print function:
print(sys.path)
If you want to get an ID of an element, let's say by a class selector, when an event (in this case click event) was fired on that specific element, then the following will do the job:
$('.your-selector').click(function(){
var id = $(this).attr('id');
});
You can use prop() for this, as Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop()
method provides a way to explicitly retrieve property values, while .attr()
retrieves attributes.
var prop=false;
if(value == 1) {
prop=true;
}
$('#checkbox').prop('checked',prop);
or simply,
$('#checkbox').prop('checked',(value == 1));
Snippet
$(document).ready(function() {_x000D_
var chkbox = $('.customcheckbox');_x000D_
$(".customvalue").keyup(function() {_x000D_
chkbox.prop('checked', this.value==1);_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h4>This is a domo to show check box is checked_x000D_
if you enter value 1 else check box will be unchecked </h4>_x000D_
Enter a value:_x000D_
<input type="text" value="" class="customvalue">_x000D_
<br>checkbox output :_x000D_
<input type="checkbox" class="customcheckbox">
_x000D_
You can delete using cURL
or visually using one of the many tools that open source enthusiasts have created for Elasticsearch.
Using cURL
curl -XDELETE localhost:9200/index/type/documentID
e.g.
curl -XDELETE localhost:9200/shop/product/1
You will then receive a reply as to whether this was successful or not. You can delete an entire index or types with an index also, you can delete a type by leaving out the document ID like so -
curl -XDELETE localhost:9200/shop/product
If you wish to delete an index -
curl -XDELETE localhost:9200/shop
If you wish to delete more than one index that follows a certain naming convention (note the *
, a wildcard), -
curl -XDELETE localhost:9200/.mar*
Visually
There are various tools as mentioned above, I wont list them here but I will link you to one which enables you to get started straight away, located here. This tool is called KOPF, to connect to your host please click on the logo on top left hand corner and enter the URL of your cluster.
Once connected you will be able to administer your entire cluster, delete, optimise and tune your cluster.
Sounds like mssql jdbc is buffering the entire resultset for you. You can add a connect string parameter saying selectMode=cursor or responseBuffering=adaptive. If you are on version 2.0+ of the 2005 mssql jdbc driver then response buffering should default to adaptive.
In Reactjs, virtual DOM is used to render browser code in Reactjs while in React Native, native APIs are used to render components in mobile.
The apps developed with Reactjs renders HTML in UI while React Native uses JSX for rendering UI, which is nothing but javascript.
Because the SCHEDULER_ADMIN role is a powerful role allowing a grantee to execute code as any user, you should consider granting individual Scheduler system privileges instead. Object and system privileges are granted using regular SQL grant syntax. An example is if the database administrator issues the following statement:
GRANT CREATE JOB TO scott;
After this statement is executed, scott can create jobs, schedules, or programs in his schema.
copied from http://docs.oracle.com/cd/B19306_01/server.102/b14231/schedadmin.htm#i1006239
You could do the following:
var inputType = $('#inputid').attr('type');
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
In .Net 4.5+ use WebUtility
Just for formatting I'm submitting this as an answer.
Couldn't find any good examples comparing them so:
string testString = "http://test# space 123/text?var=val&another=two";
Console.WriteLine("UrlEncode: " + System.Web.HttpUtility.UrlEncode(testString));
Console.WriteLine("EscapeUriString: " + Uri.EscapeUriString(testString));
Console.WriteLine("EscapeDataString: " + Uri.EscapeDataString(testString));
Console.WriteLine("EscapeDataReplace: " + Uri.EscapeDataString(testString).Replace("%20", "+"));
Console.WriteLine("HtmlEncode: " + System.Web.HttpUtility.HtmlEncode(testString));
Console.WriteLine("UrlPathEncode: " + System.Web.HttpUtility.UrlPathEncode(testString));
//.Net 4.0+
Console.WriteLine("WebUtility.HtmlEncode: " + WebUtility.HtmlEncode(testString));
//.Net 4.5+
Console.WriteLine("WebUtility.UrlEncode: " + WebUtility.UrlEncode(testString));
Outputs:
UrlEncode: http%3a%2f%2ftest%23+space+123%2ftext%3fvar%3dval%26another%3dtwo
EscapeUriString: http://test#%20space%20123/text?var=val&another=two
EscapeDataString: http%3A%2F%2Ftest%23%20space%20123%2Ftext%3Fvar%3Dval%26another%3Dtwo
EscapeDataReplace: http%3A%2F%2Ftest%23+space+123%2Ftext%3Fvar%3Dval%26another%3Dtwo
HtmlEncode: http://test# space 123/text?var=val&another=two
UrlPathEncode: http://test#%20space%20123/text?var=val&another=two
//.Net 4.0+
WebUtility.HtmlEncode: http://test# space 123/text?var=val&another=two
//.Net 4.5+
WebUtility.UrlEncode: http%3A%2F%2Ftest%23+space+123%2Ftext%3Fvar%3Dval%26another%3Dtwo
In .Net 4.5+ use WebUtility
.UrlEncode
This appears to replicate HttpUtility.UrlEncode
(pre-v4.0) for the more common characters:
Uri.EscapeDataString(testString).Replace("%20", "+").Replace("'", "%27").Replace("~", "%7E")
Note: EscapeUriString
will keep a valid uri string, which causes it to use as many plaintext characters as possible.
See this answer for a Table Comparing the various Encodings:
https://stackoverflow.com/a/11236038/555798
Line Breaks
All of them listed here (other than HttpUtility.HtmlEncode
) will convert "\n\r"
into %0a%0d
or %0A%0D
Please feel free to edit this and add new characters to my test string, or leave them in the comments and I'll edit it.
Note: All of the following instructions apply universally (aka to all OSes) unless otherwise specified.
You will need:
Change the file extension of the .apk
file by either adding a .zip
extension to the filename, or to change .apk
to .zip
.
For example, com.example.apk
becomes com.example.zip
, or com.example.apk.zip
. Note that on Windows and macOS, it may prompt you whether you are sure you want to change the file extension. Click OK or Add if you're using macOS:
Extract the renamed APK file in a specific folder. For example, let that folder be demofolder
.
If it didn't work, try opening the file in another application such as WinZip or 7-Zip.
For macOS, you can try running unzip
in Terminal (available at /Applications/Terminal.app
), where it takes one or more arguments: the file to unzip + optional arguments. See man unzip
for documentation and arguments.
Download dex2jar
(see all releases on GitHub) and extract that zip file in the same folder as stated in the previous point.
Open command prompt (or a terminal) and change your current directory to the folder created in the previous point and type the command d2j-dex2jar.bat classes.dex
and press enter. This will generate classes-dex2jar.jar
file in the same folder.
d2j-dex2jar.bat
with d2j-dex2jar.sh
. In other words, run d2j-jar2dex.sh classes.dex
in the terminal and press enter.Download Java Decompiler (see all releases on Github) and extract it and start (aka double click) the executable/application.
From the JD-GUI window, either drag and drop the generated classes-dex2jar.jar
file into it, or go to File > Open File...
and browse for the jar.
Next, in the menu, go to File > Save All Sources
(Windows: Ctrl+Alt+S, macOS: ?+?+S). This should open a dialog asking you where to save a zip file named `classes-dex2jar.jar.src.zip" consisting of all packages and java files. (You can rename the zip file to be saved)
Extract that zip file (classes-dex2jar.jar.src.zip
) and you should get all java files of the application.
xml
files from APKapktool
website for installation instructions and moreWindows:
myxmlfolder
).myxmlfolder
folder and rename the apktool jar file to apktool.jar
..apk
file in the same folder (i.e myxmlfolder
).Open the command prompt (or terminal) and change your current directory to the folder where apktool
is stored (in this case, myxmlfolder
). Next, type the command apktool if framework-res.apk
.
What we're doing here is that we are installing a framework. For more info, see the docs.
In the command prompt, type the command apktool d filename.apk
(where filename
is the name of apk file). This should decode the file. For more info, see the docs.
This should result in a folder filename.out
being outputted, where filename
is the original name of the apk file without the .apk
file extension. In this folder are all the XML files such as layout, drawables etc.
Source: How to get source code from APK file - Comptech Blogspot
In my case it was simple as using the Bind() method on the Configuration object. And then add the object as singleton in the DI.
var instructionSettings = new InstructionSettings();
Configuration.Bind("InstructionSettings", instructionSettings);
services.AddSingleton(typeof(IInstructionSettings), (serviceProvider) => instructionSettings);
The Instruction object can be as complex as you want.
{
"InstructionSettings": {
"Header": "uat_TEST",
"SVSCode": "FICA",
"CallBackUrl": "https://UATEnviro.companyName.co.za/suite/webapi/receiveCallback",
"Username": "s_integrat",
"Password": "X@nkmail6",
"Defaults": {
"Language": "ENG",
"ContactDetails":{
"StreetNumber": "9",
"StreetName": "Nano Drive",
"City": "Johannesburg",
"Suburb": "Sandton",
"Province": "Gauteng",
"PostCode": "2196",
"Email": "[email protected]",
"CellNumber": "0833 468 378",
"HomeNumber": "0833 468 378",
}
"CountryOfBirth": "710"
}
}
You might want to modify your jQuery code a bit to '#demolist li a'
so it specifically selects the text that is in the link rather than the text that is in the li element. That would allow you to have a sub-menu without causing issues. Also since your are specifically selecting the a tag you can access it with $(this).text();
.
$('#datebox li a').on('click', function(){
//$('#datebox').val($(this).text());
alert($(this).text());
});
For those who are stuck maintaining old .net, here is one that works in .net framework 2.x:
Dim lstOfStrings As New List(of String)( new String(){"v1","v2","v3"} )
You mean InputBox? Just look in the Microsoft.VisualBasic namespace.
C# and VB.Net share a common library. If one language can use it, so can the other.
I´m in Brazil. Because of the regional details sometimes the city cames in differents ways. I think its the same in India and other countries. So, to prevent errors I make this verification:
private fun getAddress(latLng: LatLng): String {
// 1
val geocoder = Geocoder(this)
val addresses: List<Address>?
var city = "no"
try {
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)
if (null != addresses && !addresses.isEmpty()) { //prevent from error
//sometimes the city comes in locality, sometimes in subAdminArea.
if (addresses[0].locality == null) {
city = addresses[0].subAdminArea
} else {
city = addresses[0].locality
}
}
} catch (e: IOException) {
Log.e("MapsActivity", e.localizedMessage)
}
return city
}
You can also check if city returns "no". If so, wasn´t possible to get the user location. Hope it helps.
Did you check
console.table(yourArray);
More infos here: https://developer.mozilla.org/en-US/docs/Web/API/Console/table
A quite decent implementation of the find
command for Git repositories can be found here:
In .NET5, I used DisplayTextFor without needing helper or extension methods:
@Html.DisplayTextFor(m => m.SomeEnumProperty)
Where SomeEnumProperty
has a value of:
public enum MyEnum
{
[Display(Name = "Not started")]
NotStarted = 0,
[Display(Name = "Weird display name instead of just 'Started'")]
Started = 1,
}
I try to avoid floating elements unless the design really needs it. Because you have floated the <li>
they are out of normal flow.
If you add .navigation { text-align:center; }
and change .navigation li { float: left; }
to .navigation li { display: inline-block; }
then entire navigation will be centred.
One caveat to this approach is that display: inline-block;
is not supported in IE6 and needs a workaround to make it work in IE7.
.jar isn't executable. Instantiate classes or make call to any static method.
EDIT: Add Main-Class entry while creating a JAR.
>p.mf (content of p.mf)
Main-Class: pk.Test
>Test.java
package pk;
public class Test{
public static void main(String []args){
System.out.println("Hello from Test");
}
}
Use Process class and it's methods,
public class Exec
{
public static void main(String []args) throws Exception
{
Process ps=Runtime.getRuntime().exec(new String[]{"java","-jar","A.jar"});
ps.waitFor();
java.io.InputStream is=ps.getInputStream();
byte b[]=new byte[is.available()];
is.read(b,0,b.length);
System.out.println(new String(b));
}
}
I found I way to flip only the background not whole element after seeing a clue to flip in Alex's answer. Thanks alex for your answer
HTML
<div class="prev"><a href="">Previous</a></div>
<div class="next"><a href="">Next</a></div>
CSS
.next a, .prev a {
width:200px;
background:#fff
}
.next {
float:left
}
.prev {
float:right
}
.prev a:before, .next a:before {
content:"";
width:16px;
height:16px;
margin:0 5px 0 0;
background:url(http://i.stack.imgur.com/ah0iN.png) no-repeat 0 0;
display:inline-block
}
.next a:before {
margin:0 0 0 5px;
transform:scaleX(-1);
}
See example here http://jsfiddle.net/qngrf/807/
Just do a require('./yourfile.js');
Declare all the variables that you want outside access as global variables. So instead of
var a = "hello"
it will be
GLOBAL.a="hello"
or just
a = "hello"
This is obviously bad. You don't want to be polluting the global scope.
Instead the suggest method is to export
your functions/variables.
If you want the MVC pattern take a look at Geddy.
var max_date = dates.sort(function(d1, d2){
return d2-d1;
})[0];
From the Google Font Directory examples:
@font-face {
font-family: 'Tangerine';
font-style: normal;
font-weight: normal;
src: local('Tangerine'), url('http://example.com/tangerine.ttf') format('truetype');
}
body {
font-family: 'Tangerine', serif;
font-size: 48px;
}
This works cross browser with .ttf, I believe it may work with .otf. (Wikipedia says .otf is mostly backwards compatible with .ttf) If not, you can convert the .otf to .ttf
Here are some good sites:
Good primer:
Other Info:
You could also write it a little more cleaner using updateOne & $set, plus async/await.
const updateUser = async (newUser) => {
try {
await User.updateOne({ username: oldUsername }, {
$set: {
username: newUser.username,
password: newUser.password,
rights: newUser.rights
}
})
} catch (err) {
console.log(err)
}
}
Since you don't need the resulting document, you can just use updateOne instead of findOneAndUpdate.
Here's a good discussion about the difference: MongoDB 3.2 - Use cases for updateOne over findOneAndUpdate
Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.
Angular 5 Solution:
import {HttpClient} from '@angular/common/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = {} as any; // Set any options you like
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.httpClient.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
Angular 4 Solution:
// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = new RequestOptions();
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.http.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
Programming to an interface has absolutely nothing to do with abstract interfaces like we see in Java or .NET. It isn't even an OOP concept.
What it means is don't go messing around with the internals of an object or data structure. Use the Abstract Program Interface, or API, to interact with your data. In Java or C# that means using public properties and methods instead of raw field access. For C that means using functions instead of raw pointers.
EDIT: And with databases it means using views and stored procedures instead of direct table access.
Assuming you're using WinForms, as it was the first thing I did when I was starting C# you need to create an event to close this form.
Lets say you've got a button called myNewButton. If you double click it on WinForms designer you will create an event. After that you just have to use this.Close
private void myNewButton_Click(object sender, EventArgs e) {
this.Close();
}
And that should be it.
The only reason for this not working is that your Event is detached from button. But it should create new event if old one is no longer attached when you double click on the button in WinForms designer.
I use the vimrc in the python repo among other things:
http://svn.python.org/projects/python/trunk/Misc/Vim/vimrc
I also add
set softtabstop=4
No solution mentioned above was solved my problem. My problem was different.
First check is your port is disabled in firewall.
Go to Control Panel -> Windows Firewall -> Advance Settings -> Inbound Rules
and see any port is blocked.
A sample image is below:
If so then you can unblock the port by following steps:
Step 1:
Here you can see that the port is blocked.
Step 2: Allow the connection -> Apply -> Ok
.
That's solved my blocked problem. Happy coding :) :)
Here is the best and simplest answer. Use try and except calls.
x = randint(1,9)
guess = -1
print "Guess the number below 10:"
while guess != x:
try:
guess = int(raw_input("Guess: "))
if guess < x:
print "Guess higher."
elif guess > x:
print "Guess lower."
else:
print "Correct."
except:
print "You did not put any number."
Another option is an interesting open source project called ScriptCS. It uses some crafty techniques to allow you a development experience outside of Visual Studio while still being able to leverage NuGet to manage your dependencies. It's free, very easy to install using Chocolatey. You can check it out here http://scriptcs.net.
Another cool feature it has is the REPL from the command line. Which allows you to do stuff like this:
C:\> scriptcs
scriptcs (ctrl-c or blank to exit)
> var message = "Hello, world!";
> Console.WriteLine(message);
Hello, world!
>
C:\>
You can create C# utility "scripts" which can be anything from small system tasks, to unit tests, to full on Web APIs. In the latest release I believe they're also allowing for hosting the runtime in your own apps.
Check out it development on the GitHub page too https://github.com/scriptcs/scriptcs
array.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.date) - new Date(a.date);
});
array.sort(function(o1,o2){
if (sort_o1_before_o2) return -1;
else if(sort_o1_after_o2) return 1;
else return 0;
});
Or more tersely:
array.sort(function(o1,o2){
return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0;
});
Define a custom non-enumerable sortBy
function using a Schwartzian transform on all arrays :
(function(){
if (typeof Object.defineProperty === 'function'){
try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){}
}
if (!Array.prototype.sortBy) Array.prototype.sortBy = sb;
function sb(f){
for (var i=this.length;i;){
var o = this[--i];
this[i] = [].concat(f.call(o,o,i),o);
}
this.sort(function(a,b){
for (var i=0,len=a.length;i<len;++i){
if (a[i]!=b[i]) return a[i]<b[i]?-1:1;
}
return 0;
});
for (var i=this.length;i;){
this[--i]=this[i][this[i].length-1];
}
return this;
}
})();
Use it like so:
array.sortBy(function(o){ return o.date });
If your date is not directly comparable, make a comparable date out of it, e.g.
array.sortBy(function(o){ return new Date( o.date ) });
You can also use this to sort by multiple criteria if you return an array of values:
// Sort by date, then score (reversed), then name
array.sortBy(function(o){ return [ o.date, -o.score, o.name ] };
See http://phrogz.net/JS/Array.prototype.sortBy.js for more details.
I have extended the regex given by @Ofir Luzon for the formats dd-mmm-YYYY, dd/mmm/YYYY, dd.mmm.YYYY as per my requirement. Anyone else with same requirement can refer this
^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
and tested for some test cases here http://regexr.com/39tr1.
For better understanding for this Regular expression refer this image:
You still have to wrap it in an ISERROR, but you could use MATCH()
instead of VLOOKUP()
:
Returns the relative position of an item in an array that matches a specified value in a specified order. Use MATCH instead of one of the LOOKUP functions when you need the position of an item in a range instead of the item itself.
Here's a complete example, assuming you're looking for the word "key" in a range of cells:
=IF(ISERROR(MATCH("key",A5:A16,FALSE)),"missing","found")
The FALSE
is necessary to force an exact match, otherwise it will look for the closest value.
If the file contains text data, a technique I use is to put the text into a textarea element and have the user select it (click in textarea then ctrl-A) then copy followed by a paste to a text editor.
Even if your data falls within your specified limits (e.g. c(0, 335)
), adding a geom_jitter()
statement could push some points outside those limits, producing the same error message.
library(ggplot2)
range(mtcars$hp)
#> [1] 52 335
# No jitter -- no error message
ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
scale_y_continuous(limits=c(0,335))
# Jitter is too large -- this generates the error message
ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
geom_jitter(position = position_jitter(w = 0.2, h = 0.2)) +
scale_y_continuous(limits=c(0,335))
#> Warning: Removed 1 rows containing missing values (geom_point).
Created on 2020-08-24 by the reprex package (v0.3.0)
1 - You can set a timeout in your application :
var client = new YourServiceReference.YourServiceClass();
client.Timeout = 60; // or -1 for infinite
It is in milliseconds.
2 - Also you can increase timeout value in httpruntime tag in web/app.config :
<configuration>
<system.web>
<httpRuntime executionTimeout="<<**seconds**>>" />
...
</system.web>
</configuration>
For ASP.NET applications, the Timeout property value should always be less than the executionTimeout attribute of the httpRuntime element in Machine.config. The default value of executionTimeout is 90 seconds. This property determines the time ASP.NET continues to process the request before it returns a timed out error. The value of executionTimeout should be the proxy Timeout, plus processing time for the page, plus buffer time for queues. -- Source
On Windows I kept facing different errors messages when trying to use pg_upgrade
.
Saved a lot of time for me to just:
If you don't mind using a couple libraries it can be done in a single line.
Include Apache Commons IOUtils & json.org libraries.
JSONObject json = new JSONObject(IOUtils.toString(new URL("https://graph.facebook.com/me"), Charset.forName("UTF-8")));
If your arrays are character arrays(which seems to be the case), You need a strcat().
Your destination array should have enough space to accommodate the appended data though.
In C++, You are much better off using std::string and then you can use std::string::append()
use
statusCode: {
404: function() {
alert('page not found');
}
}
-
$.ajax({
type: 'POST',
url: '/controller/action',
data: $form.serialize(),
success: function(data){
alert('horray! 200 status code!');
},
statusCode: {
404: function() {
alert('page not found');
},
400: function() {
alert('bad request');
}
}
});
Have a look at this answer: Encrypt and decrypt with AES and Base64 encoding
To solve the problem, I use this:
Fragment frg = null;
frg = getFragmentManager().findFragmentByTag("Feedback");
final android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
The Date constructor accepts any value. If the primitive [[value]] of the argument is number, then the Date that is created has that value. If primitive [[value]] is String, then the specification only guarantees that the Date constructor and the parse method are capable of parsing the result of Date.prototype.toString and Date.prototype.toUTCString()
A reliable way to set a Date is to construct one and use the setFullYear
and setTime
methods.
An example of that appears here: http://jibbering.com/faq/#parseDate
ECMA-262 r3 does not define any date formats. Passing string values to the Date constructor or Date.parse has implementation-dependent outcome. It is best avoided.
YYYY-MM-DD
can be parsed to a Date
with the following:-
/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* @param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* @return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}
The >
selector matches direct children only, not descendants.
You want
div.test th, td, caption {}
or more likely
div.test th, div.test td, div.test caption {}
Edit:
The first one says
div.test th, /* any <th> underneath a <div class="test"> */
td, /* or any <td> anywhere at all */
caption /* or any <caption> */
Whereas the second says
div.test th, /* any <th> underneath a <div class="test"> */
div.test td, /* or any <td> underneath a <div class="test"> */
div.test caption /* or any <caption> underneath a <div class="test"> */
In your original the div.test > th
says any <th> which is a **direct** child of <div class="test">
, which means it will match <div class="test"><th>this</th></div>
but won't match <div class="test"><table><th>this</th></table></div>
was implemented that in service-now platform. No need to use other library - makepdf have all you need!
that my html part (include preloder gif):
<div class="pdf-preview" ng-init="generatePDF(true)">
<object data="{{c.content}}" type="application/pdf" style="width:58vh;height:88vh;" ng-if="c.content" ></object>
<div ng-if="!c.content">
<img src="https://support.lenovo.com/esv4/images/loading.gif" width="50" height="50">
</div>
</div>
this is client script (js part)
$scope.generatePDF = function (preview) {
docDefinition = {} //you rootine to generate pdf content
//...
if (preview) {
pdfMake.createPdf(docDefinition).getDataUrl(function(dataURL) {
c.content = dataURL;
});
}
}
So on page load I fire init function that generate pdf content and if required preview (set as true) result will be assigned to c.content variable. On html side object will be not shown until c.content will got a value, so that will show loading gif.
__call__
is also used to implement decorator classes in python. In this case the instance of the class is called when the method with the decorator is called.
class EnterExitParam(object):
def __init__(self, p1):
self.p1 = p1
def __call__(self, f):
def new_f():
print("Entering", f.__name__)
print("p1=", self.p1)
f()
print("Leaving", f.__name__)
return new_f
@EnterExitParam("foo bar")
def hello():
print("Hello")
if __name__ == "__main__":
hello()
program output:
Entering hello
p1= foo bar
Hello
Leaving hello
If your are invoking fetch on a localhost server, use non-SSL unless you have a valid certificate for localhost. fetch will fail on an invalid or self signed certificate especially on localhost.
Let us say we have a project social_login. To check the traffic to your repo, you can goto https://github.com//social_login/graphs/traffic
#! /bin/sh
echo "$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
UPD Some explanations
"$1"
dirname "$1"
cd "$(dirname "$1")
into this relative dir and get absolute path for it by running pwd
shell command$(basename "$1")
echo
itdata: {"csrfmiddlewaretoken" : "{{csrf_token}}"}
You see "403 (FORBIDDEN)", because you don`t send "csrfmiddlewaretoken" parameter. In template each form has this: {% csrf_token %}. You should add "csrfmiddlewaretoken" to your ajax data dictionary. My example is sending "product_code" and "csrfmiddlewaretoken" to app "basket" view "remove":
$(function(){
$('.card-body').on('click',function(){
$.ajax({
type: "post",
url: "{% url 'basket:remove'%}",
data: {"product_code": "07316", "csrfmiddlewaretoken" : "{{csrf_token}}" }
});
})
});
It worked for me after adding particular version of node-sass package ([email protected])
Maybe placing the jquery.ui.widget.js
as second after jquery.ui.core.js
.
As of Android 3.0 (API Level 11) Android has a more recent and improved JSON Parser.
http://developer.android.com/reference/android/util/JsonReader.html
Reads a JSON (RFC 4627) encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document. Within JSON objects, name/value pairs are represented by a single token.
If you are reencoding in your ffmpeg command line, that may be the reason why it is CPU intensive. You need to simply copy the streams to the single container. Since I do not have your command line I cannot suggest a specific improvement here. Your acodec and vcodec should be set to copy is all I can say.
EDIT: On seeing your command line and given you have already tried it, this is for the benefit of others who come across the same question. The command:
ffmpeg -i rtsp://@192.168.241.1:62156 -acodec copy -vcodec copy c:/abc.mp4
will not do transcoding and dump the file for you in an mp4. Of course this is assuming the streamed contents are compatible with an mp4 (which in all probability they are).
You can use range with count to check how many times a number appears in the string by checking it against the range:
def count_digit(a):
sum = 0
for i in range(10):
sum += a.count(str(i))
return sum
ans = count_digit("apple3rh5")
print(ans)
#This print 2
(Your question is still unclear on whether your code is calling printStackTrace()
or this is being done by a logging handler.)
Here are some possible explanations about what might be happening:
The logger / handler being used has been configured to only output the exception's message string, not a full stack trace.
Your application (or some third-party library) is logging the exception using LOG.error(ex);
rather than the 2-argument form of (for example) the log4j Logger method.
The message is coming from somewhere different to where you think it is; e.g. it is actually coming some third-party library method, or some random stuff left over from earlier attempts to debug.
The exception that is being logged has overloaded some methods to obscure the stacktrace. If that is the case, the exception won't be a genuine NullPointerException, but will be some custom subtype of NPE or even some unconnected exception.
I think that the last possible explanation is pretty unlikely, but people do at least contemplate doing this kind of thing to "prevent" reverse engineering. Of course it only really succeeds in making life difficult for honest developers.
for (int i = 0; i < list.size(); i++) {
if (i < list.size() - 1) {
if (list.get(i) > list.get(i + 1)) {
int j = list.get(i);
list.remove(i);
list.add(i, list.get(i));
list.remove(i + 1);
list.add(j);
i = -1;
}
}
}
You are more than likely missing $(IncludePath) within Properties->VC++ Directories->Include Directories. Adding this should make iostream and others visible again. You probably deleted it by mistake while setting up your program.
There's a situation where the cell has white space, you can't see it, use
df['col'].replace(' ', np.nan, inplace=True)
to replace white space as NaN, then
df= df.dropna(subset=['col'])
I had that problem too and I solve it by:
$today = date("Ymd");
$expire = str_replace('-', '', $row->expireDate); //from db
if(($today - $expire) > $NUMBER_OF_DAYS)
{
//do something;
}
Based on skube's approach, I found the minimal set of CSS I needed was:
.horizontal-scroll-except-first-column {_x000D_
width: 100%;_x000D_
overflow: auto;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table {_x000D_
margin-left: 8em;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th:first-child,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td:first-child {_x000D_
position: absolute;_x000D_
width: 8em;_x000D_
margin-left: -8em;_x000D_
background: #ccc;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td {_x000D_
/* Without this, if a cell wraps onto two lines, the first column_x000D_
* will look bad, and may need padding. */_x000D_
white-space: nowrap;_x000D_
}
_x000D_
<div class="horizontal-scroll-except-first-column">_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>FIXED</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> <td>66666</td> <td>77777</td> <td>88888</td> <td>99999</td> <td>AAAAA</td> <td>BBBBB</td> <td>CCCCC</td> <td>DDDDD</td> <td>EEEEE</td> <td>FFFFF</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>
_x000D_
This worked for me:
curl -v --cookie "USER_TOKEN=Yes" http://127.0.0.1:5000/
I could see the value in backend using
print request.cookies
Javascript is an asynchronous programming language so you can't stop the execution for a of time; the only way you can [pseudo]stop an execution is using setTimeout() that is not a delay but a "delayed function callback".
"Egg" is a single-file importable distribution format for Python-related projects.
"The Quick Guide to Python Eggs" notes that "Eggs are to Pythons as Jars are to Java..."
Eggs actually are richer than jars; they hold interesting metadata such as licensing details, release dependencies, etc.
Yes, you can call setId(value)
in any view with any (positive) integer value that you like and then find it in the parent container using findViewById(value)
. Note that it is valid to call setId()
with the same value for different sibling views, but findViewById()
will return only the first one.
No.
But how about:
$a="test";
if("test"==$a)
{
if ($someOtherCondition)
{
echo "yes";
}
}
echo "finish";
Doing some testing with a Raspberry Pi 3B+ (I'm using an overlay file system, and need to sync periodically), I ran a comparison of my own for diff -q and cmp -s; note that this is a log from inside /dev/shm, so disk access speeds are a non-issue:
[root@mypi shm]# dd if=/dev/urandom of=test.file bs=1M count=100 ; time diff -q test.file test.copy && echo diff true || echo diff false ; time cmp -s test.file test.copy && echo cmp true || echo cmp false ; cp -a test.file test.copy ; time diff -q test.file test.copy && echo diff true || echo diff false; time cmp -s test.file test.copy && echo cmp true || echo cmp false
100+0 records in
100+0 records out
104857600 bytes (105 MB) copied, 6.2564 s, 16.8 MB/s
Files test.file and test.copy differ
real 0m0.008s
user 0m0.008s
sys 0m0.000s
diff false
real 0m0.009s
user 0m0.007s
sys 0m0.001s
cmp false
cp: overwrite âtest.copyâ? y
real 0m0.966s
user 0m0.447s
sys 0m0.518s
diff true
real 0m0.785s
user 0m0.211s
sys 0m0.573s
cmp true
[root@mypi shm]# pico /root/rwbscripts/utils/squish.sh
I ran it a couple of times. cmp -s consistently had slightly shorter times on the test box I was using. So if you want to use cmp -s to do things between two files....
identical (){
echo "$1" and "$2" are the same.
echo This is a function, you can put whatever you want in here.
}
different () {
echo "$1" and "$2" are different.
echo This is a function, you can put whatever you want in here, too.
}
cmp -s "$FILEA" "$FILEB" && identical "$FILEA" "$FILEB" || different "$FILEA" "$FILEB"
You are using wrong JSON. In this case you should use JSON that looks like this:
["orange", "apple"]
If you have to accept JSON in that form :
{"fruits":["apple","orange"]}
You'll have to create wrapper object:
public class FruitWrapper{
List<String> fruits;
//getter
//setter
}
and then your controller method should look like this:
@RequestMapping(value = "/saveFruits", method = RequestMethod.POST,
consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody FruitWrapper fruits){
...
}
You don't know the type is Integer or String then you no need Generic. Go With old style.
List list= new ArrayList ();
list.add(1);
list.add("myname");
for(Object o = list){
}
Installing on a Mac - Sierra - After numerous failed attempts to install and run gulp globally via the command line using several different instructions I found I added this to my path and it worked:
export PATH=/usr/local/Cellar/node/7.6.0/libexec/npm/bin/:$PATH
I got that path from the text output when installing gulp.
composer dump-autoload
PATH vendor/composer/autoload_classmap.php
php artisan dump-autoload
As already mentioned continue
will skip processing the code below it and until the end of the loop. Then, you are moved to the loop's condition and run the next iteration if this condition still holds (or if there is a flag, to the denoted loop's condition).
It must be highlighted that in the case of do - while
you are moved to the condition at the bottom after a continue
, not at the beginning of the loop.
This is why a lot of people fail to correctly answer what the following code will generate.
Random r = new Random();
Set<Integer> aSet= new HashSet<Integer>();
int anInt;
do {
anInt = r.nextInt(10);
if (anInt % 2 == 0)
continue;
System.out.println(anInt);
} while (aSet.add(anInt));
System.out.println(aSet);
*If your answer is that aSet
will contain odd numbers only 100%... you are wrong!
Try this:
.transparent
{
opacity:.50;
-moz-opacity:.50;
filter:alpha(opacity=50);
}
Define any languages an enum, and call getAlphabet();
char[] armenianAlphabet = getAlphabet(LocaleLanguage.ARMENIAN);
char[] russianAlphabet = getAlphabet(LocaleLanguage.RUSSIAN);
// get uppercase alphabet
char[] currentAlphabet = getAlphabet(true);
System.out.println(armenianAlphabet);
System.out.println(russianAlphabet);
System.out.println(currentAlphabet);
result
I/System.out: ??????????????????????????????????????
I/System.out: ????????????????????????????????
I/System.out: ABCDEFGHIJKLMNOPQRSTUVWXYZ
private char[] getAlphabet(){
return getAlphabet(false);
}
private char[] getAlphabet(boolean flagToUpperCase){
Locale locale = getResources().getConfiguration().locale;
LocaleLanguage language = LocaleLanguage.getLocalLanguage(locale);
return getAlphabet(language, flagToUpperCase);
}
private char[] getAlphabet(LocaleLanguage localeLanguage, boolean flagToUpperCase){
if (localeLanguage == null)
localeLanguage = LocaleLanguage.ENGLISH;
char firstLetter = localeLanguage.getFirstLetter();
char lastLetter = localeLanguage.getLastLetter();
int alphabetSize = lastLetter - firstLetter + 1;
char[] alphabet = new char[alphabetSize];
for (int index = 0; index < alphabetSize; index++ ){
alphabet[index] = (char) (index + firstLetter);
}
if (flagToUpperCase){
alphabet = new String(alphabet).toUpperCase().toCharArray();
}
return alphabet;
}
private enum LocaleLanguage{
ARMENIAN(new Locale("hy"), '?', '?'),
RUSSIAN(new Locale("ru"), '?','?'),
ENGLISH(new Locale("en"), 'a','z');
private final Locale mLocale;
private final char mFirstLetter;
private final char mLastLetter;
LocaleLanguage(Locale locale, char firstLetter, char lastLetter) {
this.mLocale = locale;
this.mFirstLetter = firstLetter;
this.mLastLetter = lastLetter;
}
public Locale getLocale() {
return mLocale;
}
public char getFirstLetter() {
return mFirstLetter;
}
public char getLastLetter() {
return mLastLetter;
}
public String getDisplayLanguage(){
return getLocale().getDisplayLanguage();
}
public String getDisplayLanguage(LocaleLanguage locale){
return getLocale().getDisplayLanguage(locale.getLocale());
}
@Nullable
public static LocaleLanguage getLocalLanguage(Locale locale){
if (locale == null)
return LocaleLanguage.ENGLISH;
for (LocaleLanguage localeLanguage : LocaleLanguage.values()){
if (localeLanguage.getLocale().getLanguage().equals(locale.getLanguage()))
return localeLanguage;
}
return null;
}
}
On Windows, line.separator is a CR/LF combination (reference here).
The Java String.split()
method takes a regular expression. So I think there's some confusion here.
Spark gives 5 types of Storage level
MEMORY_ONLY
MEMORY_ONLY_SER
MEMORY_AND_DISK
MEMORY_AND_DISK_SER
DISK_ONLY
cache()
will use MEMORY_ONLY
. If you want to use something else, use persist(StorageLevel.<*type*>)
.
By default persist()
will
store the data in the JVM heap as unserialized objects.
The Servlet 3.0 spec doesn't seem to provide a hint on how a container should order filters that have been declared via annotations. It is clear how about how to order filters via their declaration in the web.xml file, though.
Be safe. Use the web.xml file order filters that have interdependencies. Try to make your filters all order independent to minimize the need to use a web.xml file.
I normally end up creating a single conn.php file that has my database connections. Then i include that file in all files that require database queries.
cin.clear();
fflush(stdin);
This was the only thing that worked for me when reading from console. In every other case it would either read indefinitely due to lack of \n, or something would remain in the buffer.
EDIT: I found out that the previous solution made things worse. THIS one however, works:
cin.getline(temp, STRLEN);
if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
dplyr
solution using mutate_all
and pipessay you have the following:
> dft
Source: local data frame [11 x 5]
Bureau.Name Account.Code X2014 X2015 X2016
1 Senate 110 158,000 211,000 186,000
2 Senate 115 0 0 0
3 Senate 123 15,000 71,000 21,000
4 Senate 126 6,000 14,000 8,000
5 Senate 127 110,000 234,000 134,000
6 Senate 128 120,000 159,000 134,000
7 Senate 129 0 0 0
8 Senate 130 368,000 465,000 441,000
9 Senate 132 0 0 0
10 Senate 140 0 0 0
11 Senate 140 0 0 0
and want to remove commas from the year variables X2014-X2016, and convert them to numeric. also, let's say X2014-X2016 are read in as factors (default)
dft %>%
mutate_all(funs(as.character(.)), X2014:X2016) %>%
mutate_all(funs(gsub(",", "", .)), X2014:X2016) %>%
mutate_all(funs(as.numeric(.)), X2014:X2016)
mutate_all
applies the function(s) inside funs
to the specified columns
I did it sequentially, one function at a time (if you use multiple
functions inside funs
then you create additional, unnecessary columns)
(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);
its going to give you solution i suppose
They are lists because you type them as lists in the dictionary:
bikes = {
# Bike designed for children"
"Trike": ["Trike", 20, 100],
# Bike designed for everyone"
"Kruzer": ["Kruzer", 50, 165]
}
You should use the bike-class instead:
bikes = {
# Bike designed for children"
"Trike": Bike("Trike", 20, 100),
# Bike designed for everyone"
"Kruzer": Bike("Kruzer", 50, 165)
}
This will allow you to get the cost of the bikes with bike.cost as you were trying to.
for bike in bikes.values():
profit = bike.cost * margin
print(bike.name + " : " + str(profit))
This will now print:
Kruzer : 33.0
Trike : 20.0
With this code you can get the JVM arguments:
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
...
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = runtimeMxBean.getInputArguments();
Here you can Find some other way to do the same.
Read file.
File file1 = new File("C:\Build\myfolder\myTestfile.txt");
def String yourData = file1.readLines();
Read Full file.
File file1 = new File("C:\Build\myfolder\myfile.txt");
def String yourData= file1.getText();
Read file Line Bye Line.
File file1 = new File("C:\Build\myfolder\myTestfile.txt");
for (def i=0;i<=30;i++) // specify how many line need to read eg.. 30
{
log.info file1.readLines().get(i)
}
Create a new file.
new File("C:\Temp\FileName.txt").createNewFile();
Other than the append
function, if by "multiple values" you mean another list, you can simply concatenate them like so.
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]
This is a charming answer. Work well on any currency which is selected for store.
$formattedPrice = Mage::helper('core')->currency($finalPrice, true, false);
This is too long to be posted as a comment to already accepted answer, so I put it as a separate answer
One thing also to consider is whether you expect to have a hard upper memory limit on your cache instance.
Since redis is an nosql database with tons of features and caching is only one option it can be used for, it allocates memory as it needs it — the more objects you put in it, the more memory it uses. The maxmemory
option does not strictly enforces upper memory limit usage. As you work with cache, keys are evicted and expired; chances are your keys are not all the same size, so internal memory fragmentation occurs.
By default redis uses jemalloc memory allocator, which tries its best to be both memory-compact and fast, but it is a general purpose memory allocator and it cannot keep up with lots of allocations and object purging occuring at a high rate. Because of this, on some load patterns redis process can apparently leak memory because of internal fragmentation. For example, if you have a server with 7 Gb RAM and you want to use redis as non-persistent LRU cache, you may find that redis process with maxmemory
set to 5Gb over time would use more and more memory, eventually hitting total RAM limit until out-of-memory killer interferes.
memcached is a better fit to scenario described above, as it manages its memory in a completely different way. memcached allocates one big chunk of memory — everything it will ever need — and then manages this memory by itself, using its own implemented slab allocator. Moreover, memcached tries hard to keep internal fragmentation low, as it actually uses per-slab LRU algorithm, when LRU evictions are done with object size considered.
With that said, memcached still has a strong position in environments, where memory usage has to be enforced and/or be predictable. We've tried to use latest stable redis (2.8.19) as a drop-in non-persistent LRU-based memcached replacement in workload of 10-15k op/s, and it leaked memory A LOT; the same workload was crashing Amazon's ElastiCache redis instances in a day or so because of the same reasons.
Parallel.ForEach
requires a list of user-defined workers and a non-async Action
to perform with each worker.
Task.WaitAll
and Task.WhenAll
require a List<Task>
, which are by definition asynchronous.
I found RiaanDP's response very useful to understand the difference, but it needs a correction for Parallel.ForEach
. Not enough reputation to respond to his comment, thus my own response.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncTest
{
class Program
{
class Worker
{
public int Id;
public int SleepTimeout;
public void DoWork(DateTime testStart)
{
var workerStart = DateTime.Now;
Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
Id, Thread.CurrentThread.ManagedThreadId, (workerStart - testStart).TotalSeconds.ToString("F2"));
Thread.Sleep(SleepTimeout);
var workerEnd = DateTime.Now;
Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
Id, (workerEnd - workerStart).TotalSeconds.ToString("F2"), (workerEnd - testStart).TotalSeconds.ToString("F2"));
}
public async Task DoWorkAsync(DateTime testStart)
{
var workerStart = DateTime.Now;
Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
Id, Thread.CurrentThread.ManagedThreadId, (workerStart - testStart).TotalSeconds.ToString("F2"));
await Task.Run(() => Thread.Sleep(SleepTimeout));
var workerEnd = DateTime.Now;
Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
Id, (workerEnd - workerStart).TotalSeconds.ToString("F2"), (workerEnd - testStart).TotalSeconds.ToString("F2"));
}
}
static void Main(string[] args)
{
var workers = new List<Worker>
{
new Worker { Id = 1, SleepTimeout = 1000 },
new Worker { Id = 2, SleepTimeout = 2000 },
new Worker { Id = 3, SleepTimeout = 3000 },
new Worker { Id = 4, SleepTimeout = 4000 },
new Worker { Id = 5, SleepTimeout = 5000 },
};
var startTime = DateTime.Now;
Console.WriteLine("Starting test: Parallel.ForEach...");
PerformTest_ParallelForEach(workers, startTime);
var endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
startTime = DateTime.Now;
Console.WriteLine("Starting test: Task.WaitAll...");
PerformTest_TaskWaitAll(workers, startTime);
endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
startTime = DateTime.Now;
Console.WriteLine("Starting test: Task.WhenAll...");
var task = PerformTest_TaskWhenAll(workers, startTime);
task.Wait();
endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
Console.ReadKey();
}
static void PerformTest_ParallelForEach(List<Worker> workers, DateTime testStart)
{
Parallel.ForEach(workers, worker => worker.DoWork(testStart));
}
static void PerformTest_TaskWaitAll(List<Worker> workers, DateTime testStart)
{
Task.WaitAll(workers.Select(worker => worker.DoWorkAsync(testStart)).ToArray());
}
static Task PerformTest_TaskWhenAll(List<Worker> workers, DateTime testStart)
{
return Task.WhenAll(workers.Select(worker => worker.DoWorkAsync(testStart)));
}
}
}
The resulting output is below. Execution times are comparable. I ran this test while my computer was doing the weekly anti virus scan. Changing the order of the tests did change the execution times on them.
Starting test: Parallel.ForEach...
Worker 1 started on thread 9, beginning 0.02 seconds after test start.
Worker 2 started on thread 10, beginning 0.02 seconds after test start.
Worker 3 started on thread 11, beginning 0.02 seconds after test start.
Worker 4 started on thread 13, beginning 0.03 seconds after test start.
Worker 5 started on thread 14, beginning 0.03 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.02 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.02 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.03 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.03 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.03 seconds after the test start.
Test finished after 5.03 seconds.
Starting test: Task.WaitAll...
Worker 1 started on thread 9, beginning 0.00 seconds after test start.
Worker 2 started on thread 9, beginning 0.00 seconds after test start.
Worker 3 started on thread 9, beginning 0.00 seconds after test start.
Worker 4 started on thread 9, beginning 0.00 seconds after test start.
Worker 5 started on thread 9, beginning 0.01 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.01 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.01 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.01 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.01 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.
Starting test: Task.WhenAll...
Worker 1 started on thread 9, beginning 0.00 seconds after test start.
Worker 2 started on thread 9, beginning 0.00 seconds after test start.
Worker 3 started on thread 9, beginning 0.00 seconds after test start.
Worker 4 started on thread 9, beginning 0.00 seconds after test start.
Worker 5 started on thread 9, beginning 0.00 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.00 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.00 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.00 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.00 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.
On OSX Mavericks:
Make your shell script executable:
chmod +x your-shell-script.sh
Rename your script to have a .app
suffix:
mv your-shell-script.sh your-shell-script.app
Rename your script back to a .sh
suffix:
mv your-shell-script.app your-shell-script.sh
Now when you click on the script in the dock, A terminal window will pop up and execute your script.
Bonus: To get the terminal to close when your script has completed, add exit 0
to the end and change the terminal settings to "close the shell if exited cleanly" like it says to do in this SO answer.
Using contains didn't work well for my string with special characters. Find worked though.
df[df['A'].str.find("hello") != -1]
attr accepts two strings.
The correct way is:
jQuery("#radio_1").attr('checked', 'true');
My simple trick to change background color and color of the text in Popup Menu / Option Menu
<style name="CustomActionBarTheme"
parent="@android:style/Theme.Holo">
<item name="android:popupMenuStyle">@style/MyPopupMenu</item>
<item name="android:itemTextAppearance">@style/TextAppearance</item>
</style>
<!-- Popup Menu Background Color styles -->
<style name="MyPopupMenu"
parent="@android:style/Widget.Holo.ListPopupWindow">
<item name="android:popupBackground">@color/Your_color_for_background</item>
</style>
<!-- Popup Menu Text Color styles -->
<style name="TextAppearance">
<item name="android:textColor">@color/Your_color_for_text</item>
</style>
you could have both of them use a "corpo_button" class, or something like that, and then in $(".corpo_button").click(...)
just call $(this).toggleClass("corpo_buttons_asia corpo_buttons_global");
As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.
Generally speaking, if you need to generate numbers from min
to max
(including both), you write
random.nextInt(max - min + 1) + min
I'd like to add that removing the Visual C++ 2012 Redistributable may be necessary, too. I removed both the Visual C++ 2012 Redistributable x84 and x64 and then my installation worked.
Another possibility is to select the Install Dependencies checkbox In the R package installer, on the bottom right:
HTML
<a href="demoLink" id="myLink"> myLink </a>
<button onclick="fireLink(event)"> Call My Link </button>
JS
// click event listener of the link element --------------
document.getElementById('myLink').addEventListener("click", callLink);
function callLink(e) {
// code to fire
}
// function invoked by the button element ----------------
function fireLink(event) {
document.getElementById('myLink').click(); // script calls the "click" event of the link element
}
Open github app. Then, add the Folder of files into the github repo file onto your computer (You WILL need to copy the repo onto your computer. Most repo files are located in the following directory: C:\Users\USERNAME\Documents\GitHub\REPONAME) Then, in the github app, check our your repo. You can easily commit from there.
I know this has been said earlier, but jQuery Autocomplete will do exactly what you need. You should check out the docs as the autocomplete is very customizable. If you are familiar with javascript then you should be able to work this out. If not I can give you a few pointers, as I have done this once before, but beware I am not well versed in javascript myself either, so bear with me on this.
I think the first thing you should do is just get a simple autocomplete text field working on your page, and then you can customize it from there.
The autocomplete widget accepts JSON data as it's 'source:' option. So you should set-up your app to produce the 20 top level categories, and subcategories in JSON format.
The next thing to know is that when the user types into your textfield, the autocomplete widget will send the typed values in a parameter called "term".
So let's say you first set-up your site to deliver the JSON data from a URL like this:
/categories.json
Then your autocomplete source: option would be 'source: /categories.json'.
When a user types into the textfield, such as 'first-cata...' the autocomplete widget will start sending the value in the 'term' parameter like this:
/categories.json?term=first-cata
This will return JSON data back to the widget filtered by anything that matches 'first-cata', and this is displayed as an autocomplete suggestion.
I am not sure what you are programming in, but you can specify how the 'term' parameter finds a match. So you can customize this, so that the term finds a match in the middle of a word if you want. Example, if the user types 'or' you code could make a match on 'sports'.
Lastly, you made a comment that you want to be able to select a category name but have the autocomplete widget submit the category ID not the name.
This can easily be done with a hidden field. This is what is shown in the jQuery autocomplete docs.
When a user selects a category, your JavaScript should update a hidden field with the ID.
I know this answer is not very detailed, but that is mainly because I am not sure what you are programming in, but the above should point you in the right direction. The thing to know is that you can do practically any customizing you want with this widget, if you are willing to spend the time to learn it.
These are the broad strokes, but you can look here for some notes I made when I implemented something similar to what you want in a Rails app.
Hope this helped.
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
in your PrimaryKey column and make sure its set to a data type int. If the column is the primary key and is set to IsIDentity to true in SQL there is no need for this line of code [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Count()
is an extension method introduced by LINQ while the Count
property is part of the List itself (derived from ICollection
). Internally though, LINQ checks if your IEnumerable
implements ICollection
and if it does it uses the Count
property. So at the end of the day, there's no difference which one you use for a List
.
To prove my point further, here's the code from Reflector for Enumerable.Count()
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection<TSource> is2 = source as ICollection<TSource>;
if (is2 != null)
{
return is2.Count;
}
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}
with 2008 Server 2008 and 2008 R2
Add-PSSnapin -Name SqlServerCmdletSnapin100, SqlServerProviderSnapin100
with 2012 and 2014
Push-Location
Import-Module -Name SQLPS -DisableNameChecking
Pop-Location
If you don't want to have to know the serial name of your device for adb -s emulator-5554 emu kill
, then you can just use adb -e emu kill
to kill a single emulator. This won't kill anything if you have more than one emulator running at once, but it's useful for automation where you start and stop a single emulator for a test.
If you want to do this in the fastest possible way, while at the same time handling any issues with the path parsing or property resolution, check out path-value.
const {resolveValue} = require('path-value');
const value = resolveValue(obj, 'a.b.c');
The library is 100% TypeScript, works in NodeJS + all web browsers. And it is fully extendible, you can use lower-level resolvePath
, and handle errors your own way, if you want.
const {resolvePath} = require('path-value');
const res = resolvePath(obj, 'a.b.c'); //=> low-level parsing result descriptor
Simply use min()
SELECT company, workflow, MIN(date)
FROM workflowTable
GROUP BY company, workflow
Have a look at this list on Wikipedia about which browsers support SVG. It also provides links to more details in the footnotes. Firefox for example supports basic SVG, but at the moment lacks most animation features.
A tutorial about how to create SVG objects using Javascript can be found here:
var svgns = "http://www.w3.org/2000/svg";
var svgDocument = evt.target.ownerDocument;
var shape = svgDocument.createElementNS(svgns, "circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r", 20);
shape.setAttributeNS(null, "fill", "green");
You can use file -i file_name
to check what exactly your original file format is.
Once you get that, you can do the following:
iconv -f old_format -t utf-8 input_file -o output_file
The data still exists out in github, you can create a new branch from the old data:
git checkout origin/BranchName #get a readonly pointer to the old branch
git checkout –b BranchName #create a new branch from the old
git push origin BranchName #publish the new branch
You need to run the .datepicker();
again after you've dynamically created the other textbox elements.
I would recommend doing so in the callback method of the call that is adding the elements to the DOM.
So lets say you're using the JQuery Load method to pull the elements from a source and load them into the DOM, you would do something like this:
$('#id_of_div_youre_dynamically_adding_to').load('ajax/get_textbox', function() {
$(".datepicker_recurring_start" ).datepicker();
});
With formulas, what you can do is:
D2
), add =COUNTA(A2:C2)
D4
in our example)D5
): =SUM(D2:D4)
None of the above solution worked for me. Not sure if it is specific to my setup or new release.
I am using Android Studio Beta 0.8.9 and I was not getting any com.google.android.gms:play-service in the library list on following this instruction:
Go to File -> Project Structure -> Select Project Settings -> Select 'Dependencies' Tab Click '+' -> 1.Library Dependencies -> Select com.google.android.gms:play-services:+
I had already done this:
First of all you have to launch the sdk manager and download and install the following files located under "extras": Android support repository, Google play services, Google repository.
What resolved it was to add from SDK Manager, "Google play services for Froyo" then repeating the first step.
Did not understand the reason properly but this worked.
PS: I just observed that even now when I search for play-services this does not come, but when I directly scroll and look through the list it is right there.
Building on Joan-Diego Rodriguez's routine with Jordi's approach and some of Jacek Kotowski's code - This function converts any table name for the active workbook into a usable address for SQL queries.
Note to MikeL: Addition of "[#All]" includes headings avoiding problems you reported.
Function getAddress(byVal sTableName as String) as String
With Range(sTableName & "[#All]")
getAddress= "[" & .Parent.Name & "$" & .Address(False, False) & "]"
End With
End Function
As of now (version 1.18.0), you can check keyboard shortcuts by going to File > Preferences > Keyboard shortcuts. Here you can search for comment related shortcuts.
For users who are coming from Sublime Text
or likes to have Ctrl+Shift+/, you can make the change from the above mentioned setting or simply install the Sublime Text Keymap
extension by Microsoft.
obj
is an array in your example.
fs.writeFileSync(filename, data, [options]) requires either String
or Buffer
in the data parameter. see docs.
Try to write the array in a string format:
// writes 'https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks'
fs.writeFileSync('./data.json', obj.join(',') , 'utf-8');
Or:
// writes ['https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks']
var util = require('util');
fs.writeFileSync('./data.json', util.inspect(obj) , 'utf-8');
edit: The reason you see the array in your example is because node's implementation of console.log
doesn't just call toString
, it calls util.format
see console.js source