You can do this with JavaScript.
document.getElementById('foo').height = document.getElementById('foo').contentWindow.document.body.scrollHeight + "px";
Function strlen
shows the number of character before \0
and using it for std::string
may report wrong length.
strlen(str.c_str()); // It may return wrong length.
In C++, a string can contain \0
within the characters but C-style-zero-terminated strings can not but at the end. If the std::string
has a \0
before the last character then strlen
reports a length less than the actual length.
Try to use .length()
or .size()
, I prefer second one since another standard containers have it.
str.size()
You need to escape your backslash by preceding it with, yes, another backslash:
print("\\")
And for versions prior to Python 3:
print "\\"
The \
character is called an escape character, which interprets the character following it differently. For example, n
by itself is simply a letter, but when you precede it with a backslash, it becomes \n
, which is the newline character.
As you can probably guess, \
also needs to be escaped so it doesn't function like an escape character. You have to... escape the escape, essentially.
In javascript:
function detectCardType(number) {
var re = {
electron: /^(4026|417500|4405|4508|4844|4913|4917)\d+$/,
maestro: /^(5018|5020|5038|5612|5893|6304|6759|6761|6762|6763|0604|6390)\d+$/,
dankort: /^(5019)\d+$/,
interpayment: /^(636)\d+$/,
unionpay: /^(62|88)\d+$/,
visa: /^4[0-9]{12}(?:[0-9]{3})?$/,
mastercard: /^5[1-5][0-9]{14}$/,
amex: /^3[47][0-9]{13}$/,
diners: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,
discover: /^6(?:011|5[0-9]{2})[0-9]{12}$/,
jcb: /^(?:2131|1800|35\d{3})\d{11}$/
}
for(var key in re) {
if(re[key].test(number)) {
return key
}
}
}
Unit test:
describe('CreditCard', function() {
describe('#detectCardType', function() {
var cards = {
'8800000000000000': 'UNIONPAY',
'4026000000000000': 'ELECTRON',
'4175000000000000': 'ELECTRON',
'4405000000000000': 'ELECTRON',
'4508000000000000': 'ELECTRON',
'4844000000000000': 'ELECTRON',
'4913000000000000': 'ELECTRON',
'4917000000000000': 'ELECTRON',
'5019000000000000': 'DANKORT',
'5018000000000000': 'MAESTRO',
'5020000000000000': 'MAESTRO',
'5038000000000000': 'MAESTRO',
'5612000000000000': 'MAESTRO',
'5893000000000000': 'MAESTRO',
'6304000000000000': 'MAESTRO',
'6759000000000000': 'MAESTRO',
'6761000000000000': 'MAESTRO',
'6762000000000000': 'MAESTRO',
'6763000000000000': 'MAESTRO',
'0604000000000000': 'MAESTRO',
'6390000000000000': 'MAESTRO',
'3528000000000000': 'JCB',
'3589000000000000': 'JCB',
'3529000000000000': 'JCB',
'6360000000000000': 'INTERPAYMENT',
'4916338506082832': 'VISA',
'4556015886206505': 'VISA',
'4539048040151731': 'VISA',
'4024007198964305': 'VISA',
'4716175187624512': 'VISA',
'5280934283171080': 'MASTERCARD',
'5456060454627409': 'MASTERCARD',
'5331113404316994': 'MASTERCARD',
'5259474113320034': 'MASTERCARD',
'5442179619690834': 'MASTERCARD',
'6011894492395579': 'DISCOVER',
'6011388644154687': 'DISCOVER',
'6011880085013612': 'DISCOVER',
'6011652795433988': 'DISCOVER',
'6011375973328347': 'DISCOVER',
'345936346788903': 'AMEX',
'377669501013152': 'AMEX',
'373083634595479': 'AMEX',
'370710819865268': 'AMEX',
'371095063560404': 'AMEX'
};
Object.keys(cards).forEach(function(number) {
it('should detect card ' + number + ' as ' + cards[number], function() {
Basket.detectCardType(number).should.equal(cards[number]);
});
});
});
});
"project property - CUDA Runtime API - GPU - NVCC Compilation Type"
Set the 64 bit compile option -m64 -cubin
The hint is at compile log. Like this:
nvcc.exe ~~~~~~ -machine 32 -ccbin ~~~~~
That "-machine 32"
is problem.
First set 64bit compile option, next re setting hybrid compile option. Then u can see the succeed.
I posted this question and never saw the feedback (which came in several months after, it seems :).
As Kinlan mentioned, ALLOW-FROM is not supported in all browsers as an X-Frame-Options value.
The solution was to branch based on browser type. For IE, ship X-Frame-Options. For everyone else, ship X-Content-Security-Policy.
Hope this helps, and sorry for taking so long to close the loop!
Strangely enough,
package main
func main () {
var sessions = map[string] chan int{};
delete(sessions, "moo");
}
seems to work. This seems a poor use of resources though!
Another way is to check for existence and use the value itself:
package main
func main () {
var sessions = map[string] chan int{};
sessions["moo"] = make (chan int);
_, ok := sessions["moo"];
if ok {
delete(sessions, "moo");
}
}
This error may happen when mapping variables you defined in REST definition do not match with @PathVariable names.
Example: Suppose you defined in the REST definition
@GetMapping(value = "/{appId}", produces = "application/json", consumes = "application/json")
Then during the definition of the function, it should be
public ResponseEntity<List> getData(@PathVariable String appId)
This error may occur when you use any other variable other than defined in the REST controller definition with @PathVariable. Like, the below code will raise the error as ID is different than appId variable name:
public ResponseEntity<List> getData(@PathVariable String ID)
<section class="min-vh-100 d-flex align-items-center justify-content-center py-3">
<div class="container">
<div class="row justify-content-between align-items-center">
x
x
x
</div>
</div>
</section>
_x000D_
I spent a decent amount of time trying to solve this problem. I thought that I was somehow setting my classpath incorrectly but the problem was that I typed:
java -cp C:/java/MyClasses C:/java/MyClasses/utilities/myapp/Cool
instead of:
java -cp C:/java/MyClasses utilities/myapp/Cool
I thought the meaning of fully qualified meant to include the full path name instead of the full package name.
Define extension: String+Extension.ts
interface String {
toBoolean(): boolean
}
String.prototype.toBoolean = function (): boolean {
switch (this) {
case 'true':
case '1':
case 'on':
case 'yes':
return true
default:
return false
}
}
And import in any file where you want to use it '@/path/to/String+Extension'
As the other answers note, you can add a background-color
to a <span>
around your text to get this to work.
In the case where you have line-height
though, you will see gaps. To fix this you can add a box-shadow
with a little bit of grow to your span. You will also want box-decoration-break: clone;
for FireFox to render it properly.
EDIT: If you're getting issues in IE11 with the box-shadow, try adding an outline: 1px solid [color];
as well for IE only.
Here's what it looks like in action:
.container {_x000D_
margin: 0 auto;_x000D_
width: 400px;_x000D_
padding: 10px;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
font-family: Verdana, sans-serif;_x000D_
text-transform: uppercase;_x000D_
line-height: 1.5;_x000D_
text-align: center;_x000D_
font-size: 40px;_x000D_
}_x000D_
_x000D_
h2 > span {_x000D_
background-color: #D32;_x000D_
color: #FFF;_x000D_
box-shadow: -10px 0px 0 7px #D32,_x000D_
10px 0px 0 7px #D32,_x000D_
0 0 0 7px #D32;_x000D_
box-decoration-break: clone;_x000D_
}
_x000D_
<div class="container">_x000D_
<h2><span>A HEADLINE WITH BACKGROUND-COLOR PLUS BOX-SHADOW :3</span></h2>_x000D_
</div>
_x000D_
Clear() set the Text property to nothing. So txtbox1.Text = Nothing does the same thing as clear. An empty string (also available through String.Empty) is not a null reference, but has no value of course.
All answers are correct, but you need to convert a long big fat number into a timer first:
public String toTimer(long milliseconds){
String finalTimerString = "";
String secondsString;
// Convert total duration into time
int hours = (int)( milliseconds / (1000*60*60));
int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
// Add hours if there
if(hours > 0){
finalTimerString = hours + ":";
}
// Prepending 0 to seconds if it is one digit
if(seconds < 10){
secondsString = "0" + seconds;
}else{
secondsString = "" + seconds;}
finalTimerString = finalTimerString + minutes + ":" + secondsString;
// return timer string
return finalTimerString;
}
And this is how you use it:
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(String.format("%s", toTimer(progress)));
}
Try
git checkout <commit hash>
git checkout -b new_branch
The commit should only exist once in your tree, not in two separate branches.
This allows you to check out that specific commit and name it what you will.
Another alternative: HigLabo
https://higlabo.codeplex.com/documentation
Good discussion: https://higlabo.codeplex.com/discussions/479250
//====Imap sample================================//
//You can set default value by Default property
ImapClient.Default.UserName = "your server name";
ImapClient cl = new ImapClient("your server name");
cl.UserName = "your name";
cl.Password = "pass";
cl.Ssl = false;
if (cl.Authenticate() == true)
{
Int32 MailIndex = 1;
//Get all folder
List<ImapFolder> l = cl.GetAllFolders();
ImapFolder rFolder = cl.SelectFolder("INBOX");
MailMessage mg = cl.GetMessage(MailIndex);
}
//Delete selected mail from mailbox
ImapClient pop = new ImapClient("server name", 110, "user name", "pass");
pop.AuthenticateMode = Pop3AuthenticateMode.Pop;
Int64[] DeleteIndexList = new.....//It depend on your needs
cl.DeleteEMail(DeleteIndexList);
//Get unread message list from GMail
using (ImapClient cl = new ImapClient("imap.gmail.com"))
{
cl.Port = 993;
cl.Ssl = true;
cl.UserName = "xxxxx";
cl.Password = "yyyyy";
var bl = cl.Authenticate();
if (bl == true)
{
//Select folder
ImapFolder folder = cl.SelectFolder("[Gmail]/All Mail");
//Search Unread
SearchResult list = cl.ExecuteSearch("UNSEEN UNDELETED");
//Get all unread mail
for (int i = 0; i < list.MailIndexList.Count; i++)
{
mg = cl.GetMessage(list.MailIndexList[i]);
}
}
//Change mail read state as read
cl.ExecuteStore(1, StoreItem.FlagsReplace, "UNSEEN")
}
//Create draft mail to mailbox
using (ImapClient cl = new ImapClient("imap.gmail.com"))
{
cl.Port = 993;
cl.Ssl = true;
cl.UserName = "xxxxx";
cl.Password = "yyyyy";
var bl = cl.Authenticate();
if (bl == true)
{
var smg = new SmtpMessage("from mail address", "to mail addres list"
, "cc mail address list", "This is a test mail.", "Hi.It is my draft mail");
cl.ExecuteAppend("GMail/Drafts", smg.GetDataText(), "\\Draft", DateTimeOffset.Now);
}
}
//Idle
using (var cl = new ImapClient("imap.gmail.com", 993, "user name", "pass"))
{
cl.Ssl = true;
cl.ReceiveTimeout = 10 * 60 * 1000;//10 minute
if (cl.Authenticate() == true)
{
var l = cl.GetAllFolders();
ImapFolder r = cl.SelectFolder("INBOX");
//You must dispose ImapIdleCommand object
using (var cm = cl.CreateImapIdleCommand()) Caution! Ensure dispose command object
{
//This handler is invoked when you receive a mesage from server
cm.MessageReceived += (Object o, ImapIdleCommandMessageReceivedEventArgs e) =>
{
foreach (var mg in e.MessageList)
{
String text = String.Format("Type is {0} Number is {1}", mg.MessageType, mg.Number);
Console.WriteLine(text);
}
};
cl.ExecuteIdle(cm);
while (true)
{
var line = Console.ReadLine();
if (line == "done")
{
cl.ExecuteDone(cm);
break;
}
}
}
}
}
The game development world is a funny one: On one hand, they're often quick to accept new ideas, on the other hand, they're still in the stone age.
The truth is, there's rarely that much incentive in switching to .NET/Java/anything other than C/C++.
Most game companies license parts of the game engine from other companies. These parts are written in C++, and although you might have access to the source so you could port it, that takes a lot of effort (and of course, the license needs to allow it).
Also, a lot of legacy code already exists in C++. If code from previous projects can be reused (say, if you're writing a sequel), that counts even more in favor of sticking with the same language, instead of rewriting it in a new language (more so since you'll likely reintroduce a ton of bugs which you'll need to spend time ironing out.
Finally, it's rare for games to be written in 100% C++ anyway - a lot is done using scripting languages, whether they're custom or just integrating an existing languages (Lua being one of the more popular ones these days).
As far as garbage collection is concerned, that can be a bit of a problem. The problem is not so much that it exists, it's more how it works - the garbage collector MUST be non-blocking (or at least be guaranteed to only block very briefly), since it's simply unacceptable to have the game freeze for 10 seconds while it scans all the allocated memory to see what can be freed. I know Java tends to choke quite a bit in GC'ing when it's close to running out of memory (and for some games out there, it will).
You're also a bit more restricted in what you can do: you can't fully exploit the hardware due to the overhead of the runtime. Imagine Crysis being written in Java... even if that's the only visible difference, it just wouldn't be the same (I'm also pretty sure you'd need a Core i7 to run it.).
This doesn't mean these languages don't have their place in game development - and no, I'm not just referring to tool programming. For most games, you don't need that extra bit of performance you get from C++, including 3D games, and if you're writing it all from scratch, it can make perfect sense to use something like XNA - in fact, there's a good chance it will.
As far as commercial games are concerned - does RuneScape count? That may well be the most succesful Java game out there.
The Hungarian notation was abused, particularly by Microsoft, leading to prefixes longer than the variable name, and showing it is quite rigid, particularly when you change the types (the infamous lparam/wparam, of different type/size in Win16, identical in Win32).
Thus, both due to this abuse, and its use by M$, it was put down as useless.
At my work, we code in Java, but the founder cames from MFC world, so use similar code style (aligned braces, I like this!, capitals to method names, I am used to that, prefix like m_ to class members (fields), s_ to static members, etc.).
And they said all variables should have a prefix showing its type (eg. a BufferedReader is named brData). Which shown as being a bad idea, as the types can change but the names doesn't follow, or coders are not consistent in the use of these prefixes (I even see aBuffer, theProxy, etc.!).
Personally, I chose for a few prefixes that I find useful, the most important being b to prefix boolean variables, as they are the only ones where I allow syntax like if (bVar)
(no use of autocast of some values to true or false).
When I coded in C, I used a prefix for variables allocated with malloc, as a reminder it should be freed later. Etc.
So, basically, I don't reject this notation as a whole, but took what seems fitting for my needs.
And of course, when contributing to some project (work, open source), I just use the conventions in place!
My version of user113716's answer. His removes a value if no match is found, which is not good.
var y = [1, 2, 3]
var removeItem = 2;
var i = $.inArray(removeItem,y)
if (i >= 0){
y.splice(i, 1);
}
alert(y);
This now removes 1 item if a match is found, 0 if no matches are found.
How it works:
value
in an array
count
number of values starting at index
, so we just want a count
of 1
For me, I just needed to use getString()
vs. getJSONObject()
(the latter threw that error):
JSONObject jsonObject = new JSONObject(jsonString);
String valueIWanted = jsonObject.getString("access_token"))
File -> Source Control -> Advanced -> Change Source Control and then unbind and/or disconnect all projects and the solution.
This should remove all bindings from the solution and project files. (After this you can switch the SCC provider in Tools -> Options -> Source Control -> Plug-in Selection).
The SCC specification prescribes that all SCC providers should implement this behavior. (I only tested it for VSS, TFS and AnkhSVN)
I was looking for a general way of adding a column of numpy.nan
s to a dataframe without getting the dumb SettingWithCopyWarning
.
From the following:
numpy
array of NaNs in-lineI came up with this:
col = 'column_name'
df = df.assign(**{col:numpy.full(len(df), numpy.nan)})
Make sure you don't have any syntax errors in your Dockerfile as this can cause this error as well. A correct example is:
RUN apt-get update \
&& apt-get -y install curl \
another-package
It was a combination of fixing a syntax error and adding apt-get update
that solved the problem for me.
print df.sort_index(by='Frequency',ascending=False)
where by is the name of the column,if you want to sort the dataset based on column
It can be done by jquery and css. i did it in a way that can be used in dynamic situations , you just have to change background-image in jquery and it will do every thing , also you can change the time in css.
The fiddle : https://jsfiddle.net/Naderial/zohfvqz7/
Html:
<div class="test">
CSS :
.test {
/* as default, we set a background-image , but it is not nessesary */
background-image: url(http://lorempixel.com/400/200);
width: 200px;
height: 200px;
/* we set transition to 'all' properies - but you can use it just for background image either - by default the time is set to 1 second, you can change it yourself*/
transition: linear all 1s;
/* if you don't use delay , background will disapear and transition will start from a white background - you have to set the transition-delay the same as transition time OR more , so there won't be any problems */
-webkit-transition-delay: 1s;/* Safari */
transition-delay: 1s;
}
JS:
$('.test').click(function() {
//you can use all properties : background-color - background-image ...
$(this).css({
'background-image': 'url(http://lorempixel.com/400/200)'
});
});
You could do so by using the attribute accept
and adding allowed mime-types to it. But not all browsers do respect that attribute and it could easily be removed via some code inspector. So in either case you need to check the file type on the server side (your second question).
Example:
<input type="file" name="upload" accept="application/pdf,application/vnd.ms-excel" />
To your third question "And when I click the files (PDF/XLS) on webpage it automatically should open.":
You can't achieve that. How a PDF or XLS is opened on the client machine is set by the user.
This website has some nice examples for using spring's RestTemplate. Here is a code example of how it can work to get a simple object:
private static void getEmployees()
{
final String uri = "http://localhost:8080/springrestexample/employees.xml";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);
System.out.println(result);
}
This article describes maximum transmission unit (MTU) http://en.wikipedia.org/wiki/Maximum_transmission_unit. It states that IP hosts must be able to process 576 bytes for an IP packet. However, it notes the minumum is 68. RFC 791: "Every internet module must be able to forward a datagram of 68 octets without further fragmentation. This is because an internet header may be up to 60 octets, and the minimum fragment is 8 octets."
Thus, safe packet size of 508 = 576 - 60 (IP header) - 8 (udp header) is reasonable.
As mentioned by user607811, fragmentation by other network layers must be reassembled. https://tools.ietf.org/html/rfc1122#page-56 3.3.2 Reassembly The IP layer MUST implement reassembly of IP datagrams. We designate the largest datagram size that can be reassembled by EMTU_R ("Effective MTU to receive"); this is sometimes called the "reassembly buffer size". EMTU_R MUST be greater than or equal to 576
I'm assuming that by empty you mean "has no properties of its own".
// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isEmpty(obj) {
// null and undefined are "empty"
if (obj == null) return true;
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length > 0) return false;
if (obj.length === 0) return true;
// If it isn't an object at this point
// it is empty, but it can't be anything *but* empty
// Is it empty? Depends on your application.
if (typeof obj !== "object") return true;
// Otherwise, does it have any properties of its own?
// Note that this doesn't handle
// toString and valueOf enumeration bugs in IE < 9
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
}
Examples:
isEmpty(""), // true
isEmpty(33), // true (arguably could be a TypeError)
isEmpty([]), // true
isEmpty({}), // true
isEmpty({length: 0, custom_property: []}), // true
isEmpty("Hello"), // false
isEmpty([1,2,3]), // false
isEmpty({test: 1}), // false
isEmpty({length: 3, custom_property: [1,2,3]}) // false
If you only need to handle ECMAScript5 browsers, you can use Object.getOwnPropertyNames
instead of the hasOwnProperty
loop:
if (Object.getOwnPropertyNames(obj).length > 0) return false;
This will ensure that even if the object only has non-enumerable properties isEmpty
will still give you the correct results.
You can use GCD to dispatch the scroll into the next iteration of main run loop in viewDidLoad to achieve this behavior. The scroll will be performed before the collection view is showed on screen, so there will be no flashing.
- (void)viewDidLoad {
dispatch_async (dispatch_get_main_queue (), ^{
NSIndexPath *indexPath = YOUR_DESIRED_INDEXPATH;
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
});
}
See JavaDoc:
month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
So, the month you set is the first month of next year.
Well, I would do it like this:
select datediff(minute,'1990-1-1',datetime)
where '1990-1-1' is an arbitrary base datetime.
Try using SQLITE_STATIC
instead of SQLITE_TRANSIENT
for those inserts.
SQLITE_TRANSIENT
will cause SQLite to copy the string data before returning.
SQLITE_STATIC
tells it that the memory address you gave it will be valid until the query has been performed (which in this loop is always the case). This will save you several allocate, copy and deallocate operations per loop. Possibly a large improvement.
since your over
div doesn't have a positioning, the z-index doesn't know where and how to position it (and with respect to what?). Just change your over div's position to relative, so there is no side effects on that div and then the under div will obey to your will.
here is your example on jsfiddle: Fiddle
edit: I see someone already mentioned this answer!
You've missed the id out before the NOT; it needs to be specified.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php
Simple example usage:
// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
dicts[i] = values[i]
print(dicts)
alternatively
In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
We had this same issue. We solved it adding 'length' to entity attribute definition:
@Column(columnDefinition="text", length=10485760)
private String configFileXml = "";
Best one is Axios library for fetching.
use npm i --save axios
for installng and use it like fetch, just write axios instead of fetch and then get response in then().
you can use as.matrix as below:
output <- as.matrix(z)
JSONP is a good option, but there is an easier way. You can simply set the Access-Control-Allow-Origin
header on your server. Setting it to *
will accept cross-domain AJAX requests from any domain. (https://developer.mozilla.org/en/http_access_control)
The method to do this will vary from language to language, of course. Here it is in Rails:
class HelloController < ApplicationController
def say_hello
headers['Access-Control-Allow-Origin'] = "*"
render text: "hello!"
end
end
In this example, the say_hello
action will accept AJAX requests from any domain and return a response of "hello!".
Here is an example of the headers it might return:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: text/html; charset=utf-8
X-Ua-Compatible: IE=Edge
Etag: "c4ca4238a0b923820dcc509a6f75849b"
X-Runtime: 0.913606
Content-Length: 6
Server: WEBrick/1.3.1 (Ruby/1.9.2/2011-07-09)
Date: Thu, 01 Mar 2012 20:44:28 GMT
Connection: Keep-Alive
Easy as it is, it does have some browser limitations. See http://caniuse.com/#feat=cors.
This is a simple fix. Open the project you are getting this error on. Click "Project" at the top. Then click " Properties" ( Will be the name of the opened project) then click "Security" then uncheck "Enable ClickOnce security settings."
That should fix everything.
It is possible to recover it if Git hasn't garbage collected yet.
Get an overview of dangling commits with fsck
:
$ git fsck --lost-found
dangling commit b72e67a9bb3f1fc1b64528bcce031af4f0d6fcbf
Recover the dangling commit with rebase:
$ git rebase b72e67a9bb3f1fc1b64528bcce031af4f0d6fcbf
You can do objects the JavaScript way... It makes no sense but it works ;)
>>> def FakeObject():
... def test():
... print "foo"
... FakeObject.test = test
... return FakeObject
>>> x = FakeObject()
>>> x.test()
foo
Seems to be identical just in case that SQL server will not try to read data which is not required for the query, the optimizer is clever enough
It can have sense when join on complex query (i.e which have joings, groupings etc itself) then, yes, it is better to specify required fields.
But there is one more point. If the query is simple there is no difference but EVERY extra action even which is supposed to improve performance makes optimizer works harder and optimizer can fail to get the best plan in time and will run not optimal query. So extras select can be a such action which can even decrease performance
Create a lookup table first:
morse = [None] * (ord('z') - ord('a') + 1)
for line in moreCodeFile:
morse[ord(line[0].lower()) - ord('a')] = line[2:]
Then convert using the table:
for ch in userInput:
print morse[ord(ch.lower()) - ord('a')]
May not be the best way, but elegant way.
Arrays.deepToString(Arrays.asList("Test", "Test2")
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
System.out.println(Arrays.deepToString(Arrays.asList("Test", "Test2").toArray()));
}
}
Output
[Test, Test2]
How to do it programatically :
To enable EditText use:
et.setEnabled(true);
To disable EditText use:
et.setEnabled(false);
Zamples is another site where you write a java code and run it online. Here you have possibility to choose jdk version also. http://www.zamples.com/JspExplorer/index.jsp?format=jdk16cl
I guess that what you want to do is an UNION
of both tables.
If both tables have the same columns then you can just do
SELECT category_id, col1, col2, col3
FROM items_a
UNION
SELECT category_id, col1, col2, col3
FROM items_b
Else, you might have to do something like
SELECT category_id, col1, col2, col3
FROM items_a
UNION
SELECT category_id, col_1 as col1, col_2 as col2, col_3 as col3
FROM items_b
There is a racecondition between the last command ($_) and last error ( $?) variables. If you try to store one of them in an own variable, both encountered new values already because of the set command. Actually, last command hasn't got any value at all in this case.
Here is what i did to store (nearly) both informations in own variables, so my bash script can determine if there was any error AND setting the title with the last run command:
# This construct is needed, because of a racecondition when trying to obtain
# both of last command and error. With this the information of last error is
# implied by the corresponding case while command is retrieved.
if [[ "${?}" == 0 && "${_}" != "" ]] ; then
# Last command MUST be retrieved first.
LASTCOMMAND="${_}" ;
RETURNSTATUS='?' ;
elif [[ "${?}" == 0 && "${_}" == "" ]] ; then
LASTCOMMAND='unknown' ;
RETURNSTATUS='?' ;
elif [[ "${?}" != 0 && "${_}" != "" ]] ; then
# Last command MUST be retrieved first.
LASTCOMMAND="${_}" ;
RETURNSTATUS='?' ;
# Fixme: "$?" not changing state until command executed.
elif [[ "${?}" != 0 && "${_}" == "" ]] ; then
LASTCOMMAND='unknown' ;
RETURNSTATUS='?' ;
# Fixme: "$?" not changing state until command executed.
fi
This script will retain the information, if an error occured and will obtain the last run command. Because of the racecondition i can not store the actual value. Besides, most commands actually don't even care for error noumbers, they just return something different from '0'. You'll notice that, if you use the errono extention of bash.
It should be possible with something like a "intern" script for bash, like in bash extention, but i'm not familiar with something like that and it wouldn't be compatible as well.
CORRECTION
I didn't think, that it was possible to retrieve both variables at the same time. Although i like the style of the code, i assumed it would be interpreted as two commands. This was wrong, so my answer devides down to:
# Because of a racecondition, both MUST be retrieved at the same time.
declare RETURNSTATUS="${?}" LASTCOMMAND="${_}" ;
if [[ "${RETURNSTATUS}" == 0 ]] ; then
declare RETURNSYMBOL='?' ;
else
declare RETURNSYMBOL='?' ;
fi
Although my post might not get any positive rating, i solved my problem myself, finally. And this seems appropriate regarding the intial post. :)
Combination of these two helped me. None of the other answers helped me since i had a sidenav that was not scrolling.
setTimeout(function () {
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
document.body.scrollTop = document.documentElement.scrollTop = 0;
}, 15);
You can also check Spire, it allow you to create HTML to PDF
with this simple piece of code
string htmlCode = "<p>This is a p tag</p>";
//use single thread to generate the pdf from above html code
Thread thread = new Thread(() =>
{ pdf.LoadFromHTML(htmlCode, false, setting, htmlLayoutFormat); });
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
// Save the file to PDF and preview it.
pdf.SaveToFile("output.pdf");
System.Diagnostics.Process.Start("output.pdf");
Detailed article : How to convert HTML to PDF in asp.net C#
AWS EC2 install running python34:
sudo yum install python34-devel
public class Toggle {
public static String toggle(String s) {
char[] ch = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
char charat = ch[i];
if (Character.isUpperCase(charat)) {
charat = Character.toLowerCase(charat);
} else
charat = Character.toUpperCase(charat);
System.out.print(charat);
}
return s;
}
public static void main(String[] args) {
toggle("DivYa");
}
}
Looks like python requests does not handle extremely large multi-part files.
The documentation recommends you look into requests-toolbelt
.
Here's the pertinent page from their documentation.
one of the easy way to do that is use landa function without any problem like
userControl_Material1.simpleButton4.Click += (s, ee) =>
{
Save_mat(mat_global);
};
you can use DateTime.ParseExact
with the format string
DateTime dt = DateTime.ParseExact(inputString, formatString, System.Globalization.CultureInfo.InvariantCulture);
Above will throw an exception if the given string not in given format.
use DateTime.TryParseExact
if you don't need exception in case of format incorrect but you can check the return value of that method to identify whether parsing value success or not.
I'm not aware of any way to programmatically create these URLs, but the existing username space (www.facebook.com/something) works on fb.me also (e.g. http://fb.me/facebook )
Make sure you have not committed a typo as in my case
msyql_fetch_assoc should be mysql
"For my project, I have to return data that has a timestamp of 5pm of a DateTime field, No matter what the date is."
So I think what you meant was that you needed the date, not the time. You can do something like this to get a date with 5:00 as the time:
SELECT CONVERT(VARCHAR(10), GetDate(), 110) + ' 05:00:00'
Ubuntu/Debian distros have the start-stop-daemon
tool which is for the same purpose you describe. See also /etc/init.d/skeleton to see how it is used in writing start/stop scripts.
-- Noah
I know this is an old one but even I found myself wandering past it again, so I thought I'd submit my own option here.
Best bet is to check out my blog post on this: Timing things in Objective-C: A stopwatch
Basically, I wrote a class that does stop watching in a very basic way but is encapsulated so that you only need to do the following:
[MMStopwatchARC start:@"My Timer"];
// your work here ...
[MMStopwatchARC stop:@"My Timer"];
And you end up with:
MyApp[4090:15203] -> Stopwatch: [My Timer] runtime: [0.029]
in the log...
Again, check out my post for a little more or download it here: MMStopwatch.zip
SELECT Email FROM Employee WHERE NOT REGEXP_LIKE(Email, ‘[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}’, ‘i’);
I finally found the answer to my problem. The solution is
function load_home() {
document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}
TimezoneDb provides a free API: http://timezonedb.com/api
GenoNames also has a RESTful API available to get the current time for a given location: http://www.geonames.org/export/ws-overview.html.
You can use Greenwich, UK if you'd like GMT.
The problem comes because of an interesting clash of new C++ features and what you're trying to do. First, let's take a look at the push_back
signature:
void push_back(const T&)
It's expecting a reference to an object of type T
. Under the old system of initialization, such a member exists. For example, the following code compiles just fine:
#include <vector>
class Foo {
public:
static const int MEMBER;
};
const int Foo::MEMBER = 1;
int main(){
std::vector<int> v;
v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER'
v.push_back( (int) Foo::MEMBER ); // OK
return 0;
}
This is because there is an actual object somewhere that has that value stored in it. If, however, you switch to the new method of specifying static const members, like you have above, Foo::MEMBER
is no longer an object. It is a constant, somewhat akin to:
#define MEMBER 1
But without the headaches of a preprocessor macro (and with type safety). That means that the vector, which is expecting a reference, can't get one.
After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.
Simple
<input type="text" />
<script>
$("input").focusin(function() {
alert("I am in Focus");
});
</script>
Sergio Carneiro's and Jon's implementation requires you to define an initializer function for all but one class. Here is a modified version of the aggregation function, which makes use of default parameters in the constructors instead. Included are also some comments by me.
var aggregation = (baseClass, ...mixins) => {
class base extends baseClass {
constructor (...args) {
super(...args);
mixins.forEach((mixin) => {
copyProps(this,(new mixin));
});
}
}
let copyProps = (target, source) => { // this function copies all properties and symbols, filtering out some special ones
Object.getOwnPropertyNames(source)
.concat(Object.getOwnPropertySymbols(source))
.forEach((prop) => {
if (!prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/))
Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop));
})
}
mixins.forEach((mixin) => { // outside contructor() to allow aggregation(A,B,C).staticFunction() to be called etc.
copyProps(base.prototype, mixin.prototype);
copyProps(base, mixin);
});
return base;
}
Here is a little demo:
class Person{
constructor(n){
this.name=n;
}
}
class Male{
constructor(s='male'){
this.sex=s;
}
}
class Child{
constructor(a=12){
this.age=a;
}
tellAge(){console.log(this.name+' is '+this.age+' years old.');}
}
class Boy extends aggregation(Person,Male,Child){}
var m = new Boy('Mike');
m.tellAge(); // Mike is 12 years old.
This aggregation function will prefer properties and methods of a class that appear later in the class list.
Perhaps the easiest way to see which extensions are (compiled and) loaded (not in cli) is to have a server run the following:
<?php
$ext = get_loaded_extensions();
asort($ext);
foreach ($ext as $ref) {
echo $ref . "\n";
}
PHP cli does not necessarily have the same extensions loaded.
AssertionError is an Unchecked Exception which rises explicitly by programmer or by API Developer to indicate that assert statement fails.
assert(x>10);
Output:
AssertionError
If x is not greater than 10 then you will get runtime exception saying AssertionError.
You'll want to use the formatting macros from inttypes.h.
See this question: Cross platform format string for variables of type size_t?
If your threads don't do I/O, synchronization, etc., and there's nothing else running, 1 thread per core will get you the best performance. However that very likely not the case. Adding more threads usually helps, but after some point, they cause some performance degradation.
Not long ago, I was doing performance testing on a 2 quad-core machine running an ASP.NET application on Mono under a pretty decent load. We played with the minimum and maximum number of threads and in the end we found out that for that particular application in that particular configuration the best throughput was somewhere between 36 and 40 threads. Anything outside those boundaries performed worse. Lesson learned? If I were you, I would test with different number of threads until you find the right number for your application.
One thing for sure: 4k threads will take longer. That's a lot of context switches.
ngOnInit()
is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.
ngAfterViewInit()
is called after a component's view, and its children's views, are created. Its a lifecycle hook that is called after a component's view has been fully initialized.
Use SimpleDateFormat for Android N and above. Use the calendar for earlier versions for example:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
fileName = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss").format(new Date());
Log.i("fileName before",fileName);
}else{
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH,1);
String zamanl =""+cal.get(Calendar.YEAR)+"-"+cal.get(Calendar.MONTH)+"-"+cal.get(Calendar.DAY_OF_MONTH)+"-"+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND);
fileName= zamanl;
Log.i("fileName after",fileName);
}
Output:
fileName before: 2019-04-12-07:14:47 // use SimpleDateFormat
fileName after: 2019-4-12-7:13:12 // use Calender
One can issue the SQL*Plus command SET TIMING ON
to get wall-clock times, but one can't take, for example, fetch time out of that trivially.
The AUTOTRACE setting, when used as SET AUTOTRACE TRACEONLY
will suppress output, but still perform all of the work to satisfy the query and send the results back to SQL*Plus, which will suppress it.
Lastly, one can trace the SQL*Plus session, and manually calculate the time spent waiting on events which are client waits, such as "SQL*Net message to client", "SQL*Net message from client".
The solution to solve this is to find out why you're getting the segmentation fault, and fix that.
To filter a list of dicts you can use the selectattr filter together with the equalto test:
network.addresses.private_man | selectattr("type", "equalto", "fixed")
The above requires Jinja2 v2.8 or later (regardless of Ansible version).
Ansible also has the tests match
and search
, which take regular expressions:
match
will require a complete match in the string, whilesearch
will require a match inside of the string.
network.addresses.private_man | selectattr("type", "match", "^fixed$")
To reduce the list of dicts to a list of strings, so you only get a list of the addr
fields, you can use the map filter:
... | map(attribute='addr') | list
Or if you want a comma separated string:
... | map(attribute='addr') | join(',')
Combined, it would look like this.
- debug: msg={{ network.addresses.private_man | selectattr("type", "equalto", "fixed") | map(attribute='addr') | join(',') }}
If you get the server response as a String, without using a third party library you can do
JSONObject json = new JSONObject(response);
JSONObject jsonResponse = json.getJSONObject("response");
String team = jsonResponse.getString("Team");
Here is the documentation
Otherwise to parse json you can use Gson or Jackson
EDIT without libraries (not tested)
class retrievedata extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
URL url;
try {
url = new URL("http://myurlhere.com");
urlConnection.setRequestMethod("GET"); //Your method here
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
buffer.append(line + "\n");
if (buffer.length() == 0)
return null;
return buffer.toString();
} catch (IOException e) {
Log.e(TAG, "IO Exception", e);
exception = e;
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
exception = e;
Log.e(TAG, "Error closing stream", e);
}
}
}
}
@Override
protected void onPostExecute(String response) {
if(response != null) {
JSONObject json = new JSONObject(response);
JSONObject jsonResponse = json.getJSONObject("response");
String team = jsonResponse.getString("Team");
}
}
}
for using this, you can create a Repository for example this one:
Member findByEmail(String email);
List<Member> findByDate(Date date);
// custom query example and return a member
@Query("select m from Member m where m.username = :username and m.password=:password")
Member findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
In Apache 2.4 the old access authorisation syntax has been deprecated and replaced by a new system using Require.
What you want then is something like the following:
<Directory "/labs/Projects/Nebula/">
Options All
AllowOverride All
<RequireAny>
Require local
Require ip 192.168.1
</RequireAny>
</Directory>
This will allow connections that originate either from the local host or from ip addresses that start with "192.168.1".
There is also a new module available that makes Apache 2.4 recognise the old syntax if you don't want to update your configuration right away:
sudo a2enmod access_compat
Leaflet also has LatLngBounds that even has an extend function, just like google maps.
http://leafletjs.com/reference.html#latlngbounds
So you could simply use:
var latlngbounds = new L.latLngBounds();
The rest is exactly the same.
Based on the C99 Specification: a == (a / b) * b + a % b
We can write a function to calculate (a % b) == a - (a / b) * b
!
int remainder(int a, int b)
{
return a - (a / b) * b;
}
For modulo operation, we can have the following function (assuming b > 0
)
int mod(int a, int b)
{
int r = a % b;
return r < 0 ? r + b : r;
}
My conclusion is that a % b
in C is a remainder operation and NOT a modulo operation.
python --version
Python 3.7.5
cd
into /usr/lib/python3/dist-packages
and check the apt_pkg.*
files. You will find that there is none for your default Python version:ll apt_pkg.*
apt_pkg.cpython-36m-x86_64-linux-gnu.so
sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.cpython-37m-x86_64- linux-gnu.so
Interestingly no one answered this. In TigerVNC, when you are logged into the session. Go to System > Preference > Display
from the top menu bar ( I was using Cent OS as my remote Server). Click on the resolution drop down, there are various settings available including 1080p. Select the one that you like. It will change on the fly.
Make sure you Apply the new setting when a dialog is prompted. Otherwise it will revert back to the previous setting just like in Windows
I've had the above solutions work for me on many occasions, except one; that was after I buggered up an alias file - ie a file that allows the website folder to be located in another location other than the www folder. Here's the solution:
The TextWatcher
interface has 3 callbacks methods which are all called in the following order when a change occurred to the text:
beforeTextChanged(CharSequence s, int start, int count, int after)
s
parameter is the text before any change is applied.start
parameter is the position of the beginning of the changed part in the text.count
parameter is the length of the changed part in the s
sequence since the start
position.after
parameter is the length of the new sequence which will replace the part of the s
sequence from start
to start+count
.TextView
from this method (by using myTextView.setText(String newText)
).onTextChanged(CharSequence s, int start, int before, int count)`
beforeTextChanged
method but called after the text changes.s
parameter is the text after changes have been applied.start
parameter is the same as in the beforeTextChanged
method.count
parameter is the after
parameter in the beforeTextChanged method.before
parameter is the count
parameter in the beforeTextChanged method.TextView
from this method (by using myTextView.setText(String newText)
).afterTextChanged(Editable s)
TextView
from this method.TextView
, the TextWatcher
will be triggered again, starting an infinite loop. You should then add like a boolean _ignore
property which prevent the infinite loop.new TextWatcher() {
boolean _ignore = false; // indicates if the change was made by the TextWatcher itself.
@Override
public void afterTextChanged(Editable s) {
if (_ignore)
return;
_ignore = true; // prevent infinite loop
// Change your text here.
// myTextView.setText(myNewText);
_ignore = false; // release, so the TextWatcher start to listen again.
}
// Other methods...
}
TextViewListener
Personally, I made my custom text listener, which gives me the 4 parts in separate strings, which is, for me, much more intuitive to use.
/**
* Text view listener which splits the update text event in four parts:
* <ul>
* <li>The text placed <b>before</b> the updated part.</li>
* <li>The <b>old</b> text in the updated part.</li>
* <li>The <b>new</b> text in the updated part.</li>
* <li>The text placed <b>after</b> the updated part.</li>
* </ul>
* Created by Jeremy B.
*/
public abstract class TextViewListener implements TextWatcher {
/**
* Unchanged sequence which is placed before the updated sequence.
*/
private String _before;
/**
* Updated sequence before the update.
*/
private String _old;
/**
* Updated sequence after the update.
*/
private String _new;
/**
* Unchanged sequence which is placed after the updated sequence.
*/
private String _after;
/**
* Indicates when changes are made from within the listener, should be omitted.
*/
private boolean _ignore = false;
@Override
public void beforeTextChanged(CharSequence sequence, int start, int count, int after) {
_before = sequence.subSequence(0,start).toString();
_old = sequence.subSequence(start, start+count).toString();
_after = sequence.subSequence(start+count, sequence.length()).toString();
}
@Override
public void onTextChanged(CharSequence sequence, int start, int before, int count) {
_new = sequence.subSequence(start, start+count).toString();
}
@Override
public void afterTextChanged(Editable sequence) {
if (_ignore)
return;
onTextChanged(_before, _old, _new, _after);
}
/**
* Triggered method when the text in the text view has changed.
* <br/>
* You can apply changes to the text view from this method
* with the condition to call {@link #startUpdates()} before any update,
* and to call {@link #endUpdates()} after them.
*
* @param before Unchanged part of the text placed before the updated part.
* @param old Old updated part of the text.
* @param aNew New updated part of the text?
* @param after Unchanged part of the text placed after the updated part.
*/
protected abstract void onTextChanged(String before, String old, String aNew, String after);
/**
* Call this method when you start to update the text view, so it stops listening to it and then prevent an infinite loop.
* @see #endUpdates()
*/
protected void startUpdates(){
_ignore = true;
}
/**
* Call this method when you finished to update the text view in order to restart to listen to it.
* @see #startUpdates()
*/
protected void endUpdates(){
_ignore = false;
}
}
Example:
myEditText.addTextChangedListener(new TextViewListener() {
@Override
protected void onTextChanged(String before, String old, String aNew, String after) {
// intuitive use of parameters
String completeOldText = before + old + after;
String completeNewText = before + aNew + after;
// update TextView
startUpdates(); // to prevent infinite loop.
myEditText.setText(myNewText);
endUpdates();
}
}
You can use this drawable xml and set as background to cardview :
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffffff"/>
<stroke android:width="1dp"
android:color="#ff000000"
/>
<padding android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
/>
<corners
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
I installed MariaDB on new computer, stopped Mysql service renamed data folder to data- I solved my problem copying just Mysql\data\table_folders and ibdata1 from crashed HD MySql data Folder to the new installed mysql data folder.
I Skipped ib_logfile0 and ib_logfile1 (otherwise the server did not start service)
Started mysql service.
Then server is running.
To answer your question: no, it's not possible to have multiple versions of IE (if that is what you meant) installed in a 'normal' way (i.e. not a hack, a sandbox or a VM etc). It's perfectly ok to have multiple browsers of different types installed on the same machine, such as IE8, Firefox 3 and Chrome all at once.
SandboxIE should allow you to install multiple versions of IE side-by-side (as well as other software), and this is less hassle than going down the virtual machine route.
However, from a QA point of view I'd strongly recommend installing different versions on different machines as the best option from a testing point of view. This will give you the most realistic testing environment. If you don't have the hardware for that, then virtual machines are the next best option as mentioned in some of the other answers.
Differences between an XML Schema Definition (XSD) and Document Type Definition (DTD) include:
Not all these bullet points are 100% accurate, but you get the gist.
On the other hand:
You can simply use This one line code to get date in year-month-date format
var date = new Date().getFullYear() + "-" + new Date().getMonth() + 1 + "-" + new Date().getDate();
Here's a function that accurately provides the number of months between 2 dates.
The default behavior only counts whole months, e.g. 3 months and 1 day will result in a difference of 3 months. You can prevent this by setting the roundUpFractionalMonths
param as true
, so a 3 month and 1 day difference will be returned as 4 months.
The accepted answer above (T.J. Crowder's answer) isn't accurate, it returns wrong values sometimes.
For example, monthDiff(new Date('Jul 01, 2015'), new Date('Aug 05, 2015'))
returns 0
which is obviously wrong. The correct difference is either 1 whole month or 2 months rounded-up.
Here's the function I wrote:
function getMonthsBetween(date1,date2,roundUpFractionalMonths)
{
//Months will be calculated between start and end dates.
//Make sure start date is less than end date.
//But remember if the difference should be negative.
var startDate=date1;
var endDate=date2;
var inverse=false;
if(date1>date2)
{
startDate=date2;
endDate=date1;
inverse=true;
}
//Calculate the differences between the start and end dates
var yearsDifference=endDate.getFullYear()-startDate.getFullYear();
var monthsDifference=endDate.getMonth()-startDate.getMonth();
var daysDifference=endDate.getDate()-startDate.getDate();
var monthCorrection=0;
//If roundUpFractionalMonths is true, check if an extra month needs to be added from rounding up.
//The difference is done by ceiling (round up), e.g. 3 months and 1 day will be 4 months.
if(roundUpFractionalMonths===true && daysDifference>0)
{
monthCorrection=1;
}
//If the day difference between the 2 months is negative, the last month is not a whole month.
else if(roundUpFractionalMonths!==true && daysDifference<0)
{
monthCorrection=-1;
}
return (inverse?-1:1)*(yearsDifference*12+monthsDifference+monthCorrection);
};
Lets say you have a datagridview that is not bound to a dataset and you want to programmatically populate new rows...
Here's how you do it.
// Create a new row first as it will include the columns you've created at design-time.
int rowId = dataGridView1.Rows.Add();
// Grab the new row!
DataGridViewRow row = dataGridView1.Rows[rowId];
// Add the data
row.Cells["Column1"].Value = "Value1";
row.Cells["Column2"].Value = "Value2";
// And that's it! Quick and painless... :o)
Using symfony 2.3 with php 5.5 and using the built in server with
app/console server:run
which should output something like:
Server running on http://127.0.0.1:8000
Quit the server with CONTROL-C.
then go to http://127.0.0.1:8000/app_dev.php/app/example
this should give you the default, which you can also find the default route by viewing src/AppBundle/Controller/DefaultController.php
In Python 3.6 the fastest way is still the WouterOvermeire one. Kikohs' proposal is slower than the other two options.
import timeit
setup = '''
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)
'''
timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500)
timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500)
timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500)
Results:
1.1214002349999777 s # WouterOvermeire
1.1922008498571748 s # Jeff
1.7034366211428602 s # Kikohs
Add this to your global.asax.cs:
protected void Application_PreSendRequestHeaders()
{
Response.Headers.Remove("Server");
Response.Headers.Remove("X-AspNet-Version");
Response.Headers.Remove("X-AspNetMvc-Version");
}
I encountered a rare edge case in cygwin, where I would get this error when doing exec('rsync');
somewhere before the query. Might be a general PHP problem, but I could only reproduce this in cygwin with rsync.
$pdo = new PDO('mysql:host=127.0.0.1;dbname=mysql', 'root');
var_dump($pdo->query('SELECT * FROM db'));
exec('rsync');
var_dump($pdo->query('SELECT * FROM db'));
produces
object(PDOStatement)#2 (1) {
["queryString"]=>
string(16) "SELECT * FROM db"
}
PHP Warning: Error while sending QUERY packet. PID=15036 in test.php on line 5
bool(false)
Bug reported in https://cygwin.com/ml/cygwin/2017-05/msg00272.html
This question has been answered before, but wanted to add another quick/easy workaround that might help other visitors to this question.
import seasborn as sns
sns.kdeplot(mydata1)
sns.kdeplot(mydata2)
Some helpful examples are here for kde vs histogram comparison.
The java application takes too long to respond(maybe due start-up/jvm being cold) thus you get the proxy error.
Proxy Error
The proxy server received an invalid response from an upstream server.
The proxy server could not handle the request GET /lin/Campaignn.jsp.
As Albert Maclang said amending the http timeout configuration may fix the issue. I suspect the java application throws a 500+ error thus the apache gateway error too. You should look in the logs.
When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.
Late to the party - here as a pure java solution for those when JNI is not an option.JTransforms
Try to update @angular/core
using ng update @angular/cli @angular/core
If you are looking for the last row of a column, use:
Sub SelectFirstColumn()
SelectEntireColumn (1)
End Sub
Sub SelectSecondColumn()
SelectEntireColumn (2)
End Sub
Sub SelectEntireColumn(columnNumber)
Dim LastRow
Sheets("sheet1").Select
LastRow = ActiveSheet.Columns(columnNumber).SpecialCells(xlLastCell).Row
ActiveSheet.Range(Cells(1, columnNumber), Cells(LastRow, columnNumber)).Select
End Sub
Other commands you will need to get familiar with are copy and paste commands:
Sub CopyOneToTwo()
SelectEntireColumn (1)
Selection.Copy
Sheets("sheet1").Select
ActiveSheet.Range("B1").PasteSpecial Paste:=xlPasteValues
End Sub
Finally, you can reference worksheets in other workbooks by using the following syntax:
Dim book2
Set book2 = Workbooks.Open("C:\book2.xls")
book2.Worksheets("sheet1")
Try this. Create a shortcut in startup folder and iuput
PowerShell "&.'PathToFile\script.ps1'"
This is the easiest way.
import pandas as pd
import io
texts = ['''\
id Name score isEnrolled Comment
111 Jack 2.17 True He was late to class
112 Nick 1.11 False Graduated
113 Zoe 4.12 True ''',
'''\
id Name score isEnrolled Comment
111 Jack 2.17 True He was late to class
112 Nick 1.21 False Graduated
113 Zoe 4.12 False On vacation''']
df1 = pd.read_fwf(io.StringIO(texts[0]), widths=[5,7,25,21,20])
df2 = pd.read_fwf(io.StringIO(texts[1]), widths=[5,7,25,21,20])
df = pd.concat([df1,df2])
print(df)
# id Name score isEnrolled Comment
# 0 111 Jack 2.17 True He was late to class
# 1 112 Nick 1.11 False Graduated
# 2 113 Zoe 4.12 True NaN
# 0 111 Jack 2.17 True He was late to class
# 1 112 Nick 1.21 False Graduated
# 2 113 Zoe 4.12 False On vacation
df.set_index(['id', 'Name'], inplace=True)
print(df)
# score isEnrolled Comment
# id Name
# 111 Jack 2.17 True He was late to class
# 112 Nick 1.11 False Graduated
# 113 Zoe 4.12 True NaN
# 111 Jack 2.17 True He was late to class
# 112 Nick 1.21 False Graduated
# 113 Zoe 4.12 False On vacation
def report_diff(x):
return x[0] if x[0] == x[1] else '{} | {}'.format(*x)
changes = df.groupby(level=['id', 'Name']).agg(report_diff)
print(changes)
prints
score isEnrolled Comment
id Name
111 Jack 2.17 True He was late to class
112 Nick 1.11 | 1.21 False Graduated
113 Zoe 4.12 True | False nan | On vacation
Just reference the System.Web assembly and then call: HttpServerUtility.HtmlEncode
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.htmlencode.aspx
As already mentioned, you will not receive a line break where there is a "no-break space".
Also be wary, that elements containing only a " " may show up incorrectly, where will work. In i.e. 6 at least (as far as I remember, IE7 has the same issue), if you have an empty table element, it will not apply styling, for example borders, to the element, if there is no content, or only white space. So the following will not be rendered with borders:
<td></td>
<td> <td>
Whereas the borders will show up in this example:
<td>& nbsp;</td>
Hmm -had to put in a dummy space to get it to render correctly here
Old Answer (July 2016):
You can't directly debug Chrome for iOS due to restrictions on the published WKWebView
apps, but there are a few options already discussed in other SO threads:
If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.
WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.
You could try and create a simple WKWebView
browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.
There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView
, Chrome for iOS would be debuggable.
Update January 2018:
Since my answer back in 2016, some work has been done to improve things.
There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.
Check out the getting started guide in the repo, which is quite detailed.
If you are interesting, you can read up on the background and architecture here.
I had the same error. It is solved by following steps
Go to IIS -> find your site -> right click on the site -> Manage Website -> Advanced Setting -> Check your physical path is correct or not.
If it is wrong, locate the correct path. This will solve issue.
You can use the date.js library:
http://code.google.com/p/datejs/
And just do this
Date.today().next().month();
You will have the exact value for today + 1 month (including days)
Valid answer from this thread was the right answer for my special case. Specify the ORM folder path for datanucleus certainly reduce the java path compile.
I was getting this error, only in Chrome (last version 24.0.1312.57 m), and only if the image was larger than the html img. I was using a php script to output the image like this:
header('Content-Length: '.strlen($data));
header("Content-type: image/{$ext}");
echo base64_decode($data);
I resolved it adding 1 to the lenght of the image:
header('Content-Length: '.strlen($data) + 1);
header("Content-type: image/{$ext}");
echo base64_decode($data);
Appears that Chrome dont expect the correct number of bytes.
Tested with sucess in Chrome and IE 9. Hope this help.
It must be here, because accepted answer from 2012
In 2018 and modern browsers you can send a custom event from iframe to parent window.
iframe:
var data = { foo: 'bar' }
var event = new CustomEvent('myCustomEvent', { detail: data })
window.parent.document.dispatchEvent(event)
parent:
window.document.addEventListener('myCustomEvent', handleEvent, false)
function handleEvent(e) {
console.log(e.detail) // outputs: {foo: 'bar'}
}
PS: Of course, you can send events in opposite direction same way.
document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)
I had a similar problem. In my case, I'm trying to use a web service on a apache server + django (the service was written by myself). I was having the same output as you: Chrome says it was cancelled while FF does it okay. If I tried to access the service directly on the the browser instead of ajax, it would work as well. Googling around, I found out that some newer versions of apache weren't setting the length of the response correctly in the response headers, so I did this manually. With django, all I had to do was:
response['Content-Length'] = len(content)
If you have control over the service you are trying to access, find out how to modify the response header in the platform you are using, otherwise you'd have to contact the service provider to fix this issue. Apparently, FF and many others browsers are able to handle this situation correctly, but Chrome designers decided to do it as specified.
Load environment variables from a file you create at runtime.
export MYVAR="my_var_outside"
cat > build/env.sh <<EOF
MYVAR=${MYVAR}
EOF
... then in the Dockerfile
ADD build /build
RUN /build/test.sh
where test.sh loads MYVAR from env.sh
#!/bin/bash
. /build/env.sh
echo $MYVAR > /tmp/testfile
Clearly a Cell cannot contain another cell as it becomes a never-ending recursion.
However a Cell CAN contain a pointer to another cell.
typedef struct Cell {
bool isParent;
struct Cell* child;
} Cell;
Your variable size
is declared as: float size;
You can't use a floating point variable as the size of an array - it needs to be an integer value.
You could cast it to convert to an integer:
float *temp = new float[(int)size];
Your other problem is likely because you're writing outside of the bounds of the array:
float *temp = new float[size];
//Getting input from the user
for (int x = 1; x <= size; x++){
cout << "Enter temperature " << x << ": ";
// cin >> temp[x];
// This should be:
cin >> temp[x - 1];
}
Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.
I attempted several suggestions under this thread and from my external searches but it was a whole other problem for me. My specific instruction to use an image indicated by the og:image tag was being overridden by the open graph tags supplied by the Jetpack plugin. you can find my detailed answer here. However, I thought it worth to add the steps in brief on this more-followed thread. Hope this helps someone.
The Facebook Sharing Debugger helped me identify the root cause and from there, I followed these steps:
It changes the default image used any time Jetpack can not determine an image to use
function custom_jetpack_default_image() {
return 'YOUR_IMAGE_URL';
}
add_filter( 'jetpack_open_graph_image_default', 'custom_jetpack_default_image' );
I should add that the image parameters such as minimum 300px x 200px and size < 300 KB are recommended. And please follow these instructions if such general instructions do not work for you, because, then it is most likely that your issue is similar to mine. Also, sometimes the simplest solution may just be to remove the plugin (provided you verify that you can do without it).
At the end you should be able to see something like -
Hope this helps.
NS
Many answers provided for this question. Just wanted to add one more which uses bashism-
#! /bin/bash
while read -r || [[ -n "$REPLY" ]]; do
[[ "$REPLY" =~ ^(-rwx|drwx).*[[:digit:]]+$ ]] && echo "Got one -> $REPLY"
done <"$1"
@kurumi answer for bash, which uses case is also correct but it will not read last line of file if there is no newline sequence at the end(Just save the file without pressing 'Enter/Return' at the last line).
If your id is incremental then use something like
delete from table where id < (select max(id) from table)-N
You cannot always make a branch or pull an existing branch and push back to it, because you are not registered as a collaborator for that specific project.
Forking is nothing more than a clone on the GitHub server side:
You keep a fork in sync with the original project by:
The rebase allows you to make sure your changes are straightforward (no merge conflict to handle), making your pulling request that more easy when you want the maintainer of the original project to include your patches in his project.
The goal is really to allow collaboration even though direct participation is not always possible.
The fact that you clone on the GitHub side means you have now two "central" repository ("central" as "visible from several collaborators).
If you can add them directly as collaborator for one project, you don't need to manage another one with a fork.
The merge experience would be about the same, but with an extra level of indirection (push first on the fork, then ask for a pull, with the risk of evolutions on the original repo making your fast-forward merges not fast-forward anymore).
That means the correct workflow is to git pull --rebase upstream
(rebase your work on top of new commits from upstream), and then git push --force origin
, in order to rewrite the history in such a way your own commits are always on top of the commits from the original (upstream) repo.
See also:
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (object item in row.ItemArray)
{
// read item
}
}
}
Or, if you need the column info:
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
object item = row[column];
// read column and item
}
}
}
You're not passing any credentials to sqlcmd.exe
So it's trying to authenticate you using the Windows Login credentials, but you mustn't have your SQL Server setup to accept those credentials...
When you were installing it, you would have had to supply a Server Admin password (for the sa
account)
Try...
sqlcmd.exe -U sa -P YOUR_PASSWORD -S ".\SQL2008"
for reference, theres more details here...
Come, let us recurse together.
def locations_of_substring(string, substring):
"""Return a list of locations of a substring."""
substring_length = len(substring)
def recurse(locations_found, start):
location = string.find(substring, start)
if location != -1:
return recurse(locations_found + [location], location+substring_length)
else:
return locations_found
return recurse([], 0)
print(locations_of_substring('this is a test for finding this and this', 'this'))
# prints [0, 27, 36]
No need for regular expressions this way.
Try using white-space: nowrap;
in the container style (instead of overflow: hidden;
)
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
Put " DB_HOST " instead of " DB_SERVER " also
put " DB_USER " Instead of " DB_USERNAME "
than it working fine !
You need to use %2.6f
instead of %f
in your printf statement
In case if you are using node js, then this could be the possible solution
const express = require("express");
const app = express();
const server = app.listen(8080);
server.keepAliveTimeout = 61 * 1000;
1) File -> Invalide Caches (in IDE IDEA)
2) Manually, got to C:\Users\\AppData\Local\JetBrains\IntelliJ IDEA \system\caches and delete
To further jfriend00's answer (I dont't have enough points to comment) I have extended his/her answer to the following:
function log(args) {_x000D_
var str = "";_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
if (typeof arguments[i] === "object") {_x000D_
str += JSON.stringify(arguments[i]);_x000D_
} else {_x000D_
str += arguments[i];_x000D_
}_x000D_
}_x000D_
var div = document.createElement("div");_x000D_
div.innerHTML = str;_x000D_
document.body.appendChild(div);_x000D_
}_x000D_
_x000D_
Number.prototype.addCommas = function (str) {_x000D_
if (str === undefined) {_x000D_
str = this;_x000D_
}_x000D_
_x000D_
var parts = (str + "").split("."),_x000D_
main = parts[0],_x000D_
len = main.length,_x000D_
output = "",_x000D_
first = main.charAt(0),_x000D_
i;_x000D_
_x000D_
if (first === '-') {_x000D_
main = main.slice(1);_x000D_
len = main.length; _x000D_
} else {_x000D_
first = "";_x000D_
}_x000D_
i = len - 1;_x000D_
while(i >= 0) {_x000D_
output = main.charAt(i) + output;_x000D_
if ((len - i) % 3 === 0 && i > 0) {_x000D_
output = "," + output;_x000D_
}_x000D_
--i;_x000D_
}_x000D_
// put sign back_x000D_
output = first + output;_x000D_
// put decimal part back_x000D_
if (parts.length > 1) {_x000D_
output += "." + parts[1];_x000D_
}_x000D_
return output;_x000D_
}_x000D_
_x000D_
var testCases = [_x000D_
1, 12, 123, -1234, 12345, 123456, -1234567, 12345678, 123456789,_x000D_
-1.1, 12.1, 123.1, 1234.1, -12345.1, -123456.1, -1234567.1, 12345678.1, 123456789.1_x000D_
];_x000D_
_x000D_
for (var i = 0; i < testCases.length; i++) {_x000D_
log(testCases[i].addCommas());_x000D_
}_x000D_
_x000D_
/*for (var i = 0; i < testCases.length; i++) {_x000D_
log(Number.addCommas(testCases[i]));_x000D_
}*/
_x000D_
fwiw, this didn't work for me until I had this in the ajax call:
contentType: "application/json; charset=utf-8",
using Asp.Net MVC 4.
A command like the one below will show three sections: request headers, response headers and data (separated by CRLF). It avoids technical information and syntactical noise added by curl.
curl -vs www.stackoverflow.com 2>&1 | sed '/^* /d; /bytes data]$/d; s/> //; s/< //'
The command will produce the following output:
GET / HTTP/1.1
Host: www.stackoverflow.com
User-Agent: curl/7.54.0
Accept: */*
HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=UTF-8
Location: https://stackoverflow.com/
Content-Length: 149
Accept-Ranges: bytes
Date: Wed, 16 Jan 2019 20:28:56 GMT
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: cache-bma1622-BMA
X-Cache: MISS
X-Cache-Hits: 0
X-Timer: S1547670537.588756,VS0,VE105
Vary: Fastly-SSL
X-DNS-Prefetch-Control: off
Set-Cookie: prov=e4b211f7-ae13-dad3-9720-167742a5dff8; domain=.stackoverflow.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly
<head><title>Document Moved</title></head>
<body><h1>Object Moved</h1>This document may be found <a HREF="https://stackoverflow.com/">here</a></body>
Description:
-vs
- add headers (-v) but remove progress bar (-s)2>&1
- combine stdout and stderr into single stdoutsed
- edit response produced by curl using the commands below/^* /d
- remove lines starting with '* ' (technical info)/bytes data]$/d
- remove lines ending with 'bytes data]' (technical info)s/> //
- remove '> ' prefixs/< //
- remove '< ' prefixThe <ul>
element has browser inherent padding & margin by default. In your case, Use
#footer ul {
margin: 0; /* To remove default bottom margin */
padding: 0; /* To remove default left padding */
}
or a CSS browser reset ( https://cssreset.com/ ) to deal with this.
Technically the answer of zlovelady is preferable, but as I had only to remove items from the navigation, the approach of unsetting the not-needed navigation items in the template was the fastest/easiest way for me:
Just duplicate
app/design/frontend/base/default/template/customer/account/navigation
to
app/design/frontend/YOUR_THEME/default/template/customer/account/navigation
and unset the unneeded navigation items before the get rendered, e.g.:
<?php $_links = $this->getLinks(); ?>
<?php
unset($_links['recurring_profiles']);
?>
Another solution using essentially a dilate operator:
import numpy as np
from scipy.ndimage import rank_filter
def find_local_maxima(x):
x_dilate = rank_filter(x, -1, size=3)
return x_dilate == x
and for the minima:
def find_local_minima(x):
x_erode = rank_filter(x, -0, size=3)
return x_erode == x
Also, from scipy.ndimage
you can replace rank_filter(x, -1, size=3)
with grey_dilation
and rank_filter(x, 0, size=3)
with grey_erosion
. This won't require a local sort, so it is slightly faster.
I do it as Pekka says. Put an inline style on each <li>
:
style="border-right: solid 1px #555; border-left: solid 1px #111;"
Take off first and last as appropriate.
Thanks!
But then it was not working for the Google Chrome and Safari browsers (stretching worked, but the hight of the pictures was only 2 mm!), until someone told me what lacks:
Try to set
height:auto;min-height:100%;
So change that for your height:100%;
line, gives:
#### #background {
width: 100%;
height: 100%;
position: fixed;
left: 0px;
top: 0px;
z-index: -1;
}
.stretch {
width:100%;
height:auto;
min-height:100%;
}
Just before that newly added code I have this in my Drupal Tendu themes style.css
:
html, body{height:100%;}
#page{background:#ffffff; height:auto !important;height:100%;min-height:100%;position:relative;}
Then I have to make a new block within Drupal with the picture while adding class=stretch
:
< img alt="" class="stretch" src="pic.url" />
Just copying a picture with the editor in that Drupal block doesn't work; one has to change the editor to non-formatted text.
If you want to be secure use this:<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Combine the answers of RooiWillie and MohD
and remember to run your app with administrative right.
var appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe";
RegistryKey Regkey = null;
try
{
int BrowserVer, RegVal;
// get the installed IE version
using (WebBrowser Wb = new WebBrowser())
BrowserVer = Wb.Version.Major;
// set the appropriate IE version
if (BrowserVer >= 11)
RegVal = 11001;
else if (BrowserVer == 10)
RegVal = 10001;
else if (BrowserVer == 9)
RegVal = 9999;
else if (BrowserVer == 8)
RegVal = 8888;
else
RegVal = 7000;
//For 64 bit Machine
if (Environment.Is64BitOperatingSystem)
Regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
else //For 32 bit Machine
Regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
//If the path is not correct or
//If user't have priviledges to access registry
if (Regkey == null)
{
MessageBox.Show("Registry Key for setting IE WebBrowser Rendering Address Not found. Try run the program with administrator's right.");
return;
}
string FindAppkey = Convert.ToString(Regkey.GetValue(appName));
//Check if key is already present
if (FindAppkey == RegVal.ToString())
{
Regkey.Close();
return;
}
Regkey.SetValue(appName, RegVal, RegistryValueKind.DWord);
}
catch (Exception ex)
{
MessageBox.Show("Registry Key for setting IE WebBrowser Rendering failed to setup");
MessageBox.Show(ex.Message);
}
finally
{
//Close the Registry
if (Regkey != null)
Regkey.Close();
}
Assuming you want the part between single quotes, use this regular expression with a Matcher
:
"'(.*?)'"
Example:
String mydata = "some string with 'the data i want' inside";
Pattern pattern = Pattern.compile("'(.*?)'");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find())
{
System.out.println(matcher.group(1));
}
Result:
the data i want
The documentation says:
class (Optional) String
One or more CSS classes to remove from the elements, these are separated by spaces.
Example:
Remove the class 'blue' and 'under' from the matched elements.
$("p:odd").removeClass("blue under");
You could do this:
String strz[] = strs.toArray(String[strs.size()]);
String theFirstOne = strz[0];
The javadoc for Collection gives the following caveat wrt ordering of the elements of the array:
If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.
For me I forgot default
. So I wrote export class MyComponent
instead of export default class MyComponent
For the newer versions use:
var datatable = $('#table').dataTable().api();
$.get('myUrl', function(newDataArray) {
datatable.clear();
datatable.rows.add(newDataArray);
datatable.draw();
});
Taken from: https://stackoverflow.com/a/27781459/4059810
It's available in the HTTP referer
header. You can get it in a servlet as follows:
String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.
You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.
For the interested, background about the misspelling can be found in Wikipedia.
If you want to keep your version same like rails will be 2.3.8 and gem version will be latest. You can use this solution Latest gem with Rails2.x. in this some changes in boot.rb file and environment.rb file.
require 'thread
' in boot.rb file at the top.
and in environment.rb file add the following code above the initializer block.
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.3.7')
module Rails
class GemDependency
def requirement
r = super
(r == Gem::Requirement.default) ? nil : r
end
end
end
end
The quick answer is to use the .Split('\\') method.
As per PEP-20 by Tim Peters, "Explicit is better than implicit" and "Readability counts". If all you need from the os
module is under os.path
, import os.path
would be more explicit and let others know what you really care about.
Likewise, PEP-20 also says "Simple is better than complex", so if you also need stuff that resides under the more-general os
umbrella, import os
would be preferred.
There are two different methods for iPad and iPhone platforms, so you need to implement both:
segue.
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
// Selection handler (for horizontal iPad)
[self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
// Segue (for iPhone and vertical iPad)
[self performSegueWithIdentifier:"showDetail" sender:self];
In my case, I was using MySQL WorkBench and
ALTER TABLE table_name RENAME COLUMN old_name new_name varchar(50) not null;
// without TO and specify data type of that column
was enough to change the column name!
The json.load() method (without "s" in "load") can read a file directly:
import json
with open('strings.json') as f:
d = json.load(f)
print(d)
json.loads() method, which is used for string arguments only.
import json
person = '{"name": "Bob", "languages": ["English", "Fench"]}'
print(type(person))
# Output : <type 'str'>
person_dict = json.loads(person)
print( person_dict)
# Output: {'name': 'Bob', 'languages': ['English', 'Fench']}
print(type(person_dict))
# Output : <type 'dict'>
Here , we can see after using loads() takes a string ( type(str) ) as a input and return dictionary.
The Bitwise complement operator(~) is a unary operator.
It works as per the following methods
First it converts the given decimal number to its corresponding binary value.That is in case of 2 it first convert 2 to 0000 0010 (to 8 bit binary number).
Then it converts all the 1 in the number to 0,and all the zeros to 1;then the number will become 1111 1101.
that is the 2's complement representation of -3.
In order to find the unsigned value using complement,i.e. simply to convert 1111 1101 to decimal (=4294967293) we can simply use the %u during printing.
In order to just download updates:
git fetch origin master
However, this just updates a reference called origin/master
. The best way to update your local master
would be the checkout/merge mentioned in another comment. If you can guarantee that your local master
has not diverged from the main trunk that origin/master
is on, you could use git update-ref
to map your current master
to the new point, but that's probably not the best solution to be using on a regular basis...
I encounter some issue in my project.
In child table, there isn't any record Id equals 1 and 11
I inserted DEAL_ITEM_THIRD_PARTY_PO table which Id equals 1 and 11 then I can create FK
You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.
You can get the Java EE Edition of eclipse with has it pre-installed.
To create and run your first servlet:
doGet()
method.That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.
1) It looks possible. This info on Github describes how to create a java program to send a message using the whatsapp encryption protocol from WhisperSystems.
2) No. See the whatsapp security white paper.
3) See #1.
You can also get this if you mix org.junit and org.junit.jupiter annotations inadvertently.
Maybe this is a no-brainer for the xslt-professional, but for me at beginner/intermediate level, this got me puzzled. I wanted to do exactly the same thing, but I had to test a responsetime value from an xml instead of a plain number. Following this thread, I tried this:
<xsl:when test="responsetime/@value >= 5000 and responsetime/@value <= 8999">
which generated an error. This works:
<xsl:when test="number(responsetime/@value) >= 5000 and number(responsetime/@value) <= 8999">
Don't really understand why it doesn't work without number(), though. Could it be that without number() the value is treated as a string and you can't compare numbers with a string?
Anyway, hope this saves someone a lot of searching...
When you have this problem with Chrome, you don't need an Extension.
Start Chrome from the Console:
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Maybe you have to close all Tabs in Chrome and restart it.
Incorrect:
SELECT * FROM customers WHERE name LIKE '%Bob Smith%';
Instead:
select count(*)
from rearp.customers c
where c.name LIKE '%Bob smith.8%';
select count
will just query (totals)
C
will link the db.table to the names row you need this to index
LIKE
should be obvs
8
will call all references in DB 8 or less (not really needed but i like neatness)
In docs.python.org Topic = 5.6.2. String Formatting Operations http://docs.python.org/library/stdtypes.html#string-formatting then further down to the chart (text above chart is "The conversion types are:")
My comment: help does not include attitude which is a bonus. The attitude post enabled me to search further and find the info.
A String is an immutable type. This means that whenever you start concatenating strings with each other you're creating new strings each time. If you do so many times you end up with a lot of heap overhead and the risk of running out of memory.
A StringBuilder instance is used to be able to append strings to the same instance, creating a string when you call the ToString method on it.
Due to the overhead of instantiating a StringBuilder object it's said by Microsoft that it's useful to use when you have more than 5-10 string concatenations.
For sample code I suggest you take a look here:
I have google search many ways to import csv to mysql, include " load data infile ", use mysql workbench, etc.
when I use mysql workbench import button, first you need to create the empty table on your own, set each column type on your own. Note: you have to add ID column at the end as primary key and not null and auto_increment, otherwise, the import button will not visible at later. However, when I start load CSV file, nothing loaded, seems like a bug. I give up.
Lucky, the best easy way so far I found is to use Oracle's mysql for excel. you can download it from here mysql for excel
This is what you are going to do: open csv file in excel, at Data tab, find mysql for excel button
select all data, click export to mysql. Note to set a ID column as primary key.
when finished, go to mysql workbench to alter the table, such as currency type should be decimal(19,4) for large amount decimal(10,2) for regular use. other field type may be set to varchar(255).
Are you working in an N-Tiered project? If so, try rebuilding your Data Layer (or wherever your EDMX file is stored) before using it.
What you want to do is a combination of part of 1 and all of 2.
You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.
But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.
From the javadoc:
Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.
The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.
Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
class ClassWithStatics {
public static String getString() {
return "String";
}
public static int getInt() {
return 1;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
@Test
public void test() {
PowerMockito.mockStatic(ClassWithStatics.class);
when(ClassWithStatics.getString()).thenReturn("Hello!");
System.out.println("String: " + ClassWithStatics.getString());
System.out.println("Int: " + ClassWithStatics.getInt());
}
}
The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.
html { overflow-y: scroll; }
This css
rule causes a vertical scrollbar to always appear.
Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/
check the formats here http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
main
System.out.println("date : " + new classname().getMyDate("2014-01-09 14:06", "dd-MMM-yyyy E hh:mm a z", "yyyy-MM-dd HH:mm"));
method
public String getMyDate(String myDate, String returnFormat, String myFormat)
{
DateFormat dateFormat = new SimpleDateFormat(returnFormat);
Date date=null;
String returnValue="";
try {
date = new SimpleDateFormat(myFormat, Locale.ENGLISH).parse(myDate);
returnValue = dateFormat.format(date);
} catch (ParseException e) {
returnValue= myDate;
System.out.println("failed");
e.printStackTrace();
}
return returnValue;
}
Your URL should be jdbc:sqlserver://server:port;DatabaseName=dbname
and Class name should be like com.microsoft.sqlserver.jdbc.SQLServerDriver
Use MicrosoftSQL Server JDBC Driver 2.0
The best way is to use layers insted of views:
AVPlayer *player = [AVPlayer playerWithURL:[NSURL url...]]; //
AVPlayerLayer *layer = [AVPlayerLayer layer];
[layer setPlayer:player];
[layer setFrame:CGRectMake(10, 10, 300, 200)];
[layer setBackgroundColor:[UIColor redColor].CGColor];
[layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[self.view.layer addSublayer:layer];
[player play];
Don't forget to add frameworks:
#import <QuartzCore/QuartzCore.h>
#import "AVFoundation/AVFoundation.h"
logrotate -d [your_config_file]
invokes debug mode, giving you a verbose description of what would happen, but leaving the log files untouched.
For MacOS (High Sierra), MySQL that has been installed with home brew.
Increasing the global variables from mysql environment was not successful. So in that case creating of ~/.my.cnf is the safest option. Adding variables with [mysqld] will include the changes (Note: if you change with [mysql] , the change might not work).
<~/.my.cnf> [mysqld] connect_timeout = 43200 max_allowed_packet = 2048M net_buffer_length = 512M
Restart the mysql server. and check the variables. y
sql> SELECT @@max_allowed_packet; +----------------------+ | @@max_allowed_packet | +----------------------+ | 1073741824 | +----------------------+
1 row in set (0.00 sec)
May this code help you. It works in my case.
$filename = "D:\xampp\htdocs\wordpress/wp-content/uploads/json/2018-10-25.json";
$fileUrl = "http://localhost/wordpress/wp-content/uploads/json/2018-10-25.json";
if(!file_exists($filename)):
$handle = fopen( $filename, 'a' ) or die( 'Cannot open file: ' . $fileUrl ); //implicitly creates file
fwrite( $handle, json_encode(array()));
fclose( $handle );
endif;
$response = file_get_contents($filename);
$tempArray = json_decode($response);
if(!empty($tempArray)):
$count = count($tempArray) + 1;
else:
$count = 1;
endif;
$tempArray[] = array_merge(array("sn." => $count), $data);
$jsonData = json_encode($tempArray);
file_put_contents($filename, $jsonData);
similar to KNaito's answer, the following does the trick for me
function simulateClick() {
var event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
var cb = document.getElementById('player');
var canceled = !cb.dispatchEvent(event);
if (canceled) {
// A handler called preventDefault.
alert("canceled");
} else {
// None of the handlers called preventDefault.
alert("not canceled");
}
}
Once you are in terminal/command line, access the database/collection you want to use as follows:
show dbs
use <db name>
show collections
choose your collection and type the following to see all contents of that collection:
db.collectionName.find()
More info here on the MongoDB Quick Reference Guide.
The new HTTP Client shipped with Java 9 but as part of an Incubator module named
jdk.incubator.httpclient
. Incubator modules are a means of putting non-final APIs in the hands of developers while the APIs progress towards either finalization or removal in a future release.
In Java 9, you can send a GET
request like:
// GET
HttpResponse response = HttpRequest
.create(new URI("http://www.stackoverflow.com"))
.headers("Foo", "foovalue", "Bar", "barvalue")
.GET()
.response();
Then you can examine the returned HttpResponse
:
int statusCode = response.statusCode();
String responseBody = response.body(HttpResponse.asString());
Since this new HTTP Client is in java.httpclient
jdk.incubator.httpclient
module, you should declare this dependency in your module-info.java
file:
module com.foo.bar {
requires jdk.incubator.httpclient;
}
As Peter and Amro illustrate, you have to convert numeric values to formatted strings first in order to display them or concatenate them with other character strings. You can do this using the functions FPRINTF, SPRINTF, NUM2STR, and INT2STR.
With respect to getting ans = 3
as an output, it is probably because you are not assigning the output from answer
to a variable. If you want to get all of the output values, you will have to call answer
in the following way:
[out1,out2,out3] = answer(1,2);
This will place the value d
in out1
, the value e
in out2
, and the value f
in out3
. When you do the following:
answer(1,2)
MATLAB will automatically assign the first output d
(which has the value 3 in this case) to the default workspace variable ans
.
With respect to suggesting a good resource for learning MATLAB, you shouldn't underestimate the value of the MATLAB documentation. I've learned most of what I know on my own using it. You can access it online, or within your copy of MATLAB using the functions DOC, HELP, or HELPWIN.
paulsm4's answer is the correct one. If in onBackPressed()
you just return, it will disable the back button. However, I think a better approach given your use case is to flip the activity logic, i.e. make your home activity the main one, check if the user is signed in there, if not, start the sign in activity. The reason is that if you override the back button in your main activity, most users will be confused when they press back and your app does nothing.
If you are forced to use that List, or if your program has a structure like
then Thilos answer will be the best way to do it. If you combine it with the advice from Tom Hawtin - tackline, you get:
java.util.Collections.sort(listOfCountryNames, Collator.getInstance());
If you are free to decide, and if your application might get more complex, then you might change your code to use a TreeSet instead. This kind of collection sorts your entries just when they are inserted. No need to call sort().
Collection<String> countryNames =
new TreeSet<String>(Collator.getInstance());
countryNames.add("UK");
countryNames.add("Germany");
countryNames.add("Australia");
// Tada... sorted.
This has some subtle, but important advantages:
TreeSet<String> countyNames
and instantly knows: this is a sorted collection of Strings without duplicates, and I can be sure that this is true at every moment. So much information in a short declaration.Using the right collection for the right task is a key to write short and bug free code. It's not as demonstrative in this case, because you just save one line. But I've stopped counting how often I see someone using a List when they want to ensure there are no duplictes, and then build that functionality themselves. Or even worse, using two Lists when you really need a Map.
Don't get me wrong: Using Collections.sort is not an error or a flaw. But there are many cases when the TreeSet is much cleaner.
Yeah, for most cases, you don't need to create a class with getters and setters. Just create a new Dictionary and bind it to the data source. Here's an example in VB using a for loop to set the DisplayMember and ValueMember of a combo box from a list:
Dim comboSource As New Dictionary(Of String, String)()
cboMenu.Items.Clear()
For I = 0 To SomeList.GetUpperBound(0)
comboSource.Add(SomeList(I).Prop1, SomeList(I).Prop2)
Next I
cboMenu.DataSource = New BindingSource(comboSource, Nothing)
cboMenu.DisplayMember = "Value"
cboMenu.ValueMember = "Key"
Then you can set up a data grid view's rows according to the value or whatever you need by calling a method on click:
Private Sub cboMenu_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMenu.SelectionChangeCommitted
SetListGrid(cboManufMenu.SelectedValue)
End Sub
If the modulus of the given number is equal to zero, the number is even else odd number. Below is the method that does that:
public void evenOrOddNumber(int number) {
if (number % 2 == 0) {
System.out.println("Number is Even");
} else {
System.out.println("Number is odd");
}
}
(windows specific solution) The current (circa 2017) way to get accurate timings under windows is to use "QueryPerformanceCounter". This approach has the benefit of giving very accurate results and is recommended by MS. Just plop the code blob into a new console app to get a working sample. There is a lengthy discussion here: Acquiring High resolution time stamps
#include <iostream>
#include <tchar.h>
#include <windows.h>
int main()
{
constexpr int MAX_ITER{ 10000 };
constexpr __int64 us_per_hour{ 3600000000ull }; // 3.6e+09
constexpr __int64 us_per_min{ 60000000ull };
constexpr __int64 us_per_sec{ 1000000ull };
constexpr __int64 us_per_ms{ 1000ull };
// easy to work with
__int64 startTick, endTick, ticksPerSecond, totalTicks = 0ull;
QueryPerformanceFrequency((LARGE_INTEGER *)&ticksPerSecond);
for (int iter = 0; iter < MAX_ITER; ++iter) {// start looping
QueryPerformanceCounter((LARGE_INTEGER *)&startTick); // Get start tick
// code to be timed
std::cout << "cur_tick = " << iter << "\n";
QueryPerformanceCounter((LARGE_INTEGER *)&endTick); // Get end tick
totalTicks += endTick - startTick; // accumulate time taken
}
// convert to elapsed microseconds
__int64 totalMicroSeconds = (totalTicks * 1000000ull)/ ticksPerSecond;
__int64 hours = totalMicroSeconds / us_per_hour;
totalMicroSeconds %= us_per_hour;
__int64 minutes = totalMicroSeconds / us_per_min;
totalMicroSeconds %= us_per_min;
__int64 seconds = totalMicroSeconds / us_per_sec;
totalMicroSeconds %= us_per_sec;
__int64 milliseconds = totalMicroSeconds / us_per_ms;
totalMicroSeconds %= us_per_ms;
std::cout << "Total time: " << hours << "h ";
std::cout << minutes << "m " << seconds << "s " << milliseconds << "ms ";
std::cout << totalMicroSeconds << "us\n";
return 0;
}
By issuing this statement:
ALTER TABLES call MODIFY incoming_Cid CHAR;
... you omitted the length parameter. Your query was therefore equivalent to:
ALTER TABLE calls MODIFY incoming_Cid CHAR(1);
You must specify the field size for sizes larger than 1:
ALTER TABLE calls MODIFY incoming_Cid CHAR(34);
The .NET projects are always recompiled regardless. Part of this is to keep the IDE up to date (such as IntelliSense). I remember asking this question on an Microsoft forum years ago, and this was the answer I was given.
You can use convert
from hablar
to change a column of the data frame quickly.
library(tidyverse)
library(hablar)
x <- tibble(var = c(1.34, 4.45, 6.98))
x %>%
convert(int(var))
gives you:
# A tibble: 3 x 1
var
<int>
1 1
2 4
3 6
You should have a Data/Packages
folder in your Sublime Text 2 install directory.
All you need to do is download the plugin and put the plugin folder in the Packages
folder.
Or, an easier way would be to install the Package Control Plugin
by wbond.
Just go here: https://sublime.wbond.net/installation
and follow the install instructions.
Once you are done you can use the Ctrl + Shift + P shortcut in Sublime, type in install and press enter, then search for emmet
.
EDIT: You can now also press Ctrl + Shift + P right away and use the command 'Install Package Control' instead of following the install instructions. (Tested on Build 3126)
Even though I had gcc already installed, I had to run
sudo apt-get install build-essential
to get rid of that error
This is the first working version of what will be a GPS reader and data presenter. tkinter is a very fragile thing with way too few error messages. It does not put stuff up and does not tell why much of the time. Very difficult coming from a good WYSIWYG form developer. Anyway, this runs a small routine 10 times a second and presents the information on a form. Took a while to make it happen. When I tried a timer value of 0, the form never came up. My head now hurts! 10 or more times per second is good enough for me. I hope it helps someone else. Mike Morrow
import tkinter as tk
import time
def GetDateTime():
# Get current date and time in ISO8601
# https://en.wikipedia.org/wiki/ISO_8601
# https://xkcd.com/1179/
return (time.strftime("%Y%m%d", time.gmtime()),
time.strftime("%H%M%S", time.gmtime()),
time.strftime("%Y%m%d", time.localtime()),
time.strftime("%H%M%S", time.localtime()))
class Application(tk.Frame):
def __init__(self, master):
fontsize = 12
textwidth = 9
tk.Frame.__init__(self, master)
self.pack()
tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
text='Local Time').grid(row=0, column=0)
self.LocalDate = tk.StringVar()
self.LocalDate.set('waiting...')
tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
textvariable=self.LocalDate).grid(row=0, column=1)
tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
text='Local Date').grid(row=1, column=0)
self.LocalTime = tk.StringVar()
self.LocalTime.set('waiting...')
tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
textvariable=self.LocalTime).grid(row=1, column=1)
tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
text='GMT Time').grid(row=2, column=0)
self.nowGdate = tk.StringVar()
self.nowGdate.set('waiting...')
tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
textvariable=self.nowGdate).grid(row=2, column=1)
tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
text='GMT Date').grid(row=3, column=0)
self.nowGtime = tk.StringVar()
self.nowGtime.set('waiting...')
tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
textvariable=self.nowGtime).grid(row=3, column=1)
tk.Button(self, text='Exit', width = 10, bg = '#FF8080', command=root.destroy).grid(row=4, columnspan=2)
self.gettime()
pass
def gettime(self):
gdt, gtm, ldt, ltm = GetDateTime()
gdt = gdt[0:4] + '/' + gdt[4:6] + '/' + gdt[6:8]
gtm = gtm[0:2] + ':' + gtm[2:4] + ':' + gtm[4:6] + ' Z'
ldt = ldt[0:4] + '/' + ldt[4:6] + '/' + ldt[6:8]
ltm = ltm[0:2] + ':' + ltm[2:4] + ':' + ltm[4:6]
self.nowGtime.set(gdt)
self.nowGdate.set(gtm)
self.LocalTime.set(ldt)
self.LocalDate.set(ltm)
self.after(100, self.gettime)
#print (ltm) # Prove it is running this and the external code, too.
pass
root = tk.Tk()
root.wm_title('Temp Converter')
app = Application(master=root)
w = 200 # width for the Tk root
h = 125 # height for the Tk root
# get display screen width and height
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen
# calculate x and y coordinates for positioning the Tk root window
#centered
#x = (ws/2) - (w/2)
#y = (hs/2) - (h/2)
#right bottom corner (misfires in Win10 putting it too low. OK in Ubuntu)
x = ws - w
y = hs - h - 35 # -35 fixes it, more or less, for Win10
#set the dimensions of the screen and where it is placed
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
root.mainloop()
Here's another using the zip
function.
>>> a = [3, 7, 19]
>>> zip(range(len(a)), a)
[(0, 3), (1, 7), (2, 19)]
I realise I'm a litle late to the game, but just spent over a day on trying to change the timeout of a webservice. It seemed to have a default timeout of 30 seconds. I after changing evry other timeout value I could find, including:
Finaley I found that it was the SqlCommand timeout that was defaulting to 30 seconds.
I decided to just duplicate the timeout of the connection string to the command. The connection string is configured in the web.config.
Some code:
namespace ROS.WebService.Common
{
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public static class DataAccess
{
public static string ConnectionString { get; private set; }
static DataAccess()
{
ConnectionString = ConfigurationManager.ConnectionStrings["ROSdb"].ConnectionString;
}
public static int ExecuteNonQuery(string cmdText, CommandType cmdType, params SqlParameter[] sqlParams)
{
using (SqlConnection conn = new SqlConnection(DataAccess.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(cmdText, conn) { CommandType = cmdType, CommandTimeout = conn.ConnectionTimeout })
{
foreach (var p in sqlParams) cmd.Parameters.Add(p);
cmd.Connection.Open();
return cmd.ExecuteNonQuery();
}
}
}
}
}
Change introduced to "duplicate" the timeout value from the connection string:CommandTimeout = conn.ConnectionTimeout
I'd prefer to use the .Find
method directly on a range object containing the range of cells to be searched. For original poster's code it might look like:
Set cell = ActiveSheet.Columns("B:B").Find( _
What:=celda, _
After:=ActiveCell _
LookIn:=xlFormulas, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False _
)
If cell Is Nothing Then
'do something
Else
'do something else
End If
I'd prefer to use more variables (and be sure to declare them) and let a lot of optional arguments use their default values:
Dim rng as Range
Dim cell as Range
Dim search as String
Set rng = ActiveSheet.Columns("B:B")
search = "String to Find"
Set cell = rng.Find(What:=search, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)
If cell Is Nothing Then
'do something
Else
'do something else
End If
I kept LookIn:=
, LookAt::=
, and MatchCase:=
to be explicit about what is being matched. The other optional parameters control the order matches are returned in - I'd only specify those if the order is important to my application.
HI you can try this...
Try..
$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com" -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq ""}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\ceridian\NoClockNumber_2013_02_12.csv -NoTypeInformation
Or
$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com" -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq $null}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\cer
Hope it works for you.
I just had this error with a .sln file that was originally created in Visual Studio 2010 (and being built by Visual Studio 2010 and TFS 2010). I had modified the solution file to NOT build a project that was not supposed to be built in a particular configuration and visual studio changed the header of the solution file from:
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
To:
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.24720.0
MinimumVisualStudioVersion = 10.0.40219.1
Setting it back to the original 2010 version fixed my problem. I guess backwards compatibility in Visual Studio has still not been perfected.
Here's another alternative. Assuming you have an indexed DATE
or DATETIME
type field, this should use the index as the formatted dates will be type converted before the index is used. You should then see a range
query rather than an index
query when viewed with EXPLAIN.
SELECT
*
FROM
table
WHERE
date_created >= DATE_FORMAT( CURRENT_DATE - INTERVAL 1 MONTH, '%Y/%m/01' )
AND
date_created < DATE_FORMAT( CURRENT_DATE, '%Y/%m/01' )
If you are using jaxrs or any other, then there will be a class called mediatype.User interceptor before sending the request and compare it against this.