_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d19401 | test | From http://hsivonen.iki.fi/xhtml2-html5-q-and-a/ :
If I can use any doctype for XHTML5, how can browsers tell XHTML 1.0 and XHTML5 apart?
They can’t and they don’t need to. By design, a user agent that implements XHTML5 will process inputs authored as XHTML 1.0 appropriately.
A: There is no XHTML 5. Currently there is HTML 4.01 and XHTML 1.0. There will be no XHTML 2.0. There will only be HTML 5. HTML 5 is not an XML standard (meaning an HTML 5 document is not an XML document).
Perhaps you're looking at HTML 5 + XML = XHTML 5. I guess you can express HTML 5 as XML but as far as I know this is non-standard. More specifically, this is just a serialization method for the document tree rather than a standard.
To clarify this issue, take a look at HTML 5 and XHTML 5 - one vocabulary, two serializations. Even from the title it says "one vocabulary, two serializations". And Conversation With X/HTML 5 Team:
The XHTML 5 spec says that "generally speaking, authors are
discouraged from trying to use XML on
the Web". Why write an XML spec like
XHTML 5 and then discourage authors
from using it? Why not just drop
support for XML (XHTML 5)?
Some people are going to use XML with
HTML 5 whatever we do. It's a simple
thing to do — XML is a metalanguage
for describing tree structures, HTML 5
is a tree structure, it's obvious that
XML can be used to describe HTML 5.
The problem is that if we don't
specify it, then everyone who thinks
it is obvious and goes ahead and does
it will do it in a slightly different
way, and we'll have an
interoperability nightmare. So instead
we bite the bullet and define how it
must work if people do it.
XHTML 1.0 was a standard. It differed to HTML 4. XHTML 5, if you can call it that, is nothing more than representing HTML 5 documents in XML form.
A: Browsers won't. The elements exist in the same namespace, and have the same meaning, except where the WHATWG have decided to change them — such as the b element — where browsers are just going to have to muddle through.
A: It would be possible to distinguish by DOCTYPE (which is different for HTML5 and XHTML 1.x), but its presence is specifically non-mandatory in XHTML5; and element namespace is the same. So, in general, there's no good way to distinguish them. If you want to write portable XHTML5, I guess providing DOCTYPE is your best bet. | unknown | |
d19402 | test | ADSL is generally not a fixed IP, which means that the server does not recognize it.
As I understand it, you want to balance the load.
Analyzing your doubt. I leave my case study.
1 - How each server is separate.
Place a fixed IPv4 from there, create a fixed DNS and point to the corresponding fixed IP. Also place a domain and add the DNS configuration. If you have IPv6 (AAA), add it for even more answers. And prioritize cryptography.
If you need a secure proxy, use CloudFlaure to manage your settings. It helps the configuration become more practical.
2 - Pointing the DNS to fixed IP, create NS for both servers.
example: ns1.server.com //// ns2.server.com
I recommend creating 4 NS for each server.
3 - The same procedure is used on the slave. but do not use ns, switch to another silga, for example: (tl1.server.com).
This facilitates orientation.
So, for each server.
An IPv4
An Ipv6
Four NS
Two DNS
Therefore, when the first server goes down, the other server takes over. Be on IPV4 or IPV6. And the DNS and the DNS are congested or are not recognized for some reason, promptly the other takes over. So, without loss.
If there is a problem with your hosting, create IP or domains. Due to fees.
There are some free ones and, that work 90%, cloudflare itself has this service.
If I was able to understand your demand, I recommend the services later.
It works for me.
Submit questions and follow the case.
A: My Idea.
You use dynamic dns to know always, which IP Address is valid, to reach the site with the spotty connection.
A fail over Router like the one in the comment, has the advantage, that it always knows which connection is the better one, and actualizes the dyndns serverip.
For the rest, i would see that both sites build a vpn. Most router can be VPN server as also client and with the dynamic Ip, establishing the connection is no problems, as long any connection actually work. For your replication it is the same network, with a fixed ip.
If you have already a ssl server,all is the same, only you need to bridge the port, so that packet will enter the network.
For all that, you should get some help, because the are many points that can be tweaked, to fit the situation on side. | unknown | |
d19403 | test | A common source of problems when programs that execute successfully as an interactive user, but fail when run as a service, is the user settings surrounding the execution have changed. For example, when you run Gradle, there are settings in %USERPROFILE% \ .gradle (typically c:\users\<username>, which for you logged in interactively is different than the account under which the service is running.)
When you run as a service, there is a different user profile, or possibly none at all. Have your batch script dump the environment (add "set" near the top of the .bat file - this will dump an alphabetical list of environment variables), and compare the output when it runs as a service to when you run it interactively. See if USERPROFILE is defined, and if it is compare the .gradle folder in the service's area to your own .gradle folder.
In addition to Gradle settings, Gradle's cache is also typically under the .gradle folder. Your cache is likely to contain different items than the cache of the service, which may be significant if there are authentication issues in the external repositories to which your build tries to connect (again, possibly as a result of the different credentials in your user configurations!)
The tool processing the https request may look for certificates somewhere in your user profile. You may have accepted a certificate (used to 'recognize' an https server) that is not included in the accepted certificates of the service. These would likely be in the .keystore file in your user profile. Java's keytool.exe can help to decode and dump this file.
Other tools involved in your build may also have settings stored in the USERPROFILE space, which differ between your space and that of the service account - for example Android (.android), Java, Maven (.m2), Git (.gitconfig), etc. | unknown | |
d19404 | test | Why do I only have to escape the last \?
Because only after the last \ there is a symbol (") which together with \ forms an escape sequence — \" (escaping the role of the quote symbol " as a string terminator).
If \ with subsequent symbol(s) don't form an escape sequence, it's kept as is, i.e. as the backslash symbol itself.
(In your case neither \P, nor \F and nor \E form an allowed escape sequence, so the symbol \ itself is interpreted literally — as is.)
An (unsolicited) solution:
Use forward slashes (/) instead of backslashes (\)
(all Windows system calls accept them, too):
localExtractpath = "D:/Python/From 0 to 1/Excel/"
A: The last backslash in "D:\Python\From 0 to 1\Excel\" is escaping your ending quotation mark, so in the eyes of the interpreter, your string is unterminated. In fact, you have to escape all your backslashes if you want to use the literal backslash in your string:
"D:\\Python\\From 0 to 1\\Excel\\"
A: Other answers are right: you should escape all your backslashes and, even better, you should use forward slash for path elements (you can even take a look at the pathlib library).
But to answer specifically your question on why the issue lies only in the last one and not in the previous backslashes, you should take a look at the definition of string literals.
You will see that there is a (short) list of characters for which the backslash makes something particular. For the rest, the backslash is taken as itself.
For instance "\n" is interpreted not as a string with two characters (\ and n) but as a string with only a single line-feed character.
That is not the case with "\P", "\F" or "\E" which are two characters each since they don't have a specific meaning.
\" and \' are particular in that they allow to respectively insert a " or ' character in a string literal delimited by this same character.
For example, 'single: \', double "' and "single: ', double: \"" are two ways to define the single: ', double " string literal. | unknown | |
d19405 | test | Looks like the problem is you're assigning the list you build to the same name as the output file. You're also reading all of the lines out of the file and not assigning the result anywhere, so when your list comprehension iterates over it, it's already at the end of the file. So you can drop the readlines line.
def newfield(infile,outfile):
output = ["%s\t%s" %(item.strip(),2) for item in infile]
outfile.write("\n".join(output))
outfile.close()
return outfile
A: The line infile.readlines() consumes the whole input file. All lines are read and forgotten because they are not assigned to a variable.
The construct ["%s\t%s" %(item.strip(),2) for item in infile] is a list comprehension. This expression returns a list. By assigning it to the variable outfile the old value of outfile - probably a file object - is forgotten and replaced by the list returned by the list comprehension. This list object does not have a write method. By assigning the list to another variable the file object in outfile is preserved.
Try this:
def newfield(infile,outfile):
items = ["%s\t%s" %(item.strip(),2) for item in infile]
outfile.write("\n".join(items))
outfile.close()
return outfile | unknown | |
d19406 | test | They have semantic differences. A fieldset is designed to encapsulate a group of fields, inputs or controls. Sections and headings are more designed for actual text content (your actual copy in the literary sense). | unknown | |
d19407 | test | It is not related to the type of the task, it's a typical << misunderstanding.
When you write
project.task('hello') << {
println project.greeting.message
}
and execute gradle hello, the following happens:
configuration phase
*
*apply custom plugin
*create task hello
*set greeting.message = 'Hi from Gradle'
executon phase
*
*run task with empty body
*execute << closure { println project.greeting.message }
in this scenario output is Hi from Gradle
When you write
project.task('hello', type: Exec) {
println project.greeting.message
}
and execute gradle hello, the following happens
configuration phase
*
*apply custom plugin
*create exec task hello
*execute task init closure println project.greeting.message
*set greeting.message = 'Hi from Gradle' (too late, it was printed in step 3)
the rest of workflow does not matter.
So, small details matter. Here's the explanation of the same topic.
Solution:
void apply(Project project) {
project.afterEvaluate {
project.task('hello', type: Exec) {
println project.greeting.message
}
}
} | unknown | |
d19408 | test | fileName is an array of 30 uninitialized pointers to char. *fileName is the same as filename[0], which is an uninitialized pointer to a char. You cannot use this pointer for anything but assigning it a valid value. You are not doing that, though, and instead you're trying to read data to it, with predictably catastrophic consequences.
In short, you shouldn't be using any pointers in C++ at all, and instead use an std::string for your situation:
std::string fileName;
if (!(std::cin >> fileName)) { /* I/O error, die */ }
// ...
(Perhaps what you meant to do is to make fileName an array of 30 chars: char fileName[30];. But don't do that. Even though it might work, it's very terrible.)
A: There is another thing slightly dodgy here:
for(p = 0; p <= i; p++)
you probably want
for(p = 0; p < i; p++)
so that you don't try to dereference off the end of your array
probably better to write
for (int p = 0; p != i; ++p)
This is the recommended form according to Moo and Koenig: http://www.drdobbs.com/cpp/184402072
I would also not use char * to read from a cin, use std::string to store your string and inputs, you do not need to new the memory if it is not needed outside the scope of your main writeFile function. Strings support dynamic resizing also so you don't need to initialise it to any size, here is the first example I googled to help you understand
A: Why are you using the "C way" to store your file name? And you're using it the wrong way: char**. It would be easier to just declare:
std::string fileName;
while(!std::cin >> fileName);
ofstream myfile(fileName.c_str());
You also are using i inside of your loop but are iterating over p, I think that's not what you want to do ... | unknown | |
d19409 | test | You will need to use a closure to implement this correctly. For example, something like this.
for(var i in companyTickerList) {
console.log('i = ' + i);
//construct url
var url = base_url + companyTickerList[i];
console.log('url = ' + url);
function(i){
request(url, functon(error, response, xml) {
if(!error && response.statusCode == 200) {
//load xml returned from GET to url
var cik_xml = cheerio.load(xml)
console.log('i = ' + i);
//map company ticker symbol to cik value scraped from xml
TickerToCIK[companyTickerList[i]] = cik_xml('company-info cik').text();
console.log('TICKER = ' + companyTickerList[i] + ' CIK = ' + cik_xml('company-info cik').text());
}
}
}(i)
}
I haven't tested the above, but you can see how I wrapped the request in a function, and passed that function the iterator value as an argument.
A: var is tricky :)
JavaScript actually evaluates your code like this:
var i;
for(i in companyTickerList) {
console.log('i = ' + i);
// ...
meaning, it's like var definition executed before your first line of code.
So, you actually have a variable i which gets updated 6 times and eventually i = 6.
Your request() callback is async, and by the time your first callback actually got invoked, the loop is long gone and i equals 6.
Solution:
One possible solution is to use an IIFE (Immediately-Invoked Function Expression).
That is:
(function (i) {
// async code using i
})(i);
Like so:
for (var i in companyTickerList) {
console.log('i = ' + i);
//construct url
var url = base_url + companyTickerList[i];
console.log('url = ' + url);
(function (i) {
request(url, function (error, response, xml) {
if (!error && response.statusCode == 200) {
//load xml returned from GET to url
var cik_xml = cheerio.load(xml);
console.log('i = ' + i);
//map company ticker symbol to cik value scraped from xml
TickerToCIK[companyTickerList[i]] = cik_xml('company-info cik').text();
console.log('TICKER = ' + companyTickerList[i] + ' CIK = ' + cik_xml('company-info cik').text());
}
});
})(i);
} | unknown | |
d19410 | test | You can write it like this:
#include <iostream>
#include <sstream>
void log(const std::ostringstream& obj) {
std::cout<<obj.str();
//Do something meaningful with obj that doesn't modify it
}
void gol(const std::string& obj) {
std::cout<<obj;
//Do something meaningful with obj that doesn't modify it
}
int main() {
log(std::ostringstream{} << "Foo" << 123 << 'B');
gol(std::string{}.append("Foo").append(std::to_string(123)).append("Bar"));
}
Though, I am not aware of a way to give it a name, call methods, and pass it to another function, all in the same expression.
In general, trying to squeeze as much code into a single line is not something that is actually desirable. | unknown | |
d19411 | test | 1.Is autocommit turned on or turned off on your database connection ?
2. In DB2, there are chances of deadlock when you are firing a select query and
update query within same transaction.
3. If the auto commit is turned off and you have fired a select query on the
table then try committing or rollback that transaction and then fire update
query. It should work.
Let me know in case if you are still facing above issue. | unknown | |
d19412 | test | You're catching the OperationCanceledException in your DuplicateSqlProcsFrom method, which prevents its Task from ever seeing it and accordingly setting its status to Canceled. Because the exception is handled, DuplicateSqlProcsFrom finishes without throwing any exceptions and its corresponding task finishes in the RanToCompletion state.
DuplicateSqlProcsFrom shouldn't be catching either OperationCanceledException or AggregateException, unless it's waiting on subtasks of its own. Any exceptions thrown (including OperationCanceledException) should be left uncaught to propagate to the continuation task. In your continuation's switch statement, you should be checking task.Exception in the Faulted case and handling Canceled in the appropriate case as well.
In your continuation lambda, task.Exception will be an AggregateException, which has some handy methods for determining what the root cause of an error was, and handling it. Check the MSDN docs particularly for the InnerExceptions (note the "S"), GetBaseException, Flatten and Handle members.
EDIT: on getting a TaskStatus of Faulted instead of Canceled.
On the line where you construct your asyncDupSqlProcs task, use a Task constructor which accepts both your DuplicateSqlProcsFrom delegate and the CancellationToken. That associates your token with the task.
When you call ThrowIfCancellationRequested on the token in DuplicateSqlProcsFrom, the OperationCanceledException that is thrown contains a reference to the token that was cancelled. When the Task catches the exception, it compares that reference to the CancellationToken associated with it. If they match, then the task transitions to Canceled. If they don't, the Task infrastructure has been written to assume that this is an unforeseen bug, and the task transitions to Faulted instead.
Task Cancellation in MSDN
A: Sacha Barber has great series of articles about TPL. Try this one, he describe simple task with continuation and canceling | unknown | |
d19413 | test | You need to lsiten to props changes during componentDidUdpate like this, to check:
componentDidUpdate() {
if (this.props.clearColor && this.state.bgColor) {
this.setState(this.initialState)
}
}
Moving the state up is reacty and you could be using that.
I would recommend that or moving it into a context.
Also maybe look into function components, which will be the main way to write react in the future.
A: This is how I would do it. I would just lift all the state up to Quiz component. Also would keep boxClick function in Quiz component and pass it to Button component. And I am colouring the button only which title match currently selected answer using setAnswer hook.
const Button = ({answer, name, bgColor, isCorrect, boxClick, setAnswer}) => {
return (
<div className="boxClickCss"
style={{backgroundColor: (answer === name) && bgColor}}
onClick={(e) => {
boxClick(isCorrect)
setAnswer(name)
}}>
{name}
</div>
)
}
const Quiz = () => {
const questions = [
{
questionText: 'What is the capital of France?',
answerOptions: [
{ answerText: 'New York', isCorrect: false },
{ answerText: 'London', isCorrect: false },
{ answerText: 'Paris', isCorrect: true },
{ answerText: 'Dublin', isCorrect: false },
],
},
{
questionText: 'Who is CEO of Tesla?',
answerOptions: [
{ answerText: 'Jeff Bezos', isCorrect: false },
{ answerText: 'Elon Musk', isCorrect: true },
{ answerText: 'Bill Gates', isCorrect: false },
{ answerText: 'Tony Stark', isCorrect: false },
],
},
{
questionText: 'The iPhone was created by which company?',
answerOptions: [
{ answerText: 'Apple', isCorrect: true },
{ answerText: 'Intel', isCorrect: false },
{ answerText: 'Amazon', isCorrect: false },
{ answerText: 'Microsoft', isCorrect: false },
],
},
{
questionText: 'How many Harry Potter books are there?',
answerOptions: [
{ answerText: '1', isCorrect: false },
{ answerText: '4', isCorrect: false },
{ answerText: '6', isCorrect: false },
{ answerText: '7', isCorrect: true },
],
},
];
const [currentQuestion, setCurrentQuestion] = React.useState(0);
const [bgColor, setbgColor] = React.useState('')
const [answer, setAnswer] = React.useState('')
const boxClick = isCorrect => {
if(isCorrect) {
setbgColor("#9ef0bc")
} else {
setbgColor("#f56342")
}
}
const nextClicked = () => {
const nextQuestion = currentQuestion + 1;
if (nextQuestion < questions.length) {
setCurrentQuestion(nextQuestion);
}
};
const previousClicked = () => {
if (currentQuestion <= 0) {
setCurrentQuestion(0);
} else {
const nextQuestion = currentQuestion - 1;
setCurrentQuestion(nextQuestion);
}
}
return (
<div className='quiz'>
<div className='app'>
<div className='question-section'>
<div className='question-count'>
<span>Question {currentQuestion + 1}</span>/{questions.length}
</div>
<div className='question-text'>{questions[currentQuestion].questionText}</div>
</div>
<div className='answer-section'>
{questions[currentQuestion].answerOptions.map((answerOption) => (
<Button name={answerOption.answerText} isCorrect={answerOption.isCorrect} boxClick={boxClick} bgColor={bgColor} setAnswer={setAnswer} answer={answer} />
))}
</div>
</div>
<br></br>
<div className='buttons'>
<button className="prev" onClick={() => previousClicked()}>Previous</button>
<button className="next" onClick={() => nextClicked()}>Next</button>
</div>
</div>
);
}
ReactDOM.render(
<Quiz />,
document.getElementById('root')
); | unknown | |
d19414 | test | if you have a string, just loop on the string and output the characters to your stringstream
std::string name = "name1";
std::stringstream ss;
for(auto c : name)
ss << std::static_cast<int>(c);
ss << ";";
As a side note:
uint32_t* var = (uint32_t*)tab;
is totally useless, you don't need a pointer.
A: i'm not sure this will solve your problem, but i would take a different approach.
i would use a struct to describe the underlying protocol and then continue with that. example:
struct dx{
uint8 _junk0[9];
char name1[2];
char name2[2];
uint32 num;
} __attribute__((packed));
uint8 *input;
dx* struct=(dx*)input;
printf("%d",dx->num); | unknown | |
d19415 | test | Consider creating a custom filter that uses Number.prototype.toLocaleString()
console.log(Number(8).toLocaleString('en',{style: 'currency', currency: 'USD'}))
console.log(Number(8).toLocaleString('de',{style: 'currency', currency: 'EUR'}))
A: Something like this:
{{ lang == 'tr' ? '₺' + item.price : item.price + '$' }}
Or write your own Custom Filter that parses your currency. | unknown | |
d19416 | test | You can set automaticallyAdjustScrollViewInsets to false. | unknown | |
d19417 | test | The pROC::roc function doesn't accept sampling weights, so it's not just a matter of data formats -- you can extract a data frame from a survey object with model.frame, but roc still won't be doing a weighted analysis.
There's a WeightedROC package that fits weighted ROC curves. You could do something like (not tested because there isn't a reproducible example)
WeightedROC(fitted(Model3), Model3$y, weights(psurvey)) | unknown | |
d19418 | test | Your date format string is wrong. Use dd instead of DD for the days.
According to the documentation, DD means "day of year", while you need dd, which means "day of month".
Change the first line to:
DateTimeFormatter d_t = DateTimeFormat.forPattern("dd-MMM-YYYY HH:mm"); | unknown | |
d19419 | test | in *.gemspec:
s.platform = 'ruby'
possible platform values:
ruby
C Ruby (MRI) or Rubinius, but NOT Windows
ruby_18
ruby AND version 1.8
ruby_19
ruby AND version 1.9
mri
Same as ruby, but not Rubinius
mri_18
mri AND version 1.8
mri_19
mri AND version 1.9
rbx
Same as ruby, but only Rubinius (not MRI)
jruby
JRuby
mswin
Windows
mingw
Windows 'mingw32' platform (aka RubyInstaller)
mingw_18
mingw AND version 1.8
mingw_19
mingw AND version 1.9 | unknown | |
d19420 | test | I believe this has to do with the system-ui font. I've made a quick Codepen to check it out. If you enable the "Bold Text" option on iOS it will change the font weight for the p that uses the system-ui as its font-family. And you can see that the p with the custom font, Poppins, isn't bold. | unknown | |
d19421 | test | redirect_to login_path, :notice => "Please log in to continue" is a normal expression in Ruby that does not return false (or nil, see the source code), so program execution continues (to check the second part after AND) and return false can be executed.
A: The and is there only for you to be able to write the return false at the same line as the previous statement.
It's equivalent of doing this:
redirect_to login_path, :notice => "Please log in to continue"
return false
it's not exactly the same because with the "and" it would only return false if the redirect_to method returns something that isn't nil or false but as it almost always returns something that is not nil nor false then the right side of the statement is always executed (and false is returned).
The and in Ruby is just an alias to && and behaves exactly like it with only one difference, it has a lower precedence than all other pieces of the statement, so first it evaluates whatever is on it's left and then gets applied. Ruby also has the or which is the same as || but with a lower precedence in expressions.
A: This kind of construct used to be used with a filter, when filter return values were expected. The false would halt normal request processing.
So if a controller looked like this:
class FooController < ActionController::Base
before_filter :access_denied
# etc.
end
None of the controller's actions would run; this method was likely designed to be called from a filter, like:
def check_access
return access_denied unless current_user.has_access
end
These days filter return values are ignored.
It could be used as a normal method in an action to stop processing the action and return after the redirect, so no other logic/rendering/etc. is run inside the controller.
A: Documentation on operators: Under the "Defined?, And, Or, and Not" section
Using and is useful for chaining related operations together until one of them returns nil or false. You can use it like you showed in your question or you can also use it to short-circuit the line of code.
# Short circuit example
blog = Blog.find_by_id(id) and blog.publish!
The blog only gets .publish! called on it if the find_by_id was successful.
In your example:
def access_denied
redirect_to login_path, :notice => "Please log in to continue" and return false
end
They are just using it to write the code more compactly on one line.
However, it is also useful for a controller action where you may be rendering based on conditionals and you don't want to get Rails "multiple renders" warning:
def show
if something
render :partial => 'some_partial'
end
render :partial => 'some_other_partial'
end
Rails will give you a warning if something returns true since you have multiple render statements being evaluated in the action. However, if you changed it to
if something
render :partial => 'some_partial' and return
end
it would allow you to stop the action execution. | unknown | |
d19422 | test | I have used load ajax for this
$('#AREA_PARTIAL_VIEW').load('@Url.Action("Insert_Partial_View","Customers")'); | unknown | |
d19423 | test | Code changed to retrieve all the inputs inside the cloned div and change its name/id.
<script>
$(document).ready(function(){
$("#nmovimentos").change(function () {
var direction = this.defaultValue < this.value
this.defaultValue = this.value;
if (direction)
{
var $div = $('div[id^="novomov"]:last');
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
var $clone = $div.clone().prop('id', 'novomov'+ num)
$clone.insertAfter('[id^="novomov"]:last');
// get all the inputs inside the clone
var inputs = $clone.find('input');
// for each input change its name/id appending the num value
$.each(inputs, function(index, elem){
var jElem = $(elem); // jQuery element
var name = jElem.prop('name');
// remove the number
name = name.replace(/\d+/g, '');
name += num;
jElem.prop('id', name);
jElem.prop('name', name);
});
}
else $('[id^="novomov"]:last').remove();
});
});
</script>
A: Instead of parsing the id of the element to get the number you should use the data attribute. Also since you are using jQuery you can use .last() to get the last element with that id. Hope this helps.
$('#nmovimentos').on('change', function () {
var direction = this.defaultValue < this.value,
$last = $('#novomov').last(),
$clone,
num;
this.defaultValue = this.value;
if (direction) {
// add id in a data attribute instead of parsing the id
num = parseInt($last.data('id'), 10) + 1;
// set clone id data attribute to have the latest number
$clone = $last.clone().data('id', num);
// add clone after the last div
$last.after($clone);
} else {
$last.remove();
}
}); | unknown | |
d19424 | test | Simply because your query is returning a null cursor object.
So I would suggest two modification in your getStore function to avoid any crash issue.
This is a query to find a String object. So the query should look like this.
Cursor c = db.rawQuery("select * from " + TABLE_NAME + " where "
+ COL_STORE_ID + "='" + new String[]{storeid} + "'", null);
Look closely at the ' before and after the storeid you've provided as a parameter to the query.
And the other thing is you need to check for null value before you do any operation on your Cursor
// Check for null here and return if null
if(c == null) return null;
if (c.moveToFirst()) {
//.. Your code
}
Add a check here too
public void inCaseOffline() {
StoreHelper sh = new StoreHelper(ctx);
Log.i("ncdebug", "Store ID(incaseoffline): " + storeid);
StoreData sd = sh.getStore(storeid);
// Add the null checking
if(sd == null) {
Toast.makeText(YourActivity.this, "Could not fetch information", Toast.LENGTH_LONG).show();
return;
}
// .. Your code
}
Edit
You might consider having the getStore function to be modified like this
public StoreData getStore(String storeid) {
// ... Database operation.
// Initialize the StoreData here
StoreData data = new StoreData();
// ... Your code
return data;
}
To achieve the initialization, add an empty constructor too in your StoreData class
public class StoreData {
public int img;
public String store_id;
public String account_id;
public String kota_id;
public String store_name;
public String store_manager;
public String store_address;
public String store_telephone;
public String store_geo_lat;
public String store_geo_long;
public String store_leadtime;
public String store_md;
public StoreData() {
// Empty constructor
}
// ... The other constructer
} | unknown | |
d19425 | test | I don't have enough reputation to comment on answers, but I just wanted to note that downloading the JSR-311 api by itself will not work. You need to download the reference implementation (jersey).
Only downloading the api from the JSR page will give you a ClassNotFoundException when the api tries to look for an implementation at runtime.
A: Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc
Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded.
A: I wrote my own, it's short, super simple, and you can copy it if you like:
http://www.dmurph.com/2011/01/java-uri-encoder/
A: You could also use Spring's UriUtils
A: It seems that CharEscapers from Google GData-java-client has what you want. It has uriPathEscaper method, uriQueryStringEscaper, and generic uriEscaper. (All return Escaper object which does actual escaping). Apache License.
A: I think that the URI class is the one that you are looking for.
A: Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.
You said:
For example, given an input:
http://google.com/resource?key=value
I expect the output:
http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue
So:
C:\oreyes\samples\java\URL>type URLEncodeSample.java
import java.net.*;
public class URLEncodeSample {
public static void main( String [] args ) throws Throwable {
System.out.println( URLEncoder.encode( args[0], "UTF-8" ));
}
}
C:\oreyes\samples\java\URL>javac URLEncodeSample.java
C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value"
http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue
As expected.
What would be the problem with this? | unknown | |
d19426 | test | Yes, it's possible for an app to serve both static files and dynamic content. Actually there's nothing magical required for it, this is normal for most web applications.
Your configuration looks ok. One thing you should change: the package of your go file.
Don't use package main, instead use another package and make sure your .go file is put into that. For example if you name your package mypackage, use this folder structure:
+ProjectRoot
app.yaml
+mypackage
myfile.go
And start your myfile.go with line:
package mypackage | unknown | |
d19427 | test | You shouldn't need a timeout here.
function scheduleDelayedCallback() {
var now = new Date();
if (now.getTime() - lastEvent.getTime() >= 750) {
// minimum time has passed, go ahead and update or whatever
$("#main").html('Lade...');
// reset your reference time
lastEvent = now;
}
else {
this_function_needs_to_be_delayed(); // don't know what this is.
}
}
Your explanation of what you want to happen isn't the clearest so let me know if the flow is wrong. | unknown | |
d19428 | test | Vagrant plays nicely with AWS (via vagrant-aws plugin).
Vagrant seems to play nicely with Windows as well since version 1.6 and the introduction of WinRM support (ssh alternative for Windows).
However AWS plugin doesn't support WinRM communicator yet. So you'll need to pre-bake your Windows AMIs with SSH service pre installed, if you want vagrant to provision it.
Update (29/03/2016): Thanks to Rafael Goodman for pointing to vagrant-aws-winrm plugin as a possible workaround. | unknown | |
d19429 | test | Updated
This is related to sequence A051026 : Number of primitive subsequences of {1, 2, ..., n} in OEIS, the Online Encyclopedia of Integer Sequences.
I don't think there is any easy way to calculate the terms. Even the recursive computations are not trivial, except when n is prime where:
a(n) = 2 * a(n-1) - 1
Both the problem here and "A051026" can be thought of subproblems of a generalization of the above sequence. "A051026" is the instance with (a,b,..) = (2,3,4,5...), e.g. "all the integers >= 2".
A: I believe it will be easier to calculate the complimentary- that is the number of subsets of S that are not allowed. This is the number of subsets of S for each there is at least one pair (a,b) such that a divides b. After you calculate that number M' simply subtract it from the total number of subsets of S that is 2n.
Now to calculate the number of subsets of S that are not allowed you will have to apply the inclusion-exclusion principle. The solution is not very easy to implement but I don't think there is an alternative approach. | unknown | |
d19430 | test | What you need is a tooltip plugin. There are plenty of them.
Check out this list: https://cssauthor.com/jquery-css3-hover-effects/
A: <img class="enlarge-onhover" src="img.jpg">
...
And on the css:
.enlarge-onhover {
width: 30px;
height: 30px;
}
.enlarge-onhover:hover {
width: 70px;
height: 70px;
}
A: Take a look at http://fancybox.net/blog
Fancybox looks nice, uses JQuery and is highly configurable with various show/hide effects. Tutorial number 3 on this page shows you how to use it OnHover rather than OnClick
The home page http://fancybox.net/home shows some examples of the visual effect
A: <script>
function bigImg(x) {
x.style.height = "64px";
x.style.width = "64px";
}
function normalImg(x) {
x.style.height = "32px";
x.style.width = "32px";
}
</script>
<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0" src="smiley.gif" alt="Smiley" width="32" height="32">
The function bigImg() is triggered when the user mouse over the image. This function enlarges the image.
The function normalImg() is triggered when the mouse pointer is moved out of the image. That function sets the height and width of the image back to normal. | unknown | |
d19431 | test | This seems to work quite well:
files = list.files(path=".", pattern="MCL")
table_list <- lapply(X = files, FUN = read.table, header=TRUE)
combined <- Reduce(f = merge, x = table_list)
We first loop over the table names with lapply and read each one in, returning a list. By using header=TRUE we can avoid having to rename each one and instead deduce the column names from the first row of each file. Then we can use Reduce to repeatedly merge each table with the next one. merge is smart enough to assume that the shared column name is the thing we want to merge on, so we don't need to specify arguments there either.
I didn't download all the files but here's the output from running this code on the first 3: | unknown | |
d19432 | test | Based solely on the query in your OP and the records in your image nothing would be returned. It would only return if both start_range_cost AND end_range_cost were exactly 3000 which none of the records match, but this is just because you've got the < and > signs flipped around. Try using BETWEEN, I feel it's less prone to comparison mistakes if you're upper and lower bounds inclusive in your comparison.
Assuming:
*
*2500 is the number in the range searching for from your example
*You want to be lower and upper bound inclusive (base on your image, it looks like it)
You can use BETWEEN to make this clearer:
SELECT * FROM hotel_tax_details
WHERE 2500 BETWEEN start_range_cost AND end_range_cost;
You could also fix the original query and correct the comparison:
SELECT * FROM `hotel_tax_details`
WHERE `start_range_cost`<=2500 AND `end_range_cost`>=2500
A: Hope this helps
SELECT * FROM hotel_tax_details WHERE 2500 BETWEEN start_range_cost AND end_range_cost | unknown | |
d19433 | test | The elements within the transclude directive aren't receiving the same scope. If you use the angualr $compile method and apply the scope of the transclude directive to the scope of the child directives it should work. The following should be added to your simpleTransclude directive:
link: function(scope, element) {
$compile( element.contents() )( scope )
}
remember to pass $compile into the directive.
I've forked your plnkr and applied the simpleTransclude scope to it's contents. | unknown | |
d19434 | test | With the current stable Version of Loopback you cannot filter on Level 2 properties for Relational Databases. These are some of the Issues raised on the same in Loopback
https://github.com/strongloop/loopback/issues/517
https://github.com/strongloop/loopback/issues/683
As a matter of fact you might want to look into native sql queries in loopback and
do the filtering there, or might need to use native javascript array
methods for filtering | unknown | |
d19435 | test | The problem with your regular expression is that you have the both the parentheses and the word "PROPERTY" inside of the brackets. Brackets are for specifying a set of characters, not strings, any member of which will match.
A simple (although probably not optimal) variation that should work for you is:
(PROPERTY\([A-Za-z][A-Za-z0-9_]*\))|([A-Za-z][A-Za-z0-9_]*)
A slightly better version would be:
(PROPERTY\([A-Za-z]\w*\))|([A-Za-z]\w*)
A: Part of the problem is the way that you are thinking about the regex.
As an example:
[A-Za-zPROPERTY(?)_]
This is essentially a "character class" which is not behaving the way that you are expecting. It will match ANY single character in the input string that matches ANY of the characters in the class. It does not treat PROPERTY as a single entity, but rather as separate uppercase letters (which are already included with the A-Z, anyway. Also, having (?) in your character class is matching "(", which I am sure is not what you want. | unknown | |
d19436 | test | Floating point numbers (in all languages, not just Tcl) represent most numbers somewhat inexactly. As such, they should not normally be compared for equality as that's really rather unlikely. Instead, you should check to see if the two values are within a certain amount of each other (the amount is known as epsilon and takes into account that there are small errors in floating point calculations).
In your code, you might write this:
set epsilon 0.001; # Small, but non-zero
if { $epsilon < $n_rval && $n_rval < 1-$epsilon} {
set onextensionFlag 0;# inside clipping area
} elseif {abs($n_rval) < $epsilon || abs(1-$n_rval) < $epsilon} {
set onextensionFlag 1 ;# inside clipping area (but on point)
} elseif { $n_rval >= 1+$epsilon || $n_rval <= -$epsilon } {
set onextensionFlag 2 ;# outside clipping area
} else {
set onextensionFlag 3 ;# consider inside clipping area
}
Basically, think in terms of a number line where you change points to small intervals:
0 1
————————————————|————————————————|————————————————
to
0-ε 0+ε 1-ε 1+ε
———————————————(—)——————————————(—)———————————————
How to do the checks for which range you're in then follow from that. | unknown | |
d19437 | test | You could use np.where:
>>> edge = np.array(EDGE)
>>> edge[edge > 0].min()
0.5
>>> np.where(edge == edge[edge > 0].min())
(array([1, 2]), array([0, 1]))
which gives the x coordinates and the y coordinates which hit the minimum value separately. If you want to combine them, there are lots of ways, e.g.
>>> np.array(np.where(edge == edge[edge > 0].min())).T
array([[1, 0],
[2, 1]])
A few asides: from numpy import * is a bad habit because that replaces some built-in functions with numpy's versions which work differently, and in some cases have the opposite results; ALLCAPS variable names are usually only given to constants; and your
EDGE = array(zeros((NUM_NODE, NUM_NODE)))
line doesn't do anything, because your EDGE = [[ 0., ... etc line immediately makes a new list and binds EDGE to it instead. You made an array and threw it away. There's also no need to call array here; zeros already returns an array.
A: numpy.ndenumerate will enumerate over the array(by the way, you shouldn't lose position information with reshaping).
In [43]: a = array(EDGE)
In [44]: a
Out[44]:
array([[ 0. , 0. , 0. , 0. , 0. ],
[ 0.5 , 0. , 0. , 0. , 0. ],
[ 1. , 0.5 , 0. , 0. , 0. ],
[ 1.41421356, 1.11803399, 1. , 0. , 0. ],
[ 1. , 1.11803399, 1.41421356, 1. , 0. ]])
In [45]: min((i for i in ndenumerate(a) if i[1] > 0), key=lambda i: i[1])
Out[45]: ((1, 0), 0.5)
Or you can do it with the old way if you want every occurence:
In [11]: m, ms = float("inf"), []
In [12]: for pos, i in ndenumerate(a):
....: if not i: continue
....: if i < m:
....: m, ms = i, [pos]
....: elif i == m:
....: ms.append(pos)
....:
In [13]: ms
Out[13]: [(1, 0), (2, 1)] | unknown | |
d19438 | test | First calculate the statistics you need to use.
proc summary data=sashelp.cars ;
var weight horsepower enginesize length ;
output out=stats
min(weight horsepower)=
max(weight horsepower)=
mean(enginesize length)=
/ autoname
;
run;
Then use those values to generate your "grid".
data want;
set stats;
do y = 1 to 20 ;
weight= weight_min + (y-1)*(weight_min+weight_max)/20;
do x = 1 to 20 ;
horsepower = horsepower_min + (x-1)*(horsepower_min+horsepower_max)/20;
output;
end;
end;
run; | unknown | |
d19439 | test | The issue here is that when you say
NORTH_EAST = [x_coordinate + 1, y_coordinate - 1]
You construct a list of two values, which are computed and stored at the time. They will not update based on the values of x_coordinate and y_coordinate changing.
You will need to recalculate the values on each loop to get the behaviour you expect. The easiest way to do this is with a function:
directions = {
"north east": (+1, -1),
"north west": (-1, -1),
"south east": (+1, +1),
"south west": (-1, +1),
}
def new_position(old, direction):
x, y = old
dx, dy = directions[direction]
return x + dx, y + dy
position = 100, 100
direction = "north east"
while True:
print(position)
position = new_position(position, direction)
Note that where there are linked pieces of data, it's best to store them in a data structure. Here I use a tuple to store the x and y values together, and a dictionary for the directional data. This means less repetition in your code. | unknown | |
d19440 | test | When you return a copy of the object, that creates a new object, which is what you want.
So one destructor is the for the copy, and one is for the original.
In other words your code works, but you can't see the copy constructor, add the line
example(const example& cp) : some_int(cp.some_int){std::cout << "copy constructor called!" << "\n";}
And the output is
constructor called!
copy constructor called!
69
destructor called!
destructor called!
By the way, your code looks a little clunky, but maybe that's the point?
The alternative would be ...
template <class T>
T function(T* ptr_object) {
ptr_object -> some_int = 69;
return *ptr_object;
}
Which is more concise
EDIT: I just noticed that @Jarod42 beat me to it (again) | unknown | |
d19441 | test | You need to install Visual Studio Test Agent first in your remote/test machine. Then using a remote access tool such as PsExec from PsTools you use MSTest.exe or VSTest.Console.exe to run a dll. You can script this in bat file on your own machine to trigger loading of test dlls to the remote machine and automated running.
However setting up a good build-test environment using Visual Studio TFS will always be a better and more integrated solution. | unknown | |
d19442 | test | You can create a decorator, like this:
def checkargs(func):
def inner(*args, **kwargs):
if 'y' in kwargs:
print('y passed with its keyword!')
else:
print('y passed positionally.')
result = func(*args, **kwargs)
return result
return inner
>>> @checkargs
...: def foo(x, y):
...: return x + y
>>> foo(2, 3)
y passed positionally.
5
>>> foo(2, y=3)
y passed with its keyword!
5
Of course you can improve this by allowing the decorator to accept arguments. Thus you can pass the parameter you want to check for. Which would be something like this:
def checkargs(param_to_check):
def inner(func):
def wrapper(*args, **kwargs):
if param_to_check in kwargs:
print('y passed with its keyword!')
else:
print('y passed positionally.')
result = func(*args, **kwargs)
return result
return wrapper
return inner
>>> @checkargs(param_to_check='y')
...: def foo(x, y):
...: return x + y
>>> foo(2, y=3)
y passed with its keyword!
5
I think adding functools.wraps would preserve the annotations, following version also allows to perform the check over all arguments (using inspect):
from functools import wraps
from inspect import signature
def checkargs(func):
@wraps(func)
def inner(*args, **kwargs):
for param in signature(func).parameters:
if param in kwargs:
print(param, 'passed with its keyword!')
else:
print(param, 'passed positionally.')
result = func(*args, **kwargs)
return result
return inner
>>> @checkargs
...: def foo(x, y, z) -> int:
...: return x + y
>>> foo(2, 3, z=4)
x passed positionally.
y passed positionally.
z passed with its keyword!
9
>>> inspect.getfullargspec(foo)
FullArgSpec(args=[], varargs='args', varkw='kwargs', defaults=None,
kwonlyargs=[], kwonlydefaults=None, annotations={'return': <class 'int'>})
_____________HERE____________
Update Python 3.10
In Python 3.10+ new ParamSpec type annotation was introduced (PEP 612), for better specifying parameter types in higher-order functions. As of now, the correct way to annotate this decorator would be like this:
from functools import wraps
from inspect import signature
from typing import Callable, ParamSpec, TypeVar, TYPE_CHECKING
T = TypeVar("T")
P = ParamSpec("P")
def check_args(func: Callable[P, T]) -> Callable[P, T]:
"""
Decorator to monitor whether an argument is passed
positionally or with its keyword, during function call.
"""
@wraps(func)
def inner(*args: P.args, **kwargs: P.kwargs) -> T:
for param in signature(func).parameters:
if param in kwargs:
print(param, 'passed with its keyword!')
else:
print(param, 'passed positionally.')
return func(*args, **kwargs)
return inner
Which correctly preserves type annotation:
if TYPE_CHECKING:
reveal_type(foo(2, 3))
# ─❯ mypy check_kwd.py
# check_kwd.py:34: note: Revealed type is "builtins.int"
# Success: no issues found in 1 source file
A: Adapted from @Cyttorak 's answer, here's a way to do it which maintains the types:
from typing import TypeVar, Callable, Any, TYPE_CHECKING
T = TypeVar("T", bound=Callable[..., Any])
from functools import wraps
import inspect
def checkargs() -> Callable[[T], T]:
def decorate(func):
@wraps(func)
def inner(*args, **kwargs):
for param in inspect.signature(func).parameters:
if param in kwargs:
print(param, 'passed with its keyword!')
else:
print(param, 'passed positionally.')
result = func(*args, **kwargs)
return result
return inner
return decorate
@checkargs()
def foo(x, y) -> int:
return x+y
if TYPE_CHECKING:
reveal_type(foo(2, 3))
foo(2, 3)
foo(2, y=3)
Output is:
$ mypy t.py
t.py:27: note: Revealed type is 'builtins.int'
$ python t.py
x passed positionally.
y passed positionally.
x passed positionally.
y passed with its keyword!
A: It is not ordinarily possible. In a sense: the language is not designed to allow you to distinguish both ways.
You can design your function to take different parameters - positional, and named, and check which one was passed, in a thing like:
def foo(x, y=None, /, **kwargs):
if y is None:
y = kwargs.pop(y)
received_as_positional = False
else:
received_as_positional = True
The problem is that, although by using positional only parameters as abov, you could get y both ways,
it would be shown not once for a user (or IDE) inspecting the
function signature.
I hav a feeling you just want to know this for the sake of knowing - if
you really intend this for design of an API, I'd suggest you'd rethink
your API - there should be no difference in the behavior, unless both
are un-ambiguously different parameters from the user point of view.
That said, the way to go would be to inspect the caller frame, and check
the bytecode around the place the function is called:
In [24]: import sys, dis
In [25]: def foo(x, y=None):
...: f = sys._getframe().f_back
...: print(dis.dis(f.f_code))
...:
In [26]: foo(1, 2)
1 0 LOAD_NAME 0 (foo)
2 LOAD_CONST 0 (1)
4 LOAD_CONST 1 (2)
6 CALL_FUNCTION 2
8 PRINT_EXPR
10 LOAD_CONST 2 (None)
12 RETURN_VALUE
None
In [27]: foo(1, y=2)
1 0 LOAD_NAME 0 (foo)
2 LOAD_CONST 0 (1)
4 LOAD_CONST 1 (2)
6 LOAD_CONST 2 (('y',))
8 CALL_FUNCTION_KW 2
10 PRINT_EXPR
12 LOAD_CONST 3 (None)
14 RETURN_VALUE
So, as you can see, when y is called as named parameter, the opcode for the call is CALL_FUNCTION_KW , and the name of the parameter is loaded into the stack imediately before it.
A: You can trick the user and add another argument to the function like this:
def foo(x,y1=None,y=None):
if y1 is not None:
print('y was passed positionally!')
else:
print('y was passed with its keyword')
I don't recommend doing it but it does work
A: In foo, you can pass the call stack from traceback to positionally, which will then parse the lines, find the line where foo itself is called, and then parse the line with ast to locate positional parameter specifications (if any):
import traceback, ast, re
def get_fun(name, ast_obj):
if isinstance(ast_obj, ast.Call) and ast_obj.func.id == name:
yield from [i.arg for i in getattr(ast_obj, 'keywords', [])]
for a, b in getattr(ast_obj, '__dict__', {}).items():
yield from (get_fun(name, b) if not isinstance(b, list) else \
[i for k in b for i in get_fun(name, k)])
def passed_positionally(stack):
*_, [_, co], [trace, _] = [re.split('\n\s+', i.strip()) for i in stack]
f_name = re.findall('(?:line \d+, in )(\w+)', trace)[0]
return list(get_fun(f_name, ast.parse(co)))
def foo(x, y):
if 'y' in passed_positionally(traceback.format_stack()):
print('y was passed with its keyword')
else:
print('y was passed positionally')
foo(1, y=2)
Output:
y was passed with its keyword
Notes:
*
*This solution does not require any wrapping of foo. Only the traceback needs to be captured.
*To get the full foo call as a string in the traceback, this solution must be run in a file, not the shell.
A: At the end, if you are going to do something like this:
def foo(x, y):
if passed_positionally(y):
raise Exception("You need to pass 'y' as a keyword argument")
else:
process(x, y)
You can do this:
def foo(x, *, y):
pass
>>> foo(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() takes 1 positional argument but 2 were given
>>> foo(1, y=2) # works
Or only allow them to be passed positionally:
def foo(x, y, /):
pass
>>> foo(x=1, y=2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got some positional-only arguments passed as keyword arguments: 'x, y'
>>> foo(1, 2) # works
See PEP 570 and PEP 3102 for more. | unknown | |
d19443 | test | I just wanted to understand if we are creating any additional threads that is responsible for this task threads?
Yes - from the documentation:
Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially. | unknown | |
d19444 | test | Consider it as a gaps-and-islands problem and use the following trick to group consecutive rows together:
WITH cte1 AS (
SELECT *, Year - ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Year) AS grp
FROM t
), cte2 AS (
SELECT *, COUNT(*) OVER (PARTITION BY Name, grp) AS grp_count
FROM cte1
)
SELECT *
FROM cte2
WHERE grp_count >= 3
ORDER BY Name, Year
If you look at the values in grp column you will find the pattern.
db<>fiddle
A: If there are no duplicate years for each Name, you need LEAD() window function to check for the 2nd next row.
If the year in that row is equal to the current year + 2 then this means that for this Name there are 3 consecutive years:
WITH cte AS (
SELECT *, LEAD(Year, 2) OVER (PARTITION BY Name ORDER BY Year) next_next
FROM participatition
)
SELECT DISTINCT p.*
FROM participatition p INNER JOIN cte c
ON p.Name = c.Name AND p.Year BETWEEN c.Year AND c.next_next
WHERE c.next_next = c.Year + 2;
See the demo.
A: I would simply use lead():
select distinct name
from (select p.*,
lead(year, 2) over (partition by name order by year) as year_2
from participation p
) p
where year_2 = year + 2;
For each row, this looks at the row two ahead for the same name ordered by year. If that row is the current year plus 2, then you have three years in a row.
A: There may be a more elegant way. But, well, this is what I've come up with:
select name, year
from
(
select
name, year,
case when lag(year, 2) over (partition by name order by year) = year - 2 then 1 else 0 end +
case when lag(year, 1) over (partition by name order by year) = year - 1 then 1 else 0 end +
case when lead(year, 1) over (partition by name order by year) = year + 1 then 1 else 0 end +
case when lead(year, 2) over (partition by name order by year) = year + 2 then 1 else 0 end +
1 as consecutive_rows
from participatition
) analyzed
where consecutive_rows >= 3
order by name, year;
If the table participatition can contain multiple rows for one name and year, add DISTINCT to the subquery (aka derived table).
A: WITH CTE AS (
SELECT name
, year-lag(year,2) OVER(PARTITION BY name ORDER BY year ASC) as two_years_ago
FROM t
)
SELECT name, two_years_ago
FROM cte
WHERE two_years_ago=2
A: You can solve this using row pattern matching if you're using Oracle Database:
with rws as (
select 'Carol' nm, 1999 yr from dual union all
select 'Carol' nm, 2000 yr from dual union all
select 'Carol' nm, 2001 yr from dual union all
select 'Carol' nm, 2002 yr from dual union all
select 'Faith' nm, 1996 yr from dual union all
select 'John' nm, 2001 yr from dual union all
select 'John' nm, 2002 yr from dual union all
select 'John' nm, 2003 yr from dual union all
select 'John' nm, 2009 yr from dual union all
select 'Lyla' nm, 1994 yr from dual union all
select 'Lyla' nm, 1996 yr from dual union all
select 'Lyla' nm, 1997 yr from dual
)
select * from rws match_recognize (
partition by nm
order by yr
all rows per match
pattern ( init cons{2} )
define
cons as yr = prev ( yr ) + 1
);
NM YR
Carol 1999
Carol 2000
Carol 2001
John 2001
John 2002
John 2003
A: Adding to my initial code Group By and Having clause as below builds on the existing code (which filtered all consecutive name, year) :
SELECT DISTINCT p1.name
FROM participatition p1, participatition p2
WHERE (p1.year = p2.year+1 OR p1.year = p2.year-1) AND p1.name = p2.name
GROUP BY p1.name
HAVING COUNT(p1.name) > 2
ORDER BY p1.name, p1.year
Thanks for all the answers - I never realised there was so many alternative solutions which has opened my eyes.
A: I have updated my code based on feedback (distinct, inner join, etc) from @ThorstenKettner using PSQL this time
SELECT p1.name
FROM participation p1
JOIN participation p2 ON p1.name = p2.name
WHERE (p1.year = p2.year+1 OR p1.year = p2.year-1)
GROUP BY p1.name
HAVING COUNT(p1.name) > 2
ORDER BY p1.name
This seems to work fine, is easy to understand and less complex. However I would like to test all solutions so I may apply such instead to suit new requirements. So thank you all for your generous help. Esp. Danke TK! | unknown | |
d19445 | test | It's possible.
Using Console APIs in WebView
Just override WebViewClient for your WebView like this:
val myWebView: WebView = findViewById(R.id.webview)
myWebView.webChromeClient = object : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
consoleMessage?.apply {
Log.d("MyApplication", "${message()} -- From line ${lineNumber()} of ${sourceId()}")
}
return true
}
}
A: @Volodymyr ans work for me. Just override onConsoleMessage on WebChromeClient (reference):
webview.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.d(TAG, "onConsoleMessage: "+ consoleMessage.message());
return true;
}
}); | unknown | |
d19446 | test | How many results do you get when you fire the reuquest directly on your database? Which result are you getting?
Is it possible that there is an error with your custom route? Do you have two server running?
A: My error was stupid. I was sending a null value in my term variable:
let obj = 'term='+term;
And it was necessary to do so:
let obj = {term: term};
All my new Angular function service code is:
loadUbigeo(term:string){
let obj = {term: term};
let body = JSON.stringify(obj);
let headers = new Headers({
'Content-Type': 'application/json'
});
return this.http.post(`${this.sett.url}/ubigeo`, body, { headers })
.map(res => {
return res.json();
});
} | unknown | |
d19447 | test | With Postgresql 9.5
UPDATE test SET data = data - 'v' || '{"v":1}' WHERE data->>'c' = 'ACC';
OR
UPDATE test SET data = jsonb_set(data, '{v}', '1'::jsonb); | unknown | |
d19448 | test | Below statement will just declare an array but will not initalize its elements :
StringBuffer[][] templates = new StringBuffer[3][3];
You need to initialize your array elements before trying to append the contents to them. Not doing so will result in NullPointerException
Add this initialization
templates[0][0] = new StringBuffer();
and then append
templates[0][0].append('h');
A: You need to initialize the buffers before you append something
templates[0][0] = new StringBuffer();
A: Others correctly pointed out the correct answer, but what happens when you try to do something like templates[1][2].append('h');?
What you really need is something like this:
public class Test { //<---Classes should be capitalized.
public static final int ARRAY_SIZE = 3; //Constants are your friend.
//Have a method for init of the double array
public static StringBuffer[][] initArray() {
StringBuffer[][] array = new StringBuffer[ARRAY_SIZE][ARRAY_SIZE];
for(int i = 0;i<ARRAY_SIZE;i++) {
for(int j=0;j<ARRAY_SIZE;j++) array[i][j] = new StringBuffer();
}
return array;
}
public static void main(String args[]){
StringBuffer[][] templates = initArray();
templates[0][0].append('h');
//You are now free to conquer the world with your StringBuffer Matrix.
}
}
Using the constants are important, as is is reasonable to expect your matrix size to change. By using constants, you can change it in only one location rather then scattered throughout your program. | unknown | |
d19449 | test | Got the same issue with Qt5.2.0 on Mavericks...
I found a work around: append a dummy file name to the directory you want to select.
However, be sure not to do this on Windows because the user will see it.
QString dir = "/Users/myuser/Desktop";
#if defined(__APPLE__)
dir += "/MyFile.txt";
#endif
fn = QFileDialog::getOpenFileName(this, "Select File", dir);
Also, for those like me that instantiate a file dialog because they need more options you can also do:
QFileDialog fileDialog(this, "Select File");
#if defined(__APPLE__)
fileDialog.selectFile(dir + "/MyFile.txt");
#else
fileDialog.setDirectory(dir);
#endif
...
A: This is a bug in Qt that is reportedly fixed in Qt 5.0.1 and Qt 4.8.4 (though it seems that it still reproducible in 4.8.4 by people (myself included)).
This bug has been reported in JIRA as QTBUG-20771, QTBUG-28161 and finally QTBUG-35779 (which appears to have finally fully resolved the issue in Qt 5.2.1). Here is a link to the patch in Gerrit. | unknown | |
d19450 | test | Your way of chaining .Where() into .Where() is technically correct. The problem is that the outer .Where() under the current situation does not evaluate to boolean. However, that's a requirement. The purpose of a .Where() is to define a filter for a collection that results in a subset of that collection. You can check whether .Any() item fulfills that condition:
@foreach (var artikel in Controller.Artikel
.Where(x => x.LieferantenArtikel
.Any(y => y.Lieferant.LieferantId == bestellung.LieferantId))
)
{
<option value="@artikel.Artikelnummer">@artikel.Artikelnummer</option>
}
.
A: To add a bit more context to the other answers, which hopefully helps you to understand how to efficiently use LINQ:
What you tried to program using .Where() is technically "where exists". Translated into LINQ naively, that would be
Controller.Artikel
.Where(x =>
x.LieferantenArtikel
.Where(y => y.Lieferant.LieferantId == bestellung.LieferantId)
.Count() > 0 // naive "exists", but bad; for reasons see below
)
.Count() > 0 however is very inefficient, since this would require the execution of .Count() to evaluate the statement, which in turn requires to determine the accurate result set.
This is where .Any() steps in: it only determines if there is at least one element in the IEnumerable by checking them and immediately returning true when the first item matches. So only if there is no match, all items of "LieferantenArtikel" have to be enumerated and checked, otherwise a smaller subset will do.
A: I find non-nested LINQs to be much more readable. Flatten things out with SelectMany, and then use Where. Note that you need to make sure Equals() is implemented in Artikel so Distinct() does its job properly.
var artikels = Controller.Artikel
.SelectMany(x => x.LieferantenArtikel, (x, l) => (Artikel: x, Lieferant: l))
.Where(x => x.Lieferant.LieferantId == bestellung.LieferantId)
.Select(x => x.Artikel)
.Distinct();
@foreach(var artikel in artikels)
{
<option value="@artikel.Artikelnummer">@artikel.Artikelnummer</option>
} | unknown | |
d19451 | test | I have the same issue with eval-source-map, so I finally switch back to source-map.
However, I do find two approaches to make eval-source-map work, quite dirty though.
*
*Insert a debugger in the JS file you are working on. Open DevTools before you visit the page, then the debugger will bring you to the right place, add your break points and they should work now.
*Or insert console.log('here is it') instead of debugger. Then open DevTools -> Console, on the right end of the line, a link will bring you to the place where console.log fires. Add your break points and they should also work. | unknown | |
d19452 | test | There is a problem in param values. Change param values as follows.
$stmt = $this->conn->prepare("SELECT ur.restaurant_id, ur.service_rating, ur.food_rating, ur.music_rating FROM user_ratings ur , user u WHERE u.user_id = ? AND u.user_id = ur.user_id AND ur.rating_id = ?");
$stmt->bind_param("ii", $user_id,$rating_id);
According to your sql first param should be $user_id. Not the $rating_id.
According to your parameter settings there is no record to fetch. | unknown | |
d19453 | test | Use it something like this
for API level 5 and greater
@Override
public void onBackPressed() {
super.onBackPressed()
if (keycode == KeyEvent.KEYCODE_BACK) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
finish();
}
}
older than API 5
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
finish();
}
}
return super.onKeyDown(keycode, event);
}
Let me know if it works for you
A: Remove this.finishAffinity(); from onBackPressed()
SAMPLE CODE
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
finish();
}
} | unknown | |
d19454 | test | Left Join and Where condition can help you.
SELECT *
FROM teachers t
LEFT
JOIN courses c
ON t.id = c.teacher_id
WHERE c.teacher_id IS NULL
A: Teachers don't usually "take" courses. They "teach" courses. Students "take" courses.
That said, not exists seems appropriate:
SELECT t.*
FROM teachers t
WHERE NOT EXISTS (SELECT 1
FROM courses c
WHERE c.teacher_id = t.id
);
If you think about this, it is almost a direct translation of your question: Get teachers where there is no course that the teacher teachers. | unknown | |
d19455 | test | You can define single AEVL class for both AEVL2020 and AEVL2020 as follow:
public class AEVL
{
public string user_id { get; set; }
public string employee_id { get; set; }
public string name { get; set; }
public string privilege { get; set; }
}
public class Registers
{
public List<AEVL> AEVL2020 { get; set; }
public List<AEVL> AEVL2021 { get; set; }
}
Then your code would be like this and you can get items based on given string:
var aevlProp = root.registers.GetType().GetProperty("AEVL2020");
var values = (aevlProp.GetValue(root.registers, null) as List<AEVL>);
foreach (var p in values)
{
Console.WriteLine(p.user_id + p.name + p.employee_id + p.privilege);
}
Output for GetProperty("AEVL2020");
1Juan Dela Cruz120
2Pedro Dela Cruz320
Output for GetProperty("AEVL2021");
1Maria Del Mundo290
2Jay Del Mundo2220
A: Something like this i guess
Given
public class SomeObject
{
public string user_id { get; set; }
public string employee_id { get; set; }
public string name { get; set; }
public string privilege { get; set; }
}
public class RootObject
{
public Dictionary<string, List<SomeObject>> registers { get; set; }
}
Usage
var input = "{\r\n\"registers\":{\r\n \"AEVL2020\":[\r\n {\r\n \"user_id\": \"1\",\r\n \"employee_id\": \"12\",\r\n \"name\": \"Juan Dela Cruz\",\r\n \"privilege\": \"0\"\r\n },\r\n {\r\n \"user_id\": \"2\",\r\n \"employee_id\": \"32\",\r\n \"name\": \"Pedro Dela Cruz\",\r\n \"privilege\": \"0\"\r\n }\r\n ],\r\n \"AEVL2021\":[\r\n {\r\n \"user_id\": \"1\",\r\n \"employee_id\": \"29\",\r\n \"name\": \"Maria Del Mundo\",\r\n \"privilege\": \"0\"\r\n },\r\n {\r\n \"user_id\": \"2\",\r\n \"employee_id\": \"222\",\r\n \"name\": \"Jay Del Mundo\",\r\n \"privilege\": \"0\"\r\n }\r\n ]\r\n }\r\n}";
var r= JsonConvert.DeserializeObject<RootObject>(input);
// choose the name you want here
var values = r.registers["<Name>"];
foreach (var p in values )
Console.WriteLine(p.user_id + p.name + p.employee_id + p.privilege); | unknown | |
d19456 | test | data is sent as the request body. What you really want is headers.
From the docs:
*
*data – {string|Object} – Data to be sent as the request message data.
*headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Functions accept a config object as an argument.
Example:
$http({
...
headers: {
username: "akram",
password: "yes"
}
})
A: When you use @HeaderParam, you have to pass the values from .JS using headers: { 'something': 'anything' }. As i can see currently you are using data : {username: "akram",password:"yes"}. try to use headers: { 'something': 'anything' } instead of this.
Please try header, hope it will solve your null issue. | unknown | |
d19457 | test | It depends on what exactly you want to mutate.
*
*If you really want to reassign the field values::Vector{Int64} itself, then you have to use a mutable struct. There's no way around that, because the actual data of the struct changes when you reassign that field.
*If you use an immutable struct with a values::Vector{Int64} field, it means that you cannot change which array is contained, but the array itself is mutable and can change its elements (which are not stored in the struct). In this case, you really do have to copy values to it from external arrays, like your example code (though I would point out that your code did not reset the array to an empty one). I personally think this would be cleaner:
function set_values!(list::NumberedList, new_values::Vector{Int64})
empty!(list.values) # reset list.values to Int64[]
append!(list.values, new_values)
end
*The thread you linked talks about using Base.Ref. Base.Ref is pretty much THE way to make a field of an immutable struct indirectly act like a mutable field. It works like this: the field cannot change which RefValue{Vector{Int64}} instance is contained, but the instance itself is mutable and can change its reference (again, not stored in the struct) to any Int64 array. You have to use indexing values[] to get to the array, though:
struct NumberedList
index::Int64
values::Ref{Vector{Int64}}
NumberedList(i) = new(i, Int64[])
end
function set_values!(list::NumberedList, new_values::Vector{Int64})
list.values[] = new_values # "reassign" different array to Ref
end
# ---
mylist = NumberedList(1)
set_values!(mylist, [1, 2, 3]) | unknown | |
d19458 | test | To generate a link that is universal and not specific to an App Store Country do the following
Use
itms-apps://**ax.itunes**.apple.com/app/yourAppLinker
where yourAppLinker is the part of the link generated in (http://itunes.apple.com/linkmaker), as in Matthew Frederick's post, which contains your application name and id
it worked for me
cheers
A: For IOS7 and later for example:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/app/id547101139"]];
A: *
*You can get the appropriate URL to your app here:
http://itunes.apple.com/linkmaker
If you enter the name of your company the linkmaker will provide an "artist link" that shows all of your apps.
*If you use the itms-apps:// prefix the user is sent directly to the
App Store App with the specified app showing rather than the ugly
first-Safari-then-the-App-Store-App shuffle that you get without that
UTI. A la:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:
@"itms-apps://yourAppLinkHere"]]; | unknown | |
d19459 | test | You need to create a Windows Runtime component by creating a class library from the "Visual C#" -> "Windows Metro Style" -> "Class Library" template. Then in the properties for that class library project you need to mark the output type as "WinMD File"
Better instructions can be found here:
http://msdn.microsoft.com/en-us/library/windows/apps/hh779077(v=vs.110).aspx
This isn't stated in the documentation and is probably just a bug with the Windows 8 Consumer Preview and the Visual Studio 11 Beta but be sure not to include a period in the name of the project you're referencing. For instance, I was working on a Car application so I made an assembly named "Car.Business". The application would always crash with a blank startup screen whenever I tried to reference this. If on the other hand I just used "Business" as the name of the assembly then the application would work fine. | unknown | |
d19460 | test | You should take a look at how "Twitter Bootstrap" outlines their media query structure at http://getbootstrap.com/css/#grid-media-queries
Try comparing those with your own written media query structure, and if you are still stuck, you should check out Chris' written media query set at https://stackoverflow.com/a/21437955/4069464
Hope this helps!
Note: If after you have setup all the proper media query sets, and somehow this is still not working for the UC browser, then you probably have to read out in detail on how UC browser defines their mobile screen size (possibly they might have defined themselves a different set of definition of screen sizes) | unknown | |
d19461 | test | try:
$('ul li').on('mouseenter mouseleave', function() {
$(this).find('.overview').toggleClass('top_out');
});
A: You have to use the hovered over li as the context:
$("ul li").hover(function(){
$(".overview", this).toggleClass("top_out");
});
Rather than .hover(function() ... you may want to use:
.on('mouseenter mouseleave', function() ...
$("ul li").on('mouseenter mouseleave', function(){
$(".overview", this).toggleClass("top_out");
});
.top_out {
background-color: black;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>
<div class="overview top_out">Eye</div>
<div class="link bottom_out">link</div>
<div class="image"></div>
</li>
<li>
<div class="overview top_out">Eye</div>
<div class="link bottom_out">link</div>
<div class="image"></div>
</li>
</ul>
A: It seems like you need to toggle the class based on the context of the element you are hovering over.
Use the jQuery selector $(".overview", this) to select .overview elements within the li element that is currently being moused over.
I also change the hover event to mouseover/mouseout.
$("ul li").on('mouseover mouseout', function () {
$(".overview", this).toggleClass("top_out");
});
Which is essentially equivalent to
$("ul li").on('mouseover mouseout', function () {
$(this).find(".overview").toggleClass("top_out");
}); | unknown | |
d19462 | test | You can use the even rule to target all the even children, like this.
li:nth-child(even) a {
color: white;
}
Here's a reference: https://www.w3.org/Style/Examples/007/evenodd.en.html
A: In your first example, you are saying "the nth li" of which there are several. In the second example, you are saying "the nth a in a li" of which there is only one.
A: Perhaps it worked taking all lis together strange
li:nth-child(2n)>a
{ color:white} | unknown | |
d19463 | test | Due to your current indentation, coordpairs is only seeing the last value of longitudes each time it loops through y.
If you would like to use loops, you could do something like this (assuming your longitudes and latitudes lists are the same length)
coordpairs = []
for coord_num in range(len(longitudes)):
coord_pair = [longitudes[coord_num], latitudes[coord_num]]
coordpairs.append(coord_pair)
If you want to combine each item in longitudes with each item in latitudes without using loops, you can use
list(zip(longitudes, latitudes)) | unknown | |
d19464 | test | You should use Enumerable.Skip(Int32)
public IEnumerable<PersonViewModel> GetAllStudents(int page)
{
const int PageSize = 2;
IEnumerable<Person> dbPersons = _repo.getPersons().OrderBy(s => s.ID).Skip(page * PageSize).Take(PageSize);
List<PersonViewModel> persons = new List<PersonViewModel>();
foreach(var p in dbPersons)
{
persons.Add(MapDbPieToPersonViewModel(p));
}
return persons;
} | unknown | |
d19465 | test | You just drag an NSMenu from the object library and release it over the segment you want it to be attached to. | unknown | |
d19466 | test | You didn't close
conn.Open();
Add conn.Close in try-catch's finally
finally
{
conn.Close();
}
Add max pool size in your connection string
Like this
public const String connectionString = "server=localhost; uid=root; pwd=; database=it_map;max pool size=5;"; | unknown | |
d19467 | test | As you can see in the error message, rails is looking for a file called reviews/create[extension] or application/create[extension] and extensions allowed are .erb, .builder, .raw, .ruby, .coffee or .jbuilder.
I suggest to change you ajax call to ask for js, not json, create a file called reviews/create.js.erb, and add this kind of code :
<% if @restaurant.reviews.find_by user_id: current_user.id %>
// do the code to show the error message in javascript
<% else %>
reviewList.append("<%= j(render('create')) %>");
currentRestaurant.find('.review_count').text(<%= pluralize(@restaurant.reviews.count, 'reviews') %>)
currentRestaurant.find('.average_rating_number').text(<%= number_with_precision(@restaurant.average_rating, precision: 1) %>);
currentRestaurant.find('.average_rating_stars').text(<%=star_rating(@restaurant.average_rating) %>);
<% end %>
This code should be executed after the success of the creation. You also have to create a file called reviews/_create.html.erb with the html you want to show. Finally, you have to delete some logic in the javascript and in the controller. | unknown | |
d19468 | test | Well as @kfx pointed out in the comments const struct aes_128_driver AES_128 was shadowing the global variable. | unknown | |
d19469 | test | I copied your example into a test file, and it works fine. I also can't see how the error message in your example could be generated by the current version of noUiSlider, so I'd suggest using the latest version of noUiSlider and the latest version of jQuery.
It would also be a good idea to only run this JS after the page has loaded, like this:
$(function() {
$("#sslider").noUiSlider({
start: 5,
range: {
'min': 1,
'max': 80
}
});
});
A: Ok, problem solved. I have downloaded jquery.nouislider.js from NuGet (from VisualStudio 2013) and they provided me older or broken file. I thought the file was from website, but I browsed NuGet and noticed, that I have already downloaded from there.
There is no problem with code but with file. Lesson: before asking question, compare official files with those you already have installed.
A: Try to follow the official docs:
$("#slider").noUiSlider({
start: [5],
connect: true,
range: {
'min': 1,
'max': 80
}
}); | unknown | |
d19470 | test | It's been a looong time since I used FaxComExLib, but if memory serves, you need to install the Fax printer or something for XP, it is not installed by default. | unknown | |
d19471 | test | why do you wish to have an empty array as a default column values? That isn't correct to assign an empty array to value of DB column, because it must be specifically serialized. Instead define methods in model, which will return empty array for specific column:
def some_field
read_attribute(:some_field) || []
end
def other_field
read_attribute(:other_field) || []
end
But better way is to define that methods not in model, but in a serializer or decorator. | unknown | |
d19472 | test | item is a string, so borderLength + item + 1 actually does string concatenation instead of arithmetical addition. Assuming map contains numerical values, you should write map?values, not map?keys. | unknown | |
d19473 | test | You can assign the output of the command to a string.
Use 2>&1 to redirect stderr to stdout and thus capture all the output.
str = `git pull origin master 2>&1`
if $?.exitstatus > 0
...
elsif str =~ /up-to-date/
...
else
...
end | unknown | |
d19474 | test | Thanks to ekhumoro for guiding me to the answer. The QsciAPIs class has a load method, and PyQt comes with a set of api files. Below is the code that does proper autocompletion in the manner I was looking for:
"""Base code originally from: http://kib2.free.fr/tutos/PyQt4/QScintilla2.html"""
import sys
import os
import PyQt5
from PyQt5 import QtWidgets, Qsci
app = QtWidgets.QApplication(sys.argv)
editor = Qsci.QsciScintilla()
lexer = Qsci.QsciLexerPython(editor)
editor.setLexer(lexer)
## setup autocompletion
api = Qsci.QsciAPIs(lexer)
# import the desired api file
pyqt_path = os.path.dirname(PyQt5.__file__)
api.load(os.path.join(pyqt_path, "Qt/qsci/api/python/Python-3.6.api"))
api.prepare()
editor.setAutoCompletionThreshold(1)
editor.setAutoCompletionSource(Qsci.QsciScintilla.AcsAll)
editor.show()
editor.setText(open(sys.argv[0]).read())
sys.exit(app.exec_())
A: qscintilla does not know the keywords of python nor of the libraries, QsciAPIs hopes that you provide information, in the following part I show some functions that return the keywords and the name of the standard libraries. qscintilla will only autocomplete with the words you provide, if you want an intelligent autocomplete, I recommend you do a logic that recognizes the points or parenthesis and filter the words you provide to QsciAPIs.
import sys
from PyQt5 import QtWidgets, Qsci
import keyword
import pkgutil
app = QtWidgets.QApplication(sys.argv)
editor = Qsci.QsciScintilla()
lexer = Qsci.QsciLexerPython()
editor.setLexer(lexer)
## setup autocompletion
api = Qsci.QsciAPIs(lexer)
for key in keyword.kwlist + dir(__builtins__):
api.add(key)
for importer, name, ispkg in pkgutil.iter_modules():
api.add(name)
api.prepare()
editor.setAutoCompletionThreshold(1)
editor.setAutoCompletionSource(Qsci.QsciScintilla.AcsAPIs)
editor.show()
editor.setText(open(sys.argv[0]).read())
sys.exit(app.exec_()) | unknown | |
d19475 | test | Check this
var frequency = 10000;
var data = {
1: {duration:500, sleep:1000},
0: {duration:500, sleep:500}
}
var audio = new window.webkitAudioContext();
//function creates an Oscillator. In this code we are creating an Oscillator for every tune, which help you control the gain.
//If you want, you can try creating the Oscillator once and stopping/starting it as you wish.
function createOscillator(freq, duration) {
var attack = 10, //duration it will take to increase volume full sound volume, makes it more natural
gain = audio.createGain(),
osc = audio.createOscillator();
gain.connect(audio.destination);
gain.gain.setValueAtTime(0, audio.currentTime); //change to "1" if you're not fadding in/out
gain.gain.linearRampToValueAtTime(1, audio.currentTime + attack / 1000); //remove if you don't want to fade in
gain.gain.linearRampToValueAtTime(0, audio.currentTime + duration / 1000); //remove if you don't want to fade out
osc.frequency.value = freq;
osc.type = "square";
osc.connect(gain);
osc.start(0);
setTimeout(function() {
osc.stop(0);
osc.disconnect(gain);
gain.disconnect(audio.destination);
}, duration)
}
function play() {
//your pattern
var song = [1,0,1,1];
timeForNext = 0;
for (i=0;i<song.length;i++){
duration = data[song[i]].duration;
//use timeout to delay next tune sound
window.setTimeout(function(){
createOscillator(frequency, duration);
},timeForNext);
timeForNext+=data[song[i]].sleep;
}
}
//play the music
play();
This link has some good info http://www.bit-101.com/blog/?p=3896 I used it to create a piano app with Cordova a while ago. Still haven't published it though. | unknown | |
d19476 | test | You seem to be describing the function of the Silverlight Popup class. | unknown | |
d19477 | test | So, you are using discord.js v13 which is a lot different from the previous version which is v12. In v13, it is compulsory to add intents.
You can read this for more information: here
A: new Discord version V13 requires you to set the intents your bot will use.
First, you can go to https://ziad87.net/intents/ where you can choose the intents you want and gives you a number, you should use that number like this:
const intents = new Discord.Intents(INTENTS NUMBER);
const client = new Discord.Client({ intents });
For example, if you want all the intents, you will have:
const intents = new Discord.Intents(32767);
const client = new Discord.Client({ intents }); | unknown | |
d19478 | test | Are you sure you have the same zookeeper clickhouse settings on all 3 nodes?
Do you insert into Distributed table or insert into ReplicatedMergeTree?
For first case, check on node-2
SELECT * FROM system.distribution_queue FORMAT Vertical
SELECT * FROM system.clusters FORMAT Vertical
and compare <remote_servers> section in your config for all 3 nodes | unknown | |
d19479 | test | You are using ODBC so you must only specify DSN:
DSN=myDsn;Uid=myUsername;Pwd=;
The jdbc:odbc is just a designation that the java driver uses and is not carried over to ODBC in .NET. I would suggest you use ADO.NET if that is an option.
or this for the TDConnection:
Data Source=myDsn;User Id=uid;Password=pwd; | unknown | |
d19480 | test | I think you may be slightly confused about <br> tags. <br> or <br /> are self-closing/void elements/empty tags:
https://www.w3schools.com/html/html_elements.asp (under the empty html section)
http://xahlee.info/js/html5_non-closing_tag.html
<br> is an empty element without a closing tag (the <br> tag defines a line break):
So when you're subbing in <br><br /> you're actually subbing in two line breaks. From your description it sounds as if you only want one line break, so you'll want to remove one of them. | unknown | |
d19481 | test | A modal window is loaded via javascript in the same page. If you want to open a new browser window or tab (popup window) you should add the atribute type="_blank" in your link (no javascript needed).
<a href="popoup_url" target="_blank">Open popup</a> | unknown | |
d19482 | test | onChange = {e => this.changeHandler(e, el.id) }
grab el.id on changeHandler and store in state, use this state in your api call. | unknown | |
d19483 | test | Replace your input loop with this:
std::string str;
while (std::getline(txtfile, str)){
vfile.push_back(str);
}
Using ios::eof() as a loop condition almost always creates a buggy program, as it did here. In this case, using eof() has two problems. First, eof() is only set after the read fails, not before, but you are checking it before the read. Second, eof() doesn't check the range of other errors. When an input line has more than 200 characters, istream::getline sets failbit, but not eofbit.
EDIT: With the added requirement of limiting the input lines to 200 characters, this should work:
// untested
std::string str;
while(std::getline(txtfile, str)) {
if(str.size() > 200)
str.erase(200, std::string::npos);
vfile.push_back(str);
} | unknown | |
d19484 | test | You need to do a few things.
First, in calculate.py call the mytest function, add the following at the end:
if __name__ == '__main__':
print(mytest())
Now when you execute the calculate.py script (e.g. with python3 /path/to/calculate.py), you'll get the mytest's return value as output.
Okay, now you can use subprocess.check_output to execute the script, and get output:
returned_bin = subprocess.check_output('/usr/bin/python3 /path/to/calculate.py'.split())
Replace the paths accordingly.
The value of returned_val would be binary string. You need to decode it to get the respective text string:
returned_val = returned_bin.decode('utf-8') # assuming utf-8
Now, as the returned value from myfunc is a dict and in returned_val is a string,
you can use json.loads(returned_val) to get the same dict representation back.
A: subprocess.check_output
import subprocess
[ print(i) for i in subprocess.check_output(['ls']).split() ]
output, my current directory:
b'a.sh'
b'app'
b'db'
b'old.sh' | unknown | |
d19485 | test | by tag mysqli I can assume that You're using PHP.
So it can be done this way:
$year = '2015';
$data = [];
foreach(range(1, 12) AS $month) {
$data[$month] = [
'date_year' => $year,
'date_month' => $month,
'nb_item' => 0
];
}
$q = "SELECT
year(feed_date) as date_year,
month(feed_date) as date_month,
count(*) as nb_item
FROM table
WHERE year(feed_date) = '".$year."'
GROUP BY date_year, date_month";
$q = mysqli_query($q);
while($record = mysqli_fetch_assoc($q)) {
$data[$record['date_month']]['nb_item'] = $record['nb_item'];
}
$data = array_values($data);
print_r($data);
or with mysql it will be huge query:
SELECT
year(table.feed_date) AS date_year,
month(table.feed_date) AS date_month,
COALESCE(count(*), 0) as nb_item
FROM (
SELECT 1 as month
UNION ALL SELECT 2
UNION ALL SELECT 3
UNION ALL SELECT 4
UNION ALL SELECT 5
UNION ALL SELECT 6
UNION ALL SELECT 7
UNION ALL SELECT 8
UNION ALL SELECT 9
UNION ALL SELECT 10
UNION ALL SELECT 11
UNION ALL SELECT 12
) months
LEFT JOIN table ON (months.month = month(table.feed_date))
WHERE year(table.feed_date) = '2015'
GROUP BY date_year, date_month;
A: You need a table containing all the year-month combinations for a LEFT JOIN. You can create it on the fly by cross joining all years and months:
SELECT y.date_year, m.date_month, count(*) as nb_item
FROM (
SELECT 1 as date_month UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9 UNION ALL
SELECT 10 UNION ALL
SELECT 11 UNION ALL
SELECT 12
) m
CROSS JOIN (
SELECT 2015 as date_year
) y
LEFT JOIN `table` t
ON year(t.feed_date) = y.date_year
AND month(t.feed_date) = m.date_month
AND t.feed_title LIKE '%word%'
AND t.source = '3'
GROUP BY y.date_year, m.date_month
If you have a helper table with sequence numbers you can shorten the query to:
SELECT y.seq as date_year, m.seq as date_month, count(*) as nb_item
FROM sequences y
CROSS JOIN sequences m
LEFT JOIN `table` t
ON year(t.feed_date) = y.date_year
AND month(t.feed_date) = m.date_month
AND t.feed_title LIKE '%word%'
AND t.source = '3'
WHERE y.seq IN (2015)
AND m.seq <= 12
GROUP BY y.seq, m.seq
A: You can join the selected data with a subquery that gets all the existing years and months from the table.
SELECT t1.date_year, t1.date_monthmonth, IFNULL(t2.nb_item, 0) AS nb_item
FROM (SELECT DISTINCT YEAR(feed_date) AS date_year, MONTH(feed_date) AS date_month
FROM table) AS t1
LEFT JOIN (
SELECT year(feed_date) as date_year,
month(feed_date) as date_month,
count(*) as nb_item
FROM table
WHERE year(feed_date) = '2015' AND
feed_title LIKE '%word%' AND
source = '3'
GROUP BY date_year, date_month) AS t2
ON t1.date_year = t2.date_year AND t1.date_month = t2.date_month
ORDER BY t1.date_year, t1.date_month | unknown | |
d19486 | test | startActivity() involves inter-process communication, even when the activity you are starting is in the same app and the same process. Android will ignore your subclass, because the OS process that handles startActivity() requests cannot use your subclass, as that is in your app, and the OS process is not your app. And, the IPC that delivers the request to start the activity back to your process will not know anything about your subclass.
Either:
*
*Combine these into one activity (e.g., using two fragments), or
*Use some sort of singleton data manager that both activities can work with | unknown | |
d19487 | test | You will have to fetch file field from request Object with following code:
form = UpdatePhotoForm(data=request.POST, files=request.FILES, instance=request.user.person) | unknown | |
d19488 | test | Assuming you want to match an entire string, you may use something like the following:
^[a-zA-Z_](?:\w|(?<=\w)\.(?=\w))*(?:\(\d+\))?$
Demo.
If you want to match partial strings, you'd need to decide what boundaries are allowed. Otherwise, "SomeVar(10" would have a match (i.e., what comes before (), for example.
Notes:
*
*\w matches a lowercase/uppercase letter, a digit, or an underscore. But it also matches Unicode letters and numbers. If you don't want that, you could use [a-zA-Z0-9_] instead.
*Similarly, \d matches any Unicode digit. You either use it or use [0-9] depending on your requirements.
A: Use
^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*(\([^()]*\))?$
See proof.
*
*[a-zA-Z_][a-zA-Z0-9_]* - a letter or underscore, then zero or more letters, digits, underscores
*(\([^()]*\))? - optional group, parens may be present or absent
*(\.[a-zA-Z_][a-zA-Z0-9_]*)* - dot is allowed between letter/digit/underscore. | unknown | |
d19489 | test | What worked for me was to replace localhost with container links. I found this tutorial helpful.
parse-server:
...
environment:
...
DATABASE_URI: mongodb://mongo:27017/myDB
links:
- mongo:mongo
mongo:
image: mongo
volumes:
- /mnt/database/mongodb
TLDR: tutorial: docker-compose.yml
mongo-parse-server:
image: mongo
parse-server:
image: yongjhih/parse-server
links:
- mongo-parse-server:mongo
environment:
- APP_ID=LWP_APP
- MASTER_KEY=DA5AC2FF-8F44-4082-8E5C-A78F2A96ACAD
- FILE_KEY=1DAFE373-5D8A-4E7A-AD05-67C3BA0EDB64
ports:
- 1337:1337
parse-dashboard:
image: yongjhih/parse-dashboard
environment:
- PARSE_DASHBOARD_CONFIG={"apps":[{"appId":"LWP_APP","serverURL":"http://192.168.99.100:1337/parse","masterKey":"DA5AC2FF-8F44-4082-8E5C-A78F2A96ACAD","appName":"LWP"}],"users":[{"user":"foo","pass":"bar"}]}
- PARSE_DASHBOARD_ALLOW_INSECURE_HTTP=1
ports:
- 4040:4040 | unknown | |
d19490 | test | You can use isLength() option of the express-validator to check max and min length of 5:
req.checkBody('partnerid', 'Partnerid field must be 5 character long ').isLength({ min: 5, max:5 });
A: You can use matches option of express-validator to check if the partner field only contains alphanumeric and has a length of 5
req.checkBody('partnerid', 'Partnerid field must be 5 character long ').matches(/^[a-zA-Z0-9]{5}$/, "i");
A: .len(5) not support in express validation, you can use .isLength(5) to check for a max and min length of 5.
req.checkBody('partnerid', 'Partnerid field must be 5 character long strong text').isLength(5); | unknown | |
d19491 | test | Try it:
parent.window.location = "http://your.url.com";
I think it's enough. | unknown | |
d19492 | test | use val() to set textarea's value
var string = "your html content";
var textarea=$('<textarea>').val( string).appendTo( containerSelector); | unknown | |
d19493 | test | 'scaled' using plt
The best thing is to use:
plt.axis('scaled')
As Saullo Castro said. Because with equal you can't change one axis limit without changing the other so if you want to fit all non-squared figures you will have a lot of white space.
Equal
Scaled
'equal' using ax
Alternatively, you can use the axes class.
fig = plt.figure()
ax = figure.add_subplot(111)
ax.imshow(image)
ax.axes.set_aspect('equal')
A: There is, I'm sure, a way to set this directly as part of your plot command, but I don't remember the trick. To do it after the fact you can use the current axis and set it's aspect ratio with "set_aspect('equal')". In your example:
import matplotlib.pyplot as plt
plt.fill(*zip(*polygon))
plt.axes().set_aspect('equal', 'datalim')
plt.show()
I use this all the time and it's from the examples on the matplotlib website.
A: Does it help to use:
plt.axis('equal')
A: Better plt.axis('scaling'), it works better if you want to modify the axes with xlim() and ylim(). | unknown | |
d19494 | test | ... It's ok ! I found my problem. I forgot to erase the tatoo out of a json list containing them all.
It looks like this now :
for(var i=0; i< tatoos.length; i++){
if(tatoos[i].url === url ){
tatoos.splice(i, 1);
}
}
$(this).removeClass('ui-state-highlight');
$(this).removeClass('ui-selected');
$(this).children(':nth-child(4)').removeClass( "tatooSelect" ); | unknown | |
d19495 | test | You can manage Azure NSG configuration via ARM template, Teffaform and Ansible.
*
*ARM template
1,You can check out below examples to create ARM Template to manage Azure NSG.
Create a Network Security Group.
How to create NSGs using a template
Please check the official document for more examples.
2, After the ARM template is created and pushed to your git repo. You can create azure pipeline to automate the deployment. See tutorial here.
3, Then you need to create an azure Resource Manager service connection to connect your Azure subscription to Azure devops. See this thread for an example.
4, In your azure devops pipeline. You can use ARM template deployment task to deploy the ARM template.
steps:
- task: AzureResourceManagerTemplateDeployment@3
displayName: 'ARM Template deployment: Resource Group scope'
inputs:
azureResourceManagerConnection: 'azure Resource Manager service connection'
subscriptionId: '...'
resourceGroupName: '...'
location: 'East US'
csmFile: azuredeploy.json
csmParametersFile: azuredeploy.parameters.json
*
*Teffaform
1, Create Teffaform configuration file. See example here.
Check out terraform-azurerm-network-security-group module for more information.
2, Upload Teffaform configuration file to git repo. Create Azure devops pipeline
3, Create azure Resource Manager service connection like above using ARM template.
4, Use Terraform task in the azure devops pipeline.
steps:
- task: ms-devlabs.custom-terraform-tasks.custom-terraform-installer-task.TerraformInstaller@0
displayName: 'Install Terraform 0.12.3'
- task: ms-devlabs.custom-terraform-tasks.custom-terraform-release-task.TerraformTaskV1@0
displayName: 'Terraform : azurerm'
inputs:
command: apply
environmentServiceNameAzureRM: 'azure Resource Manager service connection'
*
*Ansible
1, Create Ansible playbook with plugin azure.azcollection.azure_rm_securitygroup
Please check out the example here.
2,Upload ansible playbook to git repo. Create Azure devops pipeline. Use Ansible task in your pipeline.
Please check out this detailed tutorial for more information about how to run ansible playbook in azure devops pipeline.
*
*Azure powershell/Azure CLI commands
You can using azure powershell or azure cli commands to manage azure nsg. And run the commands in Azure powershell task or azure cli task in azure devops pipeline.
Please check out this document for more information. | unknown | |
d19496 | test | Just looking at the code that you posted here, I wonder if the last parameter is indeed the value that you wanted to pass to the constructEvent function. it reads webHookPaymentIntent. I wonder if this should really be the webhook signature secret? It may be that it really is the webhook secret value, but just named a bit misleadingly.
Maybe this is something though you can verify? A simple test would really to be to pass the string literal here to see if that would work first. Of course make sure not to commit that to any source control.
The stripe-node method params are listed here for reference: https://github.com/stripe/stripe-node/blob/1d6207e34f978d8709d42d8a05d7d7e8be6599c7/lib/Webhooks.js#L11 | unknown | |
d19497 | test | In principle, it's good. In practice, though, it has at least the following problems:
*
*not all fonts look good at all sizes and not all browsers do a good job at approximating them. Most problems appear when elements start being animated and, because of the approximation techniques, text looks blurry while the animation is in progress. What's worse is that animating other elements in the page affects text that is not being animated (shouldn't budge), producing a weird effect. (i.e: text blurs when opening/closing the menu...).
To work around this problem, some problematic fonts have been optimized for values of font-size expressed in px (they look good at 15px and 16px - not so much at 15.5px). The blurring effect still happens, but it's not as noticeable at some values.
*this technique needs an exception on narrow mobile devices. One needs to be able to read text even on narrow screens
Other than that, Bootstrap 4 does use rem for padding. They tried to do it in v3 as well, but reverted due to poor browser support. | unknown | |
d19498 | test | You can build your Window, and set the Background="Transparent" like so:
<Window ...
AllowsTransparency="True"
WindowStyle="None"
Background="Transparent" >
This gives you a window with a transparent background and no border. | unknown | |
d19499 | test | Try this:
SELECT $path FROM ( TRAVERSE out() FROM (select from entities where id ='A') WHILE $depth <= N ) where id ='B' | unknown | |
d19500 | test | WSO2 Developer Studio uses Eclipse bpel plugin to add support for bpel creation for WSO2 BPS. This BAM publishing bpel extension activity that you are referring to, is a custom extension developed by WSO2 and default bpel editor is not aware of this extension. This is why it gives syntax errors when you add this extension activity from the source view.
However, you should be able to export and deploy the CAR file without any issues regardless of the syntax errors.
According to this, there's a possibility to add support for custom extension activities in bpel editor.
Hence, I have raised a jira in WSO2 BPS Tooling jira for this feature.
Thanks. | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.