problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
Why do we need `*args` in decorator? : <pre><code>def pass_thru(func_to_decorate):
def new_func(*args, **kwargs): #1
print("Function has been decorated. Congratulations.")
# Do whatever else you want here
return func_to_decorate(*args, **kwargs) #2
return new_func
def print_args(*args):
for arg in args:
print(arg)
a = pass_thru(print_args)
a(1,2,3)
>> Function has been decorated. Congratulations.
1
2
3
</code></pre>
<p>I understand that <code>*args</code> is used in #1 since it is a function declaration. But why is it necessary to write <code>*args</code> in #2 even if it not a function declaration? </p>
| 0debug
|
document.write('<script src="evil.js"></script>');
| 1threat
|
how to open email app and display text in label with single click : i have a table with accept link in the first column when the it is clicked then have another column with a label with pending. therefore when thee accept is clicked the **pending** is updated to **accepted**
this line was my original code, when the accept is pressed it is displayed.
<a href="tea_appview.php?app_id=<?php echo $row['app_id'] . "&" . "state=accept";?>" class="accept">accept</a>
--------------------------------------
then i added this line so that i can also send a mail. what happens here is when the accept llink is clicked the default mail app opens but the label does not get updated from pending to accepted
<a href='mailto:".$email."?Subject=PARENT%20INQUERY' "tea_appview.php?app_id=<?php echo $row['app_id'] . "&" . "state=accept";?>" class="accept">accept</a>
| 0debug
|
What would be the correct view that needs to be created to meet the requirements? : I have a set of tables given to me and a specific business requirement that needs to be solved by creating a View in SQL. I am having trouble with understanding joins and stuff etc. I have made an attempt, but I think I am completely wrong and need some help.
The tables are as follows:
tblClients (ClientID, ClientName, ClientAddress, ClientCity, ClientProvince, ClientPostalCode, ClientPhone, ClientEmail)
tblVehicle (VehicleID, VehicleMake, VehicleModel, VehicleYear, ClientID)
tblEmployees (EmployeeID, EmployeeFirstName, EmployeeLastName, EmployeeAddress, EmployeeCity, EmployeeProvince, EmployeePostalCode, EmployeePhone, EmployeeEmail)
tblWorkOrders (OrderID, VehicleID, EmployeeID, WorkDescription, PartsCost, LabourCost, IssueDate, CompletionDate)
________________________________________________________________________________
and the Requirement is this:
A web application is being considered that will allow customers with accounts β using their email address as a login β to view their invoice / work order history with the garage.
Using SQL, create a view that will allow a customer to see work done on each of their cars, including the work description, costs and dates but not which employee completed the work.
________________________________________________________________________________
WHAT I HAVE SO FAR:
CREATE VIEW WORK_HISTORY AS
SELECT WORKDESCRIPTION, PARTSCOST,LABOURCOST, ISSUEDATE, COMPLETIONDATE
FROM TBLWORKORDERS LEFT OUTER JOIN TBLVEHICLE
ON TBLWORKORDERS.VEHICLEID = TBLVEHICLE.VEHICLEID
I dont think its too complicated, but I am new to SQL, so all your help and criticism will be appreciated. If you need anything else please let me know and I will edit as necessary. Thank you!
| 0debug
|
python convert a list to a dict : <p>I am trying to convert a list of lists to a list of dicts, the list is like,</p>
<pre><code>['A', '100000', Timestamp('2017-01-01 00:00:00'), '003']
['B', '100001', Timestamp('2017-02-01 00:00:00'), '004']
</code></pre>
<p>I want to convert it to a list of dicts like,</p>
<pre><code>{'name': 'A', 'id': '100000', 'time': Timestamp('2017-01-01 00:00:00'), 'number': '003'}
{'name': 'B', 'id': '100001', 'time': Timestamp('2017-02-01 00:00:00'), 'number': '004'}
</code></pre>
<p>I am wondering what's the best way to do it.</p>
| 0debug
|
How to pass route parameter in datatable function in laravel to update the datatable using only one blade.php : This is my first post please pardon me.
I have page named data.blade.php .I want to update the data-table of this page for every person id.
My route will be like this /admin/data/1, /admin/data/2, /admin/data/3.
Here 1,2,3 are the person id.I want show the person's element in data-table single.
But though I change the id my data-table stuck on the first id and doesn't change.
| 0debug
|
how to insert id from another table to a table using 1 form : i've been on this for atleast 3 days but i cant seem to get it. i have to get the user_id from the users table and insert it to the user_id of patients table using only one form.
this is the tables i am using:
user_table: user_id is auto increment.
βββββββββββ¦βββββββββββ¦βββββββββββββββββ¦ββββββββββββ
β user_id β level_id β email β password β
β ββββββββββ¬βββββββββββ¬βββββββββββββββββ¬ββββββββββββ£
β 1 β 5 β sasa@denva.com β sasadenva β
β 2 β 1 β tony@stark.com β tonystark β
βββββββββββ©βββββββββββ©βββββββββββββββββ©ββββββββββββ
patients_table: patients_id is auto increment.
+--------+---------+--------------+----------+-----------+--------+
| pat_id | user_id | name | address | number | sex |
| 1 | 1 | sasa mindred | manhatan | 987654329 | female |
| 2 | 2 | tony stark | new york | 123456789 | male |
+--------+---------+--------------+----------+-----------+--------+
i made the name short for the table here.
$sql = "SELECT email FROM users WHERE email=?";
$stmt =mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../auth/register.php?error=sqlerror");
exit();
}else{
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultcheck= mysqli_stmt_num_rows($stmt);
if($resultcheck > 0) {
header("Location: ../auth/register.php?error=emailtaken&last_name=".$last."&first_name=".$first."&middle_name=".$middle."&sex=".$sex."");
exit();
}else{
$sql= "INSERT INTO users (level_id, email, password, created_at) VALUES (?, ?, ?, now())";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("Location: ../auth/register.php?error=sqlerror");
exit();
}else{
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "iss", $lvl, $email, $hashedPwd);
$user_id = mysqli_insert_id($conn);
$sqli = "INSERT INTO patients (user_id, last_name, first_name, middle_name, sex) VALUES ($user_id, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("Location: ../auth/register.php?error=sqlerror");
exit();
}else{
mysqli_stmt_bind_param($stmt, "ssss", $last, $first, $middle, $sex);
mysqli_stmt_execute($stmt);
}
mysqli_stmt_execute($stmt);
header("Location: ../auth/register.php?signup=success".$conn->insert_id."");
exit();
}
}
}
i expected the output to insert the user_id from the users table to the user_id of the patients table
| 0debug
|
what method is created for this? perl : <p>I need an explanation of this one liner. Is this only calling the set() method? Or something else? </p>
<p>Thanks for the help! </p>
<p><code>has 'shape' =>
( is => 'rw' );</code></p>
<p>The object is using MooseX::FollowPBP.</p>
| 0debug
|
static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, int n, const uint8_t *scantable, int qp, int max_coeff){
MpegEncContext * const s = &h->s;
const uint16_t *qmul= dequant_coeff[qp];
static const int coeff_token_table_index[17]= {0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3};
int level[16], run[16];
int suffix_length, zeros_left, coeff_num, coeff_token, total_coeff, i, trailing_ones;
if(n == CHROMA_DC_BLOCK_INDEX){
coeff_token= get_vlc2(gb, chroma_dc_coeff_token_vlc.table, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 1);
total_coeff= coeff_token>>2;
}else{
if(n == LUMA_DC_BLOCK_INDEX){
total_coeff= pred_non_zero_count(h, 0);
coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
total_coeff= coeff_token>>2;
}else{
total_coeff= pred_non_zero_count(h, n);
coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
total_coeff= coeff_token>>2;
h->non_zero_count_cache[ scan8[n] ]= total_coeff;
}
}
if(total_coeff==0)
return 0;
trailing_ones= coeff_token&3;
tprintf("trailing:%d, total:%d\n", trailing_ones, total_coeff);
assert(total_coeff<=16);
for(i=0; i<trailing_ones; i++){
level[i]= 1 - 2*get_bits1(gb);
}
suffix_length= total_coeff > 10 && trailing_ones < 3;
for(; i<total_coeff; i++){
const int prefix= get_level_prefix(gb);
int level_code, mask;
if(prefix<14){
if(suffix_length)
level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length);
else
level_code= (prefix<<suffix_length);
}else if(prefix==14){
if(suffix_length)
level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length);
else
level_code= prefix + get_bits(gb, 4);
}else if(prefix==15){
level_code= (prefix<<suffix_length) + get_bits(gb, 12);
if(suffix_length==0) level_code+=15;
}else{
av_log(h->s.avctx, AV_LOG_ERROR, "prefix too large at %d %d\n", s->mb_x, s->mb_y);
return -1;
}
if(i==trailing_ones && i<3) level_code+= 2;
mask= -(level_code&1);
level[i]= (((2+level_code)>>1) ^ mask) - mask;
if(suffix_length==0) suffix_length=1;
#if 1
if(ABS(level[i]) > (3<<(suffix_length-1)) && suffix_length<6) suffix_length++;
#else
if((2+level_code)>>1) > (3<<(suffix_length-1)) && suffix_length<6) suffix_length++;
? == prefix > 2 or sth
#endif
tprintf("level: %d suffix_length:%d\n", level[i], suffix_length);
}
if(total_coeff == max_coeff)
zeros_left=0;
else{
if(n == CHROMA_DC_BLOCK_INDEX)
zeros_left= get_vlc2(gb, chroma_dc_total_zeros_vlc[ total_coeff-1 ].table, CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 1);
else
zeros_left= get_vlc2(gb, total_zeros_vlc[ total_coeff-1 ].table, TOTAL_ZEROS_VLC_BITS, 1);
}
for(i=0; i<total_coeff-1; i++){
if(zeros_left <=0)
break;
else if(zeros_left < 7){
run[i]= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
}else{
run[i]= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
}
zeros_left -= run[i];
}
if(zeros_left<0){
av_log(h->s.avctx, AV_LOG_ERROR, "negative number of zero coeffs at %d %d\n", s->mb_x, s->mb_y);
return -1;
}
for(; i<total_coeff-1; i++){
run[i]= 0;
}
run[i]= zeros_left;
coeff_num=-1;
if(n > 24){
for(i=total_coeff-1; i>=0; i--){
int j;
coeff_num += run[i] + 1;
j= scantable[ coeff_num ];
block[j]= level[i];
}
}else{
for(i=total_coeff-1; i>=0; i--){
int j;
coeff_num += run[i] + 1;
j= scantable[ coeff_num ];
block[j]= level[i] * qmul[j];
}
}
return 0;
}
| 1threat
|
Console Error on webpage - Javascript : <p>Hello if you go to my site and open up the developer tools I keep getting an error can anyone tell what might be causing that? </p>
<p>I can add more details if necessary just let me know.</p>
<p><a href="http://tommy2.bitballoon.com/" rel="nofollow noreferrer">http://tommy2.bitballoon.com/</a></p>
<p>Thanks,</p>
<p>Tom</p>
| 0debug
|
How to set the value of a JavaFX Spinner? : <p>I'm wondering how to set the value of a JavaFX Spinner, as I haven't been able to figure it out.</p>
<p>I know with Swing you can just use spinner#setValue but it seems to be different with JavaFX.</p>
<pre><code>@FXML
private Spinner<Integer> spinner;
</code></pre>
| 0debug
|
CommonModule vs BrowserModule in angular : <p>I am pretty new to the world of Angular. What is the difference between <code>CommonModule</code> vs <code>BrowserModule</code> and why one should be preferred over the other?</p>
| 0debug
|
void av_log_default_callback(void* ptr, int level, const char* fmt, va_list vl)
{
static int print_prefix=1;
static int count;
static char line[1024], prev[1024];
static int is_atty;
AVClass* avc= ptr ? *(AVClass**)ptr : NULL;
if(level>av_log_level)
return;
line[0]=0;
#undef fprintf
if(print_prefix && avc) {
if (avc->parent_log_context_offset) {
AVClass** parent= *(AVClass***)(((uint8_t*)ptr) + avc->parent_log_context_offset);
if(parent && *parent){
snprintf(line, sizeof(line), "[%s @ %p] ", (*parent)->item_name(parent), parent);
}
}
snprintf(line + strlen(line), sizeof(line) - strlen(line), "[%s @ %p] ", avc->item_name(ptr), ptr);
}
vsnprintf(line + strlen(line), sizeof(line) - strlen(line), fmt, vl);
print_prefix= line[strlen(line)-1] == '\n';
#if HAVE_ISATTY
if(!is_atty) is_atty= isatty(2) ? 1 : -1;
#endif
if(print_prefix && (flags & AV_LOG_SKIP_REPEATED) && !strcmp(line, prev)){
count++;
if(is_atty==1)
fprintf(stderr, " Last message repeated %d times\r", count);
return;
}
if(count>0){
fprintf(stderr, " Last message repeated %d times\n", count);
count=0;
}
colored_fputs(av_clip(level>>3, 0, 6), line);
strcpy(prev, line);
}
| 1threat
|
void migrate_fd_error(MigrationState *s)
{
DPRINTF("setting error state\n");
s->state = MIG_STATE_ERROR;
notifier_list_notify(&migration_state_notifiers, s);
migrate_fd_cleanup(s);
}
| 1threat
|
Restart one service in docker swarm stack : <p>Does anyone know if there is a way to have docker swarm restart one service that is part of a stack without restarting the whole stack?</p>
| 0debug
|
Regex to remove spaces within square brackets (Java) : <p>I need a regex to remove spaces within square brackets. For example: </p>
<ul>
<li>add eax [ebp + 8]</li>
<li>add eax [esp + 12]</li>
</ul>
<p>will become </p>
<ul>
<li>add eax [ebp+8]</li>
<li>add eax [esp+12]</li>
</ul>
<p>Thanks for your assistance.</p>
| 0debug
|
I would like to create a scripte to move a image on a circle using the cursor? : I would like to create a scripte(jquery) to move a image on a circle using the cursor ?
code :
html :
<div id="carousel">
<div class="slide"></div>
</div>
css :
#carousel{border: dashed 1px;border-radius: 50%;background:linear-gradient(transparent 49%, black 49%, black 51%, transparent 51%), rgba(0,0,255,.3) linear-gradient(90deg,transparent 49%, black 49%, black 51%, transparent 51%);width: 250px;height: 250px;margin:auto;position: relative;}.slide{width: 50px;height: 50px}
#carousel .slide{background-size: 100% 100% !important}
#carousel .slide:nth-child(1){position: absolute;top:100px; left:225px; background: url(https://4.bp.blogspot.com/-n7ysjpiiIuk/WTv5FyumGSI/AAAAAAAAADU/RynLbNdpYDUv8Bx4DJ_iczeXmqXfOrf_wCLcB/s1600/1.png) no-repeat;}
https://jsfiddle.net/SaidDev/wp8j66gg/
thanks
| 0debug
|
ASP.NET Core - Custom model validation : <p>In MVC when we post a model to an action we do the following in order to validate the model against the data annotation of that model:</p>
<pre><code>if (ModelState.IsValid)
</code></pre>
<p>If we mark a property as [Required], the ModelState.IsValid will validate that property if contains a value or not.</p>
<p>My question: How can I manually build and run custom validator?</p>
<p>P.S. I am talking about backend validator only.</p>
| 0debug
|
static int readv_f(int argc, char **argv)
{
struct timeval t1, t2;
int Cflag = 0, qflag = 0, vflag = 0;
int c, cnt;
char *buf;
int64_t offset;
int total = 0;
int nr_iov;
QEMUIOVector qiov;
int pattern = 0;
int Pflag = 0;
while ((c = getopt(argc, argv, "CP:qv")) != EOF) {
switch (c) {
case 'C':
Cflag = 1;
break;
case 'P':
Pflag = 1;
pattern = parse_pattern(optarg);
if (pattern < 0) {
return 0;
}
break;
case 'q':
qflag = 1;
break;
case 'v':
vflag = 1;
break;
default:
return command_usage(&readv_cmd);
}
}
if (optind > argc - 2) {
return command_usage(&readv_cmd);
}
offset = cvtnum(argv[optind]);
if (offset < 0) {
printf("non-numeric length argument -- %s\n", argv[optind]);
return 0;
}
optind++;
if (offset & 0x1ff) {
printf("offset %" PRId64 " is not sector aligned\n",
offset);
return 0;
}
nr_iov = argc - optind;
buf = create_iovec(&qiov, &argv[optind], nr_iov, 0xab);
if (buf == NULL) {
return 0;
}
gettimeofday(&t1, NULL);
cnt = do_aio_readv(&qiov, offset, &total);
gettimeofday(&t2, NULL);
if (cnt < 0) {
printf("readv failed: %s\n", strerror(-cnt));
goto out;
}
if (Pflag) {
void *cmp_buf = malloc(qiov.size);
memset(cmp_buf, pattern, qiov.size);
if (memcmp(buf, cmp_buf, qiov.size)) {
printf("Pattern verification failed at offset %"
PRId64 ", %zd bytes\n", offset, qiov.size);
}
free(cmp_buf);
}
if (qflag) {
goto out;
}
if (vflag) {
dump_buffer(buf, offset, qiov.size);
}
t2 = tsub(t2, t1);
print_report("read", &t2, offset, qiov.size, total, cnt, Cflag);
out:
qemu_io_free(buf);
return 0;
}
| 1threat
|
How to add new library into Arduino? : <p>Guy, I need to add a new library into my Arduino. The problem is, the creator of the new library does not put it in a zip.file, hence hard to add it to the Arduino library. This is the link of the new library </p>
<p><a href="http://www.avdweb.nl/arduino/libraries/virtualdelay.html" rel="nofollow noreferrer">http://www.avdweb.nl/arduino/libraries/virtualdelay.html</a></p>
<p>In the link, the creator give the library in code form. But how do I add it into my Arduino's library??</p>
<p>steps by steps explanation would be nice.</p>
| 0debug
|
static int ppc_hash64_pte_prot(PowerPCCPU *cpu,
ppc_slb_t *slb, ppc_hash_pte64_t pte)
{
CPUPPCState *env = &cpu->env;
unsigned pp, key;
int prot = 0;
key = !!(msr_pr ? (slb->vsid & SLB_VSID_KP)
: (slb->vsid & SLB_VSID_KS));
pp = (pte.pte1 & HPTE64_R_PP) | ((pte.pte1 & HPTE64_R_PP0) >> 61);
if (key == 0) {
switch (pp) {
case 0x0:
case 0x1:
case 0x2:
prot = PAGE_READ | PAGE_WRITE;
break;
case 0x3:
case 0x6:
prot = PAGE_READ;
break;
}
} else {
switch (pp) {
case 0x0:
case 0x6:
prot = 0;
break;
case 0x1:
case 0x3:
prot = PAGE_READ;
break;
case 0x2:
prot = PAGE_READ | PAGE_WRITE;
break;
}
}
if (!(pte.pte1 & HPTE64_R_N) || (pte.pte1 & HPTE64_R_G)
|| (slb->vsid & SLB_VSID_N)) {
prot |= PAGE_EXEC;
}
return prot;
}
| 1threat
|
Trying to find the source of a <video> tag using C# : <p>I am currently trying to get the source of a 'video' tag on a website using C#, I am using HtmlAgilityPack and have not yet found a way to make this possible, any help would be great!</p>
| 0debug
|
static int nist_read_header(AVFormatContext *s)
{
char buffer[32], coding[32] = "pcm", format[32] = "01";
int bps = 0, be = 0;
int32_t header_size;
AVStream *st;
st = avformat_new_stream(s, NULL);
if (!st)
return AVERROR(ENOMEM);
st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
ff_get_line(s->pb, buffer, sizeof(buffer));
ff_get_line(s->pb, buffer, sizeof(buffer));
sscanf(buffer, "%"SCNd32, &header_size);
if (header_size <= 0)
return AVERROR_INVALIDDATA;
while (!url_feof(s->pb)) {
ff_get_line(s->pb, buffer, sizeof(buffer));
if (avio_tell(s->pb) >= header_size)
return AVERROR_INVALIDDATA;
if (!memcmp(buffer, "end_head", 8)) {
if (!st->codec->bits_per_coded_sample)
st->codec->bits_per_coded_sample = bps << 3;
if (!av_strcasecmp(coding, "pcm")) {
st->codec->codec_id = ff_get_pcm_codec_id(st->codec->bits_per_coded_sample,
0, be, 0xFFFF);
} else if (!av_strcasecmp(coding, "alaw")) {
st->codec->codec_id = AV_CODEC_ID_PCM_ALAW;
} else if (!av_strcasecmp(coding, "ulaw") ||
!av_strcasecmp(coding, "mu-law")) {
st->codec->codec_id = AV_CODEC_ID_PCM_MULAW;
} else {
avpriv_request_sample(s, "coding %s", coding);
}
avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
st->codec->block_align = st->codec->bits_per_coded_sample * st->codec->channels / 8;
if (avio_tell(s->pb) > header_size)
return AVERROR_INVALIDDATA;
avio_skip(s->pb, header_size - avio_tell(s->pb));
return 0;
} else if (!memcmp(buffer, "channel_count", 13)) {
sscanf(buffer, "%*s %*s %"SCNd32, &st->codec->channels);
} else if (!memcmp(buffer, "sample_byte_format", 18)) {
sscanf(buffer, "%*s %*s %31s", format);
if (!av_strcasecmp(format, "01")) {
be = 0;
} else if (!av_strcasecmp(format, "10")) {
be = 1;
} else if (av_strcasecmp(format, "1")) {
avpriv_request_sample(s, "sample byte format %s", format);
return AVERROR_PATCHWELCOME;
}
} else if (!memcmp(buffer, "sample_coding", 13)) {
sscanf(buffer, "%*s %*s %31s", coding);
} else if (!memcmp(buffer, "sample_count", 12)) {
sscanf(buffer, "%*s %*s %"SCNd64, &st->duration);
} else if (!memcmp(buffer, "sample_n_bytes", 14)) {
sscanf(buffer, "%*s %*s %"SCNd32, &bps);
} else if (!memcmp(buffer, "sample_rate", 11)) {
sscanf(buffer, "%*s %*s %"SCNd32, &st->codec->sample_rate);
} else if (!memcmp(buffer, "sample_sig_bits", 15)) {
sscanf(buffer, "%*s %*s %"SCNd32, &st->codec->bits_per_coded_sample);
} else {
char key[32], value[32];
if (sscanf(buffer, "%31s %*s %31s", key, value) == 3) {
av_dict_set(&s->metadata, key, value, AV_DICT_APPEND);
} else {
av_log(s, AV_LOG_ERROR, "Failed to parse '%s' as metadata\n", buffer);
}
}
}
return AVERROR_EOF;
}
| 1threat
|
cordova requirements issue , android target not installed : <p>I am trying to install Cordova on windows 7.
I am following this tutorial :
<a href="https://www.tutorialspoint.com/cordova/cordova_first_application.htm" rel="noreferrer">https://www.tutorialspoint.com/cordova/cordova_first_application.htm</a></p>
<p>while I run <strong>cordova requirements</strong>, it says android target is not intalled
and set the ANDROID_HOME environment variable</p>
<pre><code>I:\CordovaProject\hello>cordova requirements
Requirements check results for android:
Java JDK: installed 1.8.0
Android SDK: installed true
Android target: not installed
Android SDK not found. Make sure that it is installed. If it is not at the
default location, set the ANDROID_HOME environment variable.
Gradle: installed
Error: Some of requirements check failed
I:\CordovaProject\hello>echo %ANDROID_HOME%
C:\Users\user\AppData\Local\Android\sdk
</code></pre>
<p>as you can see in the image 1, when I echo ANDROID_HOME it is set to proper location. I am not able to resolve this error. kindly help me with this </p>
<p>path has these : %ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools</p>
<p>I have downloaded android-25 in android studio </p>
<p>and project properties file has android target set to : android-25 both in
I:\CordovaProject\hello\platforms\android\CordovaLib\project.properties<br>
I:\CordovaProject\hello\platforms\android\project.properties </p>
<p>and when i run <strong>cordova build android</strong> i get following error</p>
<pre><code>BUILD FAILED
Total time: 31.807 secs
Error: cmd: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all dependencies for configuration ':classpath'.
> Could not download uast.jar (com.android.tools.external.com-
intellij:uast:145.597.3)
> Could not get resource 'https://jcenter.bintray.com/com/android/tools/ex
ternal/com-intellij/uast/145.597.3/uast-145.597.3.jar'.
> Could not GET 'https://jcenter.bintray.com/com/android/tools/external
/com-intellij/uast/145.597.3/uast-145.597.3.jar'.
> akamai.bintray.com
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or -
-debug option to get more log output.
</code></pre>
| 0debug
|
static bool linked_bp_matches(ARMCPU *cpu, int lbn)
{
CPUARMState *env = &cpu->env;
uint64_t bcr = env->cp15.dbgbcr[lbn];
int brps = extract32(cpu->dbgdidr, 24, 4);
int ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
int bt;
uint32_t contextidr;
if (lbn > brps || lbn < (brps - ctx_cmps)) {
return false;
}
bcr = env->cp15.dbgbcr[lbn];
if (extract64(bcr, 0, 1) == 0) {
return false;
}
bt = extract64(bcr, 20, 4);
contextidr = extract64(env->cp15.contextidr_el1, 0, 32);
switch (bt) {
case 3:
if (arm_current_el(env) > 1) {
return false;
}
return (contextidr == extract64(env->cp15.dbgbvr[lbn], 0, 32));
case 5:
case 9:
case 11:
default:
return false;
}
return false;
}
| 1threat
|
Why Build is needed? : <p>I am highly confused as why Build is needed in a java project.</p>
<p>I am new to Java. I have created a Java project which creates volume file.
I have run this code on my machine and created a JAR file and batch file which executes this JAR.
Now who ever needs it, I hand over the JAR file along with .bat file and it is good to go.</p>
<p>Where some one asks me source code, I give them via SVN.</p>
<p>In this process I couldn't relate what BUILD means and where it is actually needed? And why we need build tool like Maven (I know what maven is but can't relate)
I can easily share my JAR files and libraries with anyone who needs it.</p>
| 0debug
|
I upgraded c++ projects from visual studio 2010 to 2015 still its showing visual studio(2010) : [enter image description here][1]
[1]: https://i.stack.imgur.com/BkRUC.jpg
I upgraded c++ projects from visual studio 2010 to 2015 still its showing visual studio(2010) please Inform me if there is any change I need to solve this cover
| 0debug
|
Unable to filter messages by recipient in Microsoft Graph Api. One or more invalid nodes : <p>I am trying to get a list of messages that are filtered by recipient from Microsoft Graph API. The url I am using for the request is:</p>
<p><code>https://graph.microsoft.com/beta/me/messages?$filter=toRecipients/any(r: r/emailAddress/address eq '[Email Address]')</code></p>
<p>But I am getting this is the response:</p>
<pre><code>{
"error": {
"code": "ErrorInvalidUrlQueryFilter",
"message": "The query filter contains one or more invalid nodes.",
"innerError": {
"request-id": "7db712c3-e337-49d9-aa8d-4a5d350d8480",
"date": "2016-09-28T16:58:34"
}
}
}
</code></pre>
<p>A successful request should look like this (with a lot more data that I have omitted).</p>
<pre><code>{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#users('99999999-9999-9999-9999-999999999999')/messages",
"@odata.nextLink": "https://graph.microsoft.com/beta/me/messages?$skip=10",
"value": [
{
"toRecipients": [
{
"emailAddress": {
"name": "[Name]",
"address": "[Email Address]"
}
}
],
}
]
}
</code></pre>
<p>The request works if I remove the filter, and I am able to perform requests with simpler filters.</p>
<p>Is there a problem with my URL, or is there another way to make the request?</p>
| 0debug
|
static uint32_t nvic_readl(NVICState *s, uint32_t offset)
{
ARMCPU *cpu = s->cpu;
uint32_t val;
switch (offset) {
case 4:
return ((s->num_irq - NVIC_FIRST_IRQ) / 32) - 1;
case 0xd00:
return cpu->midr;
case 0xd04:
val = cpu->env.v7m.exception;
val |= (s->vectpending & 0xff) << 12;
if (nvic_isrpending(s)) {
val |= (1 << 22);
}
if (nvic_rettobase(s)) {
val |= (1 << 11);
}
if (s->vectors[ARMV7M_EXCP_SYSTICK].pending) {
val |= (1 << 26);
}
if (s->vectors[ARMV7M_EXCP_PENDSV].pending) {
val |= (1 << 28);
}
if (s->vectors[ARMV7M_EXCP_NMI].pending) {
val |= (1 << 31);
}
return val;
case 0xd08:
return cpu->env.v7m.vecbase;
case 0xd0c:
return 0xfa050000 | (s->prigroup << 8);
case 0xd10:
return 0;
case 0xd14:
return cpu->env.v7m.ccr;
case 0xd24:
val = 0;
if (s->vectors[ARMV7M_EXCP_MEM].active) {
val |= (1 << 0);
}
if (s->vectors[ARMV7M_EXCP_BUS].active) {
val |= (1 << 1);
}
if (s->vectors[ARMV7M_EXCP_USAGE].active) {
val |= (1 << 3);
}
if (s->vectors[ARMV7M_EXCP_SVC].active) {
val |= (1 << 7);
}
if (s->vectors[ARMV7M_EXCP_DEBUG].active) {
val |= (1 << 8);
}
if (s->vectors[ARMV7M_EXCP_PENDSV].active) {
val |= (1 << 10);
}
if (s->vectors[ARMV7M_EXCP_SYSTICK].active) {
val |= (1 << 11);
}
if (s->vectors[ARMV7M_EXCP_USAGE].pending) {
val |= (1 << 12);
}
if (s->vectors[ARMV7M_EXCP_MEM].pending) {
val |= (1 << 13);
}
if (s->vectors[ARMV7M_EXCP_BUS].pending) {
val |= (1 << 14);
}
if (s->vectors[ARMV7M_EXCP_SVC].pending) {
val |= (1 << 15);
}
if (s->vectors[ARMV7M_EXCP_MEM].enabled) {
val |= (1 << 16);
}
if (s->vectors[ARMV7M_EXCP_BUS].enabled) {
val |= (1 << 17);
}
if (s->vectors[ARMV7M_EXCP_USAGE].enabled) {
val |= (1 << 18);
}
return val;
case 0xd28:
return cpu->env.v7m.cfsr;
case 0xd2c:
return cpu->env.v7m.hfsr;
case 0xd30:
return cpu->env.v7m.dfsr;
case 0xd34:
return cpu->env.v7m.mmfar;
case 0xd38:
return cpu->env.v7m.bfar;
case 0xd3c:
qemu_log_mask(LOG_UNIMP,
"Aux Fault status registers unimplemented\n");
return 0;
case 0xd40:
return 0x00000030;
case 0xd44:
return 0x00000200;
case 0xd48:
return 0x00100000;
case 0xd4c:
return 0x00000000;
case 0xd50:
return 0x00000030;
case 0xd54:
return 0x00000000;
case 0xd58:
return 0x00000000;
case 0xd5c:
return 0x00000000;
case 0xd60:
return 0x01141110;
case 0xd64:
return 0x02111000;
case 0xd68:
return 0x21112231;
case 0xd6c:
return 0x01111110;
case 0xd70:
return 0x01310102;
case 0xd90:
return cpu->pmsav7_dregion << 8;
break;
case 0xd94:
return cpu->env.v7m.mpu_ctrl;
case 0xd98:
return cpu->env.pmsav7.rnr;
case 0xd9c:
case 0xda4:
case 0xdac:
case 0xdb4:
{
int region = cpu->env.pmsav7.rnr;
if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
int aliasno = (offset - 0xd9c) / 8;
if (aliasno) {
region = deposit32(region, 0, 2, aliasno);
}
if (region >= cpu->pmsav7_dregion) {
return 0;
}
return cpu->env.pmsav8.rbar[region];
}
if (region >= cpu->pmsav7_dregion) {
return 0;
}
return (cpu->env.pmsav7.drbar[region] & 0x1f) | (region & 0xf);
}
case 0xda0:
case 0xda8:
case 0xdb0:
case 0xdb8:
{
int region = cpu->env.pmsav7.rnr;
if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
int aliasno = (offset - 0xda0) / 8;
if (aliasno) {
region = deposit32(region, 0, 2, aliasno);
}
if (region >= cpu->pmsav7_dregion) {
return 0;
}
return cpu->env.pmsav8.rlar[region];
}
if (region >= cpu->pmsav7_dregion) {
return 0;
}
return ((cpu->env.pmsav7.dracr[region] & 0xffff) << 16) |
(cpu->env.pmsav7.drsr[region] & 0xffff);
}
case 0xdc0:
if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
goto bad_offset;
}
return cpu->env.pmsav8.mair0;
case 0xdc4:
if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
goto bad_offset;
}
return cpu->env.pmsav8.mair1;
default:
bad_offset:
qemu_log_mask(LOG_GUEST_ERROR, "NVIC: Bad read offset 0x%x\n", offset);
return 0;
}
}
| 1threat
|
How i return a search results in my page? : I have this search bar and I would like if someone can help me when I press the search button to look for keywords in a text file that you have on your computer and bring me the words are found back to the page ...i'm a beginner and do not really manage how to fix it ... if someone can show me how to do it in writing i would be grateful.
Search engine:
<form id="frmSearch" class="search1" method="get" action="default.html" />
<input class="search" id="txtSearch" type="text" name="search_bar" size="31" maxlength="255"
value=""
<style="left: 396px; top: 20000px; width: 293px; height: 60px;" />
Button:
<input class="search2" type="submit" name="submition" value="Cauta" style=" padding-
bottom:20px; left: 300px; top: 0px; height: 50px" />
<input class="search2" type="hidden" name="sitesearch" value="default.html" />
JS:
<script type="text/javascript">
document.getElementById('frmSearch').onsubmit = function() {
window.location = 'http://www.google.ro/search?q=' + document.getElementById('txtSearch').value;
}
</script>
| 0debug
|
Show only selected controllers in swagger-swashbuckle UI : <p>I am currently using swagger in my project and i have more than 100 controllers there. I guess due to the large number of controller, swagger UI documentation page takes more than 5 min to load its controller. Is it possible to select specific controllers at the UI page and load options for them only?
Or else there are other methods to load UI page faster?
Help me!</p>
| 0debug
|
C# Coding Best Practice : <p>I'm currently doing work which requires me to convert VB.Net code to C#.
I've been using the "Builder Pattern" primarily and this has me converting many functions that are one single call of a function ie. SomeFunction(var1,var2,var3) into:</p>
<pre><code>Dim Director As New SomeDirector
With Director
.SomeProperty = SomeValue
.SomeProperty2 = SomeValue2
End With
</code></pre>
<p>My concern is that this creates 5-6 lines of code rather than one single line. Is there a way for me to do this in a more concise way or is it better to have the 5-6 lines of code?</p>
<p>Thanks!</p>
| 0debug
|
How do I transpose a tibble() in R : <p>In R the <code>t()</code> function is really meant for matrices. When I try to transpose my tibble with <code>t()</code> I end up with a matrix. A matrix can't be made into a tibble with <code>tibble()</code>. I end up spending time storing column names as variables and attaching them as I try to re-make a transposed version of my tibble. </p>
<p>Question: What is the simplest way to transpose a tibble where the first column should become the column names of the new tibble and the old column names become the first column of my new tibble. </p>
| 0debug
|
Ionic2 ngModel not updating value returned from ngOnit() : I have a text box on my page and I assign the value dynamically using ngModel.And in my component, I'm using ngOnint() to call a function that set the ngmodel value. When I run my app the value is not updating in the text box.
| 0debug
|
Python code - missunderstanding : guys
a few days ago I bought a book called "Python for kids" (for dummies).
On page 47 there is an example of a simple code and its result as follows:
a = 2
while a < 10:
a = a + 1
print (a)
resulting in:
3
4
5
6
7
8
9
10
...............................................
I think this result is incorrect, because:
- There is no 2 printed out as declared in the first line of the code
- There is though 10 printed out (10 is equal 10, not less than 10)
Even if I make the 'while' condition: a <= 10, it prints out the numbers 3 to 11 which is again incorrect.
What I think should be the correct code is as follows:
a = 2
while a < 10:
print (a)
a = a + 1
resulting in:
2
3
4
5
6
7
8
9
...............................................
Now this is what I was expecting from the code. I played a little bit with the code and interestingly enough Python allows some strange arrangements which are executable without errors yet totally incorrect! For example:
a = 2
while a < 30:
a = a + 5
print (a)
result is only the number:
32
(incorrect it seems to be)
If I indent |print (a)| (by 4 spaces) I get:
7
12
17
22
27
32
Incorrect again. Can you explain to me why all this happens like that?
| 0debug
|
static int mov_open_dref(ByteIOContext **pb, char *src, MOVDref *ref)
{
if (!url_fopen(pb, ref->path, URL_RDONLY))
return 0;
if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
char filename[1024];
char *src_path;
int i, l;
src_path = strrchr(src, '/');
if (src_path)
src_path++;
else
src_path = src;
for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
if (ref->path[l] == '/') {
if (i == ref->nlvl_to - 1)
break;
else
i++;
}
if (i == ref->nlvl_to - 1) {
memcpy(filename, src, src_path - src);
filename[src_path - src] = 0;
for (i = 1; i < ref->nlvl_from; i++)
av_strlcat(filename, "../", 1024);
av_strlcat(filename, ref->path + l + 1, 1024);
if (!url_fopen(pb, filename, URL_RDONLY))
return 0;
}
}
return AVERROR(ENOENT);
};
| 1threat
|
static uint64_t grlib_irqmp_read(void *opaque, target_phys_addr_t addr,
unsigned size)
{
IRQMP *irqmp = opaque;
IRQMPState *state;
assert(irqmp != NULL);
state = irqmp->state;
assert(state != NULL);
addr &= 0xff;
switch (addr) {
case LEVEL_OFFSET:
return state->level;
case PENDING_OFFSET:
return state->pending;
case FORCE0_OFFSET:
return state->force[0];
case CLEAR_OFFSET:
case MP_STATUS_OFFSET:
return 0;
case BROADCAST_OFFSET:
return state->broadcast;
default:
break;
}
if (addr >= MASK_OFFSET && addr < FORCE_OFFSET) {
int cpu = (addr - MASK_OFFSET) / 4;
assert(cpu >= 0 && cpu < IRQMP_MAX_CPU);
return state->mask[cpu];
}
if (addr >= FORCE_OFFSET && addr < EXTENDED_OFFSET) {
int cpu = (addr - FORCE_OFFSET) / 4;
assert(cpu >= 0 && cpu < IRQMP_MAX_CPU);
return state->force[cpu];
}
if (addr >= EXTENDED_OFFSET && addr < IRQMP_REG_SIZE) {
int cpu = (addr - EXTENDED_OFFSET) / 4;
assert(cpu >= 0 && cpu < IRQMP_MAX_CPU);
return state->extended[cpu];
}
trace_grlib_irqmp_readl_unknown(addr);
return 0;
}
| 1threat
|
How do I initialize a composed struct in Go? : <p>Let's say I have a struct with another struct embedded in it.</p>
<pre><code>type Base struct {
ID string
}
type Child struct {
Base
a int
b int
}
</code></pre>
<p>When I go to initialize <code>Child</code>, I can't initialize the <code>ID</code> field directly.</p>
<pre><code>// unknown field 'ID' in struct literal of type Child
child := Child{ ID: id, a: a, b: b }
</code></pre>
<p>I instead have to initialize the ID field separately.</p>
<pre><code>child := Child{ a: 23, b: 42 }
child.ID = "foo"
</code></pre>
<p>This would seem to violate encapsulation. The user of Child has to know there's something different about the ID field. If I later moved a public field into an embedded struct, that might break initialization.</p>
<p>I could write a <code>NewFoo()</code> method for every struct and hope everyone uses that, but <strong><em>is there a way to use the struct literal safely with embedded structs that doesn't reveal some of the fields are embedded?</em></strong> Or am I applying the wrong pattern here?</p>
| 0debug
|
What would be the default constructor header : <p>I am new to java and trying to grasp concepts concerning headers for the default constructor.</p>
<p>The header for the first constructor in Circle is:</p>
<pre><code>public Circle(String label, int radius)
</code></pre>
<p>If one decides to add a default constructor to the class. What would be the header for this default constructor?</p>
<p>I have looked online but not really seen a succinct answer. </p>
| 0debug
|
How to stop program from running? : <p>I included three break; in three different cases. I tested case 2, it stopped the program; however for case 1, it goes on and on even tho it has break;. I tried every possible solution to fix it. I couldn't figure it out.</p>
<p>how can I fix it?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
// self-referential structure
struct queueNode {
char data; // define data as a char
struct queueNode *nextPtr; // queueNode pointer
struct queueNode *prevPtr;
}; // end structure queueNode
typedef struct queueNode QueueNode;
typedef QueueNode *QueueNodePtr;
// function prototypes
void printQueue( QueueNodePtr currentPtr );
int isEmpty( QueueNodePtr headPtr );
char dequeue( QueueNodePtr *headPtr, QueueNodePtr *tailPtr );
void enqueue( QueueNodePtr *headPtr, QueueNodePtr *tailPtr,
char value );
void instructions( void );
void reverse( QueueNodePtr currentPtr);
// function main begins program execution
int main( void )
{
QueueNodePtr headPtr = NULL; // initialize headPtr
QueueNodePtr tailPtr = NULL; // initialize tailPtr
unsigned int choice; // user's menu choice
char item; // char input by user
instructions(); // display the menu
printf( "%s", "? " );
scanf( "%u", &choice );
// while user does not enter 3
while ( choice != 3 ) {
switch( choice ) {
// enqueue value
case 1:
printf( "%s", "Enter a character: " );
scanf( "\n%c", &item );
enqueue( &headPtr, &tailPtr, item );
printQueue( headPtr );
reverse( headPtr );
break;
// dequeue value
case 2:
// if queue is not empty
if ( !isEmpty( headPtr ) ) {
item = dequeue( &headPtr, &tailPtr );
printf( "%c has been dequeued.\n", item );
} // end if
printQueue( headPtr );
reverse( headPtr );
break;
default:
puts( "Invalid choice.\n" );
instructions();
break;
} // end switch
printf( "%s", "? " );
scanf( "%u", &choice );
} // end while
puts( "End of run." );
} // end main
// display program instructions to user
void instructions( void )
{
printf ( "Enter your choice:\n"
" 1 to add an item to the queue\n"
" 2 to remove an item from the queue\n"
" 3 to end\n" );
} // end function instructions
// insert a node in at queue tail
void enqueue( QueueNodePtr *headPtr, QueueNodePtr *tailPtr,
char value )
{
QueueNodePtr newPtr; // pointer to new node
QueueNodePtr currentPtr;
QueueNodePtr previousPtr;
newPtr = (QueueNodePtr)malloc(sizeof(QueueNode));
if ( newPtr != NULL ) { // is space available
newPtr->data = value;
newPtr->nextPtr = NULL;
newPtr->prevPtr = NULL;
previousPtr = NULL;
currentPtr = *headPtr;
while(currentPtr != NULL && value > currentPtr-> data)
{
previousPtr = currentPtr;
currentPtr = currentPtr->nextPtr;
}
if(previousPtr == NULL)
{
newPtr->nextPtr = *headPtr;
if(*headPtr != NULL)
(*headPtr)->prevPtr = newPtr;
*headPtr = newPtr;
}
else
{
newPtr->prevPtr = previousPtr;
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
if(currentPtr != NULL)
currentPtr->prevPtr = newPtr;
}
} // end if
else {
printf( "%c not inserted. No memory available.\n", value );
} // end else
} // end function enqueue
// remove node from queue head
char dequeue( QueueNodePtr *headPtr, QueueNodePtr *tailPtr )
{
char value; // node value
QueueNodePtr tempPtr; // temporary node pointer
QueueNodePtr currentPtr;
QueueNodePtr previousPtr;
if(value == ( *headPtr )->data)
{
tempPtr = *headPtr;
*headPtr = ( *headPtr )->nextPtr;
free(tempPtr);
return value;
}
else
{
previousPtr = *headPtr;
currentPtr = (*headPtr)->nextPtr;
while(currentPtr != NULL && currentPtr->data != value)
{
previousPtr = currentPtr;
currentPtr = currentPtr->nextPtr;
}
if(currentPtr !=NULL)
{
tempPtr = currentPtr;
previousPtr->nextPtr= currentPtr->nextPtr;
free(tempPtr);
return value;
}
}
return '\0';
} // end function dequeue
// return 1 if the queue is empty, 0 otherwise
int isEmpty( QueueNodePtr headPtr )
{
return headPtr == NULL;
} // end function isEmpty
// print the queue
void printQueue( QueueNodePtr currentPtr )
{
// if queue is empty
if ( currentPtr == NULL ) {
puts( "List is empty.\n" );
} // end if
else {
puts( "The list is:" );
// while not end of queue
while ( currentPtr != NULL ) {
printf( "%c --> ", currentPtr->data );
currentPtr = currentPtr->nextPtr;
} // end while
puts( "NULL\n" );
} // end else
} // end function printQueue
void reverse(QueueNodePtr currentPtr )
{
QueueNodePtr tempPtr = NULL;
while(currentPtr != NULL)
{
tempPtr = currentPtr;
currentPtr = currentPtr->nextPtr;
}
printf("\nThe list in reverse is:");
printf("NULL");
currentPtr = tempPtr;
while(currentPtr != NULL)
{
printf(" <-- %c", currentPtr->data);
}
printf("NULL\n");
}
</code></pre>
| 0debug
|
How to subtract ten minutes from a time picked from time picker? : <p>I have a time picker in which the user picks the time and I am sending a notification to user ten minutes before or after the time user picked.Suppose if the user picks time as 11:00 AM then I want the notification to trigger at 10:55 AM. I am unable to subtract and add ten minutes to the time. As I am new to this Please help..I have spent a lot of time on it still not able to solve this. Any help is appreciated</p>
| 0debug
|
Runtime error in Finding perfect square within a range c++ : I am trying to solve Sherlock and Square problem in Hackerrank [(link)](https://www.hackerrank.com/challenges/sherlock-and-squares/problem) for finding the perfect square within a range of data. But i am getting a runtime error. Please suggest something to improve its performance
My code is as follows:
#include<iostream>
#include<cmath>
using namespace std;
int squares(int a, int b) {
long double i;
long long int count=0;
for(i=a;i<=b;i++)
{
long double b = sqrt(i);
if(fmod(b,1)==0.000000)
{
count++;
}
}
return count;
}
int main()
{
int q,i,a,b;
cin>>q;
for(i=0;i<q;i++)
{
cin>>a>>b;
int result = squares(a, b);
cout<<result<<"\n";
}
}
| 0debug
|
Realm accessed from incorrect thread - again : <p>I noticed many problems with accessing realm object, and I thought that my solution would be solving that.</p>
<p>So I have written simple helping method like this:</p>
<pre><code>public func write(completion: @escaping (Realm) -> ()) {
DispatchQueue(label: "realm").async {
if let realm = try? Realm() {
try? realm.write {
completion(realm)
}
}
}
}
</code></pre>
<p>I thought that completion block will be fine, because everytime I write object or update it, I use this method above. </p>
<p>Unfortunately I'm getting error:</p>
<pre><code>libc++abi.dylib: terminating with uncaught exception of type realm::IncorrectThreadException: Realm accessed from incorrect thread.
</code></pre>
| 0debug
|
i want to send mail through asp.net but error occurred : I am using c# for the back end of this contact form and html is the front end
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Send_Click(object sender, EventArgs e)
{
try
{
MailMessage message = new MailMessage(From.Text, To.Text,
Subject.Text, Body.Text);
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com", 465);
client.EnableSsl = true;
client.Credentials = new
The credentials when I ran the code were correct.
System.Net.NetworkCredential("example@gmail.com","password");
client.Send(message);
status.Text = "Mail was sent successfully";
status.Text = "Send was clicked";
}
This catch exception is so that you can see what error is occurring if there is an error
catch(Exception ex)
{
status.Text = ex.StackTrace;
}
}
}
| 0debug
|
In Python, how do I create and array from words from multiple lists, with word occurrences : <p>I have a JSON file that has multiple objects with a text field:</p>
<pre><code>{
"messages":
[
{"timestamp": "123456789", "timestampIso": "2019-06-26 09:51:00", "agentId": "2001-100001", "skillId": "2001-20000", "agentText": "That customer was great"},
{"timestamp": "123456789", "timestampIso": "2019-06-26 09:55:00", "agentId": "2001-100001", "skillId": "2001-20001", "agentText": "That customer was stupid\nI hope they don't phone back"},
{"timestamp": "123456789", "timestampIso": "2019-06-26 09:57:00", "agentId": "2001-100001", "skillId": "2001-20002", "agentText": "Line number 3"},
{"timestamp": "123456789", "timestampIso": "2019-06-26 09:59:00", "agentId": "2001-100001", "skillId": "2001-20003", "agentText": ""}
]
}
</code></pre>
<p>I'm only interested in the 'agentText' field.</p>
<p>I basically need to strip out every word in the agentText field and do a count of the occurrences of the word.</p>
<p>So my python code:</p>
<pre><code>import json
with open('20190626-101200-text-messages.json') as f:
data = json.load(f)
for message in data['messages']:
splittext= message['agentText'].strip().replace('\n',' ').replace('\r',' ')
if len(splittext)>0:
splittext2 = splittext.split(' ')
print(splittext2)
</code></pre>
<p>gives me this:</p>
<pre><code>['That', 'customer', 'was', 'great']
['That', 'customer', 'was', 'stupid', 'I', 'hope', 'they', "don't", 'phone', 'back']
['Line', 'number', '3']
</code></pre>
<p>how can I add each word to an array with counts?
so like;</p>
<pre><code>That 2
customer 2
was 2
great 1
..
</code></pre>
<p>and so on?</p>
| 0debug
|
start_list(Visitor *v, const char *name, GenericList **list, size_t size,
Error **errp)
{
StringInputVisitor *siv = to_siv(v);
assert(list);
if (parse_str(siv, name, errp) < 0) {
*list = NULL;
return;
}
siv->cur_range = g_list_first(siv->ranges);
if (siv->cur_range) {
Range *r = siv->cur_range->data;
if (r) {
siv->cur = r->begin;
}
*list = g_malloc0(size);
} else {
*list = NULL;
}
}
| 1threat
|
PHP function, call only one variable : <p>I need help with a PHP function im writing. My code:</p>
<pre><code>function get_config() {
$db = dbServer::getInstance();
$mysqli = $db->getConnection();
$sql_query = 'SELECT * FROM server_config';
$result = $mysqli->query($sql_query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$serverStatus = $row['server_status'];
$serverTitle = $row['server_title'];
}
}
}
</code></pre>
<p>Now, If I'd want to call the function and only echo let's say, $serverTitle, how should I do that? I.e:</p>
<pre><code>get_config($serverStatus)?
</code></pre>
<p>I'm a total rookie when it comes to PHP.</p>
| 0debug
|
Basic issues in android : <p>Can some one please tell me the solution to this problem in android studio:
I am new at android... Can some one tell me the solution to resolve it:</p>
<p><a href="http://i.stack.imgur.com/hVX6o.jpg" rel="nofollow">enter image description here</a></p>
| 0debug
|
Are these CSS selector syntax equivalent? : <p>I would want to know if both the syntax below are valid and equivalent?</p>
<pre><code> /* Type: 1 */
html, body {
}
/* Type: 2 */
html body {
}
</code></pre>
| 0debug
|
Conda: Choose where packages are downloaded : <p>I don't have enough space in my default conda directory so I want conda packages to be downloaded at a different location. I have a conda environment created and activated at </p>
<pre><code>/different_drive/condaenv
</code></pre>
<p>Based on what I found online, I tried editing the .condarc file to have</p>
<pre><code>pkgs_dirs
- /different_drive/pkgs
</code></pre>
<p>and edited the permission of the default directory </p>
<pre><code>/home/user/conda/pkgs/
</code></pre>
<p>to read-only. However, I just get permission denied errors as conda still tries to download the files to the default directory. Any suggestions on what I can do to change the download location of the packages? </p>
| 0debug
|
static void filter(struct vf_priv_s *p, uint8_t *dst[3], uint8_t *src[3], int dst_stride[3], int src_stride[3], int width, int height){
int x, y, i;
for(i=0; i<3; i++){
p->frame->data[i]= src[i];
p->frame->linesize[i]= src_stride[i];
}
p->avctx_enc->me_cmp=
p->avctx_enc->me_sub_cmp= FF_CMP_SAD ;
p->frame->quality= p->qp*FF_QP2LAMBDA;
avcodec_encode_video(p->avctx_enc, p->outbuf, p->outbuf_size, p->frame);
p->frame_dec = p->avctx_enc->coded_frame;
for(i=0; i<3; i++){
int is_chroma= !!i;
int w= width >>is_chroma;
int h= height>>is_chroma;
int fils= p->frame_dec->linesize[i];
int srcs= src_stride[i];
for(y=0; y<h; y++){
if((y ^ p->parity) & 1){
for(x=0; x<w; x++){
if((x-2)+(y-1)*w>=0 && (x+2)+(y+1)*w<w*h){
uint8_t *filp= &p->frame_dec->data[i][x + y*fils];
uint8_t *srcp= &src[i][x + y*srcs];
int diff0= filp[-fils] - srcp[-srcs];
int diff1= filp[+fils] - srcp[+srcs];
int spatial_score= ABS(srcp[-srcs-1] - srcp[+srcs-1])
+ABS(srcp[-srcs ] - srcp[+srcs ])
+ABS(srcp[-srcs+1] - srcp[+srcs+1]) - 1;
int temp= filp[0];
#define CHECK(j)\
{ int score= ABS(srcp[-srcs-1+(j)] - srcp[+srcs-1-(j)])\
+ ABS(srcp[-srcs +(j)] - srcp[+srcs -(j)])\
+ ABS(srcp[-srcs+1+(j)] - srcp[+srcs+1-(j)]);\
if(score < spatial_score){\
spatial_score= score;\
diff0= filp[-fils+(j)] - srcp[-srcs+(j)];\
diff1= filp[+fils-(j)] - srcp[+srcs-(j)];
CHECK(-1) CHECK(-2) }} }}
CHECK( 1) CHECK( 2) }} }}
| 1threat
|
Bing maps stopped working suddenly : <p>I have used Bing map control in my UWP application for Desktop. It has suddenly stopped working and shows red icon on top of it as attached here:-
Please help if anyone has encountered this issue!</p>
<p><a href="https://i.stack.imgur.com/URoqO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/URoqO.png" alt="bing map with icon"></a></p>
| 0debug
|
Why is passing by value (if a copy is needed) recommended in C++11 if a const reference only costs a single copy as well? : <p>I am trying to understand move semantics, rvalue references, <code>std::move</code>, etc. I have been trying to figure out, by searching through various questions on this site, why passing a <code>const std::string &name</code> + <code>_name(name)</code> is less recommended than a <code>std::string name</code> + <code>_name(std::move(name))</code> if a copy is needed.</p>
<p>If I understand correctly, the following requires a single copy (through the constructor) plus a move (from the temporary to the member):</p>
<pre><code>Dog::Dog(std::string name) : _name(std::move(name)) {}
</code></pre>
<p>The alternative (and old-fashioned) way is to pass it by reference and copy it (from the reference to the member):</p>
<pre><code>Dog::Dog(const std::string &name) : _name(name) {}
</code></pre>
<p>If the first method requires a copy and move both, and the second method only requires a single copy, how can the first method be preferred and, in some cases, faster?</p>
| 0debug
|
json: cannot unmarshal object into Go value of type error with certain values : <p>Can I decode certain values from json to a struct? I am getting a response like this <a href="https://developer.github.com/v3/gists/#response-5" rel="nofollow noreferrer">https://developer.github.com/v3/gists/#response-5</a> when creating a gist and I created a struct like so:</p>
<pre><code>type GistResponse struct {
HTMLURL string `json:"html_url"`
Public bool `json:"public"`
}
</code></pre>
<p>But when I try to decode the json response the above struct I get a :</p>
<pre><code>json: cannot unmarshal object into Go value of type []main.GistResponse
</code></pre>
<p>Thanks</p>
| 0debug
|
How to get values of all rows in jTable and split them with delimiters and newline? : Say I had a table like this:
```
|ID|Name|Work|Age|
|31|John|IT |31 |
|32|Jane|IT |22 |
```
And I wanted to convert the values in the cell to string with delimiters(,) and newline like this:
```
31,John,IT, 31
32,Jane,IT ,22
```
What code would I need to punch in in order for this to happen?
| 0debug
|
Is it possible to show the `WORKDIR` when building a docker image? : <p>We have a problem with the <code>WORKDIR</code> when we building a docker image. Is it possible to print the value of <code>WORKDIR</code>?</p>
<p>We tried:</p>
<pre><code>ECHO ${WORKDIR}
</code></pre>
<p>But there is no such instruction <code>ECHO</code></p>
| 0debug
|
New Array Mips Full Code : <p>i got problem. I'm not good at MIPS and i need to read from user size of new array, then read from user int to get this array full of values and after i get all in, I need to write them out in order A[0]->A[n] (like FIFO queue). Can anybody write me full code? (without hard things)
Thanks!</p>
| 0debug
|
MYSQL SELECT statements : <p>I made a table and I want to select certain data from the table using select statements.
I want to see all the book titles that were published in May.
How can I go about doing this?</p>
<p>Here is the table</p>
<pre><code>CREATE TABLE titles
(
title_id CHAR(3) NOT NULL,
title_name VARCHAR(40) NOT NULL,
type VARCHAR(10) ,
pub_id CHAR(3) NOT NULL,
pages INTEGER ,
price DECIMAL(5,2) ,
sales INTEGER ,
pubdate DATE ,
contract SMALLINT NOT NULL,
CONSTRAINT pk_titles PRIMARY KEY (title_id)
)ENGINE = InnoDB;
</code></pre>
<p>I tried this: </p>
<pre><code>SELECT * FROM titles
WHERE pubdate LIKE '%%%%-05-%%';
</code></pre>
<p>It displays the whole column, how can I get it to only display the books title?</p>
| 0debug
|
int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
{
struct kvm_irq_routing_entry kroute;
if (!kvm_irqchip_in_kernel()) {
return -ENOSYS;
}
kroute.gsi = virq;
kroute.type = KVM_IRQ_ROUTING_MSI;
kroute.flags = 0;
kroute.u.msi.address_lo = (uint32_t)msg.address;
kroute.u.msi.address_hi = msg.address >> 32;
kroute.u.msi.data = le32_to_cpu(msg.data);
return kvm_update_routing_entry(s, &kroute);
}
| 1threat
|
lsb_release: command not found in latest Ubuntu Docker container : <p>I just wanted to test something out real quick. So I ran a docker container and I wanted to check which version I was running:</p>
<pre><code>$ docker run -it ubuntu
root@471bdb08b11a:/# lsb_release -a
bash: lsb_release: command not found
root@471bdb08b11a:/#
</code></pre>
<p>So I tried installing it (as <a href="http://www.andryhacks.com/bash-lsb_release-command-not-found/" rel="noreferrer">suggested here</a>):</p>
<pre><code>root@471bdb08b11a:/# apt install lsb_release
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package lsb_release
root@471bdb08b11a:/#
</code></pre>
<p>Anybody any idea why this isn't working?</p>
| 0debug
|
What's the Swift Equivalent of this Python Code? : <p>Hopefully this is a simple question, but what's the Swift equivalent of this Python code:</p>
<pre><code>param = [{"f_agg": "mean"}]
</code></pre>
| 0debug
|
int64_t helper_fstox(CPUSPARCState *env, float32 src)
{
int64_t ret;
clear_float_exceptions(env);
ret = float32_to_int64_round_to_zero(src, &env->fp_status);
check_ieee_exceptions(env);
return ret;
}
| 1threat
|
is there ashift operation in Rstudio? : in c++ there is shift operartion
>> right shift
<< left shift
this is consider to be very fast.
I tried to apply the same in R studio but it seems to be wrong.
Is there a similar operation in R studio that is as fast as this?
thanks in advance.
| 0debug
|
"Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on." : <p>I'm trying to log some messages to a <code>RichTextBox</code> control. It logs the first 2 or 3, then throws the following error:</p>
<blockquote>
<p>"Cross-thread operation not valid: Control 'txtLog' accessed from a thread other than the thread it was created on."</p>
</blockquote>
<p>This is a very simple app that just does a single <a href="/questions/tagged/pubnub" class="post-tag" title="show questions tagged 'pubnub'" rel="tag">pubnub</a> subscription. There was no attempt at threading. </p>
<p>Per another question I found on SO, I'm using a stringbuilder:</p>
<pre><code> public StringBuilder logtext = new StringBuilder();
</code></pre>
<p>Then I wanted to simplify things so I could just call <code>log("this is a log message")</code>:</p>
<pre><code> public void log(string txt)
{
logtext.Append(Environment.NewLine + txt);
txtLog.Text = logtext.ToString();
}
</code></pre>
<p>Like I said, it logs a few strings fine but then it tries to log the following:</p>
<blockquote>
<p>"ConnectStatus: [1,\"Connected\",\"presence\"]"</p>
</blockquote>
<p>that's when it throws the error. Here is the code which is returning that value:</p>
<pre><code>pubnub.Subscribe<string>(
chnl,
DisplayReturnMessage,
DisplayConnectStatusMessage,
DisplayErrorMessage
);
public void DisplayReturnMessage(string result)
{
log(TimeStamp() + " Result: " + result);
}
</code></pre>
<p>And here is a ss of the debugger if it helps:</p>
<p><a href="https://i.stack.imgur.com/sKzLh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sKzLh.png" alt="enter image description here"></a></p>
<p>Please ignore the fact that <code>TimeStamp()</code> literally returns "H:mm:ss.ffff" right now :)</p>
<p>I was able to manually <code>log("ConnectStatus: [1,\"Connected\",\"presence\"]")</code> and it worked, so I don't think it's a string issue. The threading thing is really throwing me off.</p>
| 0debug
|
static int coroutine_fn qed_aio_read_data(void *opaque, int ret,
uint64_t offset, size_t len)
{
QEDAIOCB *acb = opaque;
BDRVQEDState *s = acb_to_s(acb);
BlockDriverState *bs = acb->bs;
offset += qed_offset_into_cluster(s, acb->cur_pos);
trace_qed_aio_read_data(s, acb, ret, offset, len);
qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
if (ret == QED_CLUSTER_ZERO) {
qemu_iovec_memset(&acb->cur_qiov, 0, 0, acb->cur_qiov.size);
return 0;
} else if (ret != QED_CLUSTER_FOUND) {
return qed_read_backing_file(s, acb->cur_pos, &acb->cur_qiov,
&acb->backing_qiov);
}
BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
ret = bdrv_co_preadv(bs->file, offset, acb->cur_qiov.size,
&acb->cur_qiov, 0);
if (ret < 0) {
return ret;
}
return 0;
}
| 1threat
|
Sending messages to groups in Django Channels 2 : <p>I am completely stuck in that I cannot get group messaging to work with Channels 2! I have followed all tutorials and docs that I could find, but alas I haven't found what the issue seems to be yet. What I am trying to do right now is to have one specific URL that when visited should broadcast a simple message to a group named "events".</p>
<p>First things first, here are the relevant and current settings that I employ in Django:</p>
<pre><code>CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
'hosts': [('localhost', 6379)],
},
}
}
ASGI_APPLICATION = 'backend.routing.application'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'channels',
'channels_redis',
'backend.api'
]
</code></pre>
<p>Next, here is my EventConsumer, extending the JsonWebsocketConsumer in a very basic way. All this does is echo back when receiving a message, which works! So, the simple send_json response arrives as it should, it is ONLY group broadcasting that does not work.</p>
<pre><code>class EventConsumer(JsonWebsocketConsumer):
groups = ["events"]
def connect(self):
self.accept()
def disconnect(self, close_code):
print("Closed websocket with code: ", close_code)
self.close()
def receive_json(self, content, **kwargs):
print("Received event: {}\nFrom: {}\nGroups:
{}".format(content,
self.channel_layer,
self.groups))
self.send_json(content)
def event_notification(self, event):
self.send_json(
{
'type': 'test',
'content': event
}
)
</code></pre>
<p>And here is the URL configurations for the URL that I want to trigger the broadcast:</p>
<p>Project urls.py</p>
<pre><code>from backend.events import urls as event_urls
urlpatterns = [
url(r'^events/', include(event_urls))
]
</code></pre>
<p>Events app urls.py</p>
<pre><code>from backend.events.views import alarm
urlpatterns = [
url(r'alarm', alarm)
]
</code></pre>
<p>And finally, the view itself where the group broadcast should take place:</p>
<pre><code>from django.shortcuts import HttpResponse
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
def alarm(req):
layer = get_channel_layer()
async_to_sync(layer.group_send)('events', {'type': 'test'})
return HttpResponse('<p>Done</p>')
</code></pre>
| 0debug
|
How to find group of three elements in array whose sum equals to target sum? [javascript] : I can do this with three loops but complexity will be O(n3), can it be done with less complexity.
| 0debug
|
if else condition in java, android : <p>i have a TextView which is set using...</p>
<pre><code>// Declare view variables
private TextView mInfoText;
// Assign views from layout file to cor. vars
mInfoText = (TextView) findViewById(R.id.infoText);
</code></pre>
<p>how do i do an if else statement for the text inside it, i thought about doing it like this, but it doesn't work, i get a red line under the word "Sand".</p>
<pre><code>if (mInfoText = "Sand"){
//Show correct
} else {
//Show incorrect
}
</code></pre>
<p>Any ideas?</p>
| 0debug
|
Javascript popup link in php : <p><br>
i have this php code:</p>
<pre><code>echo "<div class='show-popup'><a class='button-popup-container-right' href='javascript:apri('popup.html');' target='_blank'><i class='far fa-play-circle'></i>&nbsp;ASCOLTA LA RADIO</span></a></div>"
</code></pre>
<p>but, when i click on the link the path is only "javascript:apri("</p>
<p>I have inserted this script in the footer of the page</p>
<pre><code>function apri(url) {
newin = window.open(url,'Player','top=50, left=50,scrollbars=no,resizable=yes,width=400,height=550,status=no,location=no,toolbar=no,nomenubar=no');
}
</code></pre>
<p>Can anyone help me please?</p>
| 0debug
|
static void i8042_class_initfn(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
dc->realize = i8042_realizefn;
dc->no_user = 1;
dc->vmsd = &vmstate_kbd_isa;
}
| 1threat
|
Can I prevent Babel from traversing code inserted by a plugin? : <p>I'm building a plugin that inserts <code>enterFunction()</code> in front of every existing function call by calling <code>path.insertBefore</code>. So my code is transformed from:</p>
<pre><code>myFunction();
</code></pre>
<p>To:</p>
<pre><code>enterFunction();
myFunction();
</code></pre>
<p>The problem is that when I insert the node Babel once again traverses the inserted node. Here's the logging output:</p>
<blockquote>
<p>'CallExpression', 'myFunction'<br>
'CallExpression', 'enterFunction'</p>
</blockquote>
<p>How can I prevent Babel from entering the <code>enterFunction</code> call expression and its children?</p>
<p>This is the code I'm currently using for my Babel plugin: </p>
<pre><code>function(babel) {
return {
visitor: {
CallExpression: function(path) {
console.log("CallExpression", path.node.callee.name)
if (path.node.ignore) {
return;
}
path.node.ignore = true
var enterCall = babel.types.callExpression(
babel.types.identifier("enterFunction"), []
)
enterCall.ignore = true;
path.insertBefore(enterCall)
}
}
}
}
</code></pre>
| 0debug
|
void set_system_io_map(MemoryRegion *mr)
{
memory_region_transaction_begin();
address_space_io.root = mr;
memory_region_transaction_commit();
}
| 1threat
|
How to troubleshoot/resolve "Signal strength query returned error" logs that are appearing in Xcode 10.1/iOS 12.1? : <p>Recently updated to iOS 12.1 (from 12.0), Xcode 10.1 (from 10.0) and seeing a flood of error messages in the Xcode console when debugging on my physical device like the following:</p>
<p><code>[NetworkInfo] Signal strength query returned error: Error Domain=NSPOSIXErrorDomain Code=13 "Permission denied", descriptor: <CTServiceDescriptor 0x28051d700, domain=1, instance=1></code></p>
<p>I get a couple of these logs every couple seconds, the only thing that changes is the hex value for the CTServiceDescriptor. There have been no code changes so I have to assume its related to the iOS or Xcode updates. </p>
<p>As far as I can tell it doesn't appear to have any performance impact, the app is operating as expected and my phone is working (its even updating its signal strength!). I've been unable to find anything helpful/relevant across Stack Overflow, Google, or the Apple Developer forums though I made a similar post to the latter that I'll link here once the post is approved. </p>
<p>Any suggestions/insight into how I could troubleshoot this further or resolve would be greatly appreciated. Thanks!</p>
| 0debug
|
two trees and a joint table between them : i have three tables, 2 hierarchical and 1 junction between these.
Teams
id idParent
1 null
2 1
3 null
4 null
5 4
Projects
id idParent
1 null
2 null
3 2
4 2
5 null
TeamProjects
idTeam idProject
2 2
3 1
5 5
A project always depend on at least one team, this is what teamprojects is for.
The result i'm trying to achieve : for each of the object (both teams and projects), i want to know what are the ascendant and descendant objects (id concatened)
idObject ascendantTeams descendantTeam ascendantProjects descendantProjects
1 2 7, 10
2 1 7
3 6
4
5 4 10
6 3
7 2 8, 9
8 2 7
9 2 7
10 5
I am trying to achieve this with a linq to entities query, but i need both CTE (for the recursive part) and (stuff-for-xml) for the concatenation part... and neither translate to linq to entities.
so i'm trying to make a view to help, but i dont manage to write the sql for it either.
how would you resolve this, either with linq to entities or sql ?
| 0debug
|
javascript function - jquey.each not work, any solutions? : [enter image description here][1]
[1]: https://i.stack.imgur.com/fvHFv.jpg
see my code,
colorSelectType in .each not working, what should i do now? pls help β₯
| 0debug
|
rules not work in jQuery validate function : I don't know what's wrong with my code as i am newbie to jQuery validate function,
i want to use `'required'` value `'true'` or `'false'` dynamically for add and edit page separately. i want field `'cate_image'` set to 'not required' in edit page as already have an image which inserted in 'add' page but need to validate only image format using '`accept`'. help me out.
if($("#hidden_cate_id").val() > 0){
var tf = "false";
}else{
var tf = "true";
}
$("#form-addcategory").validate(
{
rules: {
cate_name: { required: true },
cate_image: { required: tf, accept: "image/jpg,image/jpeg,image/png" }
},
messages: {
cate_name: { required: "Category name is required" },
cate_image: { required: "Category image is required" }
},
});
i put `if` condition for edit page if `$("#hidden_cate_id").` exist `tf` value will `false` and only check for `accept` rule. but it doesn't works !
| 0debug
|
def flatten_list(list1):
result_list = []
if not list1: return result_list
stack = [list(list1)]
while stack:
c_num = stack.pop()
next = c_num.pop()
if c_num: stack.append(c_num)
if isinstance(next, list):
if next: stack.append(list(next))
else: result_list.append(next)
result_list.reverse()
return result_list
| 0debug
|
Bootstrap button outline not working : <p>I am pretty new to Bootstrap, and am having a bit of trouble with getting my buttons styled correctly. I want a green(success) colored button, with just an outline as documented on their website <a href="http://v4-alpha.getbootstrap.com/components/buttons/#outline-buttons">here</a>. When I use the code suggested <code><button type="button" class="btn btn-success-outline">Success</button></code>, I get a grey button that has no apparent styling <a href="http://i.stack.imgur.com/vnA46.png">which looks like this</a>... Could anybody help me out?
Thanks!</p>
| 0debug
|
Grid constant - Layout manager in java : I just made a small program by adding button in my GUI using Gridbagconstraint in layout manager in Java the location of the button is always in center irrespective of the coordinates given. please help me
package StudentInfo;
import javax.swing.*;
import java.awt.*;
public class Gui {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(new GridBagLayout());
frame.setSize(600,600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
GridBagConstraints gbc = new GridBagConstraints();
JButton b = new JButton("Hello");
gbc.gridx=1;
gbc.gridy=1;
panel.add(b,gbc);
JButton v = new JButton("exit");
gbc.gridx=1;
gbc.gridx=0;
panel.add(v,gbc);
}
}
[output][2]`
[2]: https://i.stack.imgur.com/clVr9.png
| 0debug
|
static int init_directories(BDRVVVFATState* s,
const char *dirname, int heads, int secs)
{
bootsector_t* bootsector;
mapping_t* mapping;
unsigned int i;
unsigned int cluster;
memset(&(s->first_sectors[0]),0,0x40*0x200);
s->cluster_size=s->sectors_per_cluster*0x200;
s->cluster_buffer=g_malloc(s->cluster_size);
i = 1+s->sectors_per_cluster*0x200*8/s->fat_type;
s->sectors_per_fat=(s->sector_count+i)/i;
array_init(&(s->mapping),sizeof(mapping_t));
array_init(&(s->directory),sizeof(direntry_t));
{
direntry_t* entry=array_get_next(&(s->directory));
entry->attributes=0x28;
memcpy(entry->name,"QEMU VVF",8);
memcpy(entry->extension,"AT ",3);
}
init_fat(s);
s->faked_sectors=s->first_sectors_number+s->sectors_per_fat*2;
s->cluster_count=sector2cluster(s, s->sector_count);
mapping = array_get_next(&(s->mapping));
mapping->begin = 0;
mapping->dir_index = 0;
mapping->info.dir.parent_mapping_index = -1;
mapping->first_mapping_index = -1;
mapping->path = g_strdup(dirname);
i = strlen(mapping->path);
if (i > 0 && mapping->path[i - 1] == '/')
mapping->path[i - 1] = '\0';
mapping->mode = MODE_DIRECTORY;
mapping->read_only = 0;
s->path = mapping->path;
for (i = 0, cluster = 0; i < s->mapping.next; i++) {
int fix_fat = (i != 0);
mapping = array_get(&(s->mapping), i);
if (mapping->mode & MODE_DIRECTORY) {
mapping->begin = cluster;
if(read_directory(s, i)) {
fprintf(stderr, "Could not read directory %s\n",
mapping->path);
return -1;
}
mapping = array_get(&(s->mapping), i);
} else {
assert(mapping->mode == MODE_UNDEFINED);
mapping->mode=MODE_NORMAL;
mapping->begin = cluster;
if (mapping->end > 0) {
direntry_t* direntry = array_get(&(s->directory),
mapping->dir_index);
mapping->end = cluster + 1 + (mapping->end-1)/s->cluster_size;
set_begin_of_direntry(direntry, mapping->begin);
} else {
mapping->end = cluster + 1;
fix_fat = 0;
}
}
assert(mapping->begin < mapping->end);
cluster = mapping->end;
if(cluster > s->cluster_count) {
fprintf(stderr,"Directory does not fit in FAT%d (capacity %.2f MB)\n",
s->fat_type, s->sector_count / 2000.0);
return -EINVAL;
}
if (fix_fat) {
int j;
for(j = mapping->begin; j < mapping->end - 1; j++)
fat_set(s, j, j+1);
fat_set(s, mapping->end - 1, s->max_fat_value);
}
}
mapping = array_get(&(s->mapping), 0);
s->sectors_of_root_directory = mapping->end * s->sectors_per_cluster;
s->last_cluster_of_root_directory = mapping->end;
fat_set(s,0,s->max_fat_value);
fat_set(s,1,s->max_fat_value);
s->current_mapping = NULL;
bootsector=(bootsector_t*)(s->first_sectors+(s->first_sectors_number-1)*0x200);
bootsector->jump[0]=0xeb;
bootsector->jump[1]=0x3e;
bootsector->jump[2]=0x90;
memcpy(bootsector->name,"QEMU ",8);
bootsector->sector_size=cpu_to_le16(0x200);
bootsector->sectors_per_cluster=s->sectors_per_cluster;
bootsector->reserved_sectors=cpu_to_le16(1);
bootsector->number_of_fats=0x2;
bootsector->root_entries=cpu_to_le16(s->sectors_of_root_directory*0x10);
bootsector->total_sectors16=s->sector_count>0xffff?0:cpu_to_le16(s->sector_count);
bootsector->media_type=(s->first_sectors_number>1?0xf8:0xf0);
s->fat.pointer[0] = bootsector->media_type;
bootsector->sectors_per_fat=cpu_to_le16(s->sectors_per_fat);
bootsector->sectors_per_track = cpu_to_le16(secs);
bootsector->number_of_heads = cpu_to_le16(heads);
bootsector->hidden_sectors=cpu_to_le32(s->first_sectors_number==1?0:0x3f);
bootsector->total_sectors=cpu_to_le32(s->sector_count>0xffff?s->sector_count:0);
bootsector->u.fat16.drive_number=s->first_sectors_number==1?0:0x80;
bootsector->u.fat16.current_head=0;
bootsector->u.fat16.signature=0x29;
bootsector->u.fat16.id=cpu_to_le32(0xfabe1afd);
memcpy(bootsector->u.fat16.volume_label,"QEMU VVFAT ",11);
memcpy(bootsector->fat_type,(s->fat_type==12?"FAT12 ":s->fat_type==16?"FAT16 ":"FAT32 "),8);
bootsector->magic[0]=0x55; bootsector->magic[1]=0xaa;
return 0;
}
| 1threat
|
Problem with declaring a collection of objects : <p>When I run this code i get a Null Reference exception error when I try to add a tag to the tagCollection. I'm pretty it's an issue with how I've declared tagCollection but I'm not sure where I'm going wrong.</p>
<p>The 2 classes setup are to enable me serialize the collection back to a JSON file once I have finished collecting my data.</p>
<pre><code> class TagCollection
{
[JsonProperty("tags")]
public List<Tag> Tags { get; set; }
}
public class Tag
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
private TagCollection tagCollection;
private void createCollection(){
tagCollection.Tags.Add(
new Tag { Name = "Test", Id = "tag1", Value = "145" }
);
}
</code></pre>
| 0debug
|
How to share two private keys ,while anyone else is listening in on the conversation : <p>Cryptographic hashing is a very useful concept. The MD varieties are no longer sufficiently secure--you can break them in reasonable time using Amazon cloud. We use SHA-512 for our superuser password.</p>
<p>While we're on cryptography, you should explain how 2 people can share a completely private key while anyone else is listening in on the conversation. That is the basis of all security on the Internet.</p>
| 0debug
|
Add sequence number to fasta headers : Hi I have a set of fasta sequences starting with a different header. I need to add sequence number with increasing count (Seq1, Seq2, Seqn...) for each sequence header. Here is the first one:
input:
>[organism=Fowl Adenovirus] Fowl Adenovirus FAdV hexon gene, isolate FAdV/SP/1184/2013
output:
>Seq1 [organism=Fowl Adenovirus] Fowl Adenovirus FAdV hexon gene, isolate FAdV/SP/1184/2013
| 0debug
|
static void xenstore_update_be(char *watch, char *type, int dom,
struct XenDevOps *ops)
{
struct XenDevice *xendev;
char path[XEN_BUFSIZE], *dom0, *bepath;
unsigned int len, dev;
dom0 = xs_get_domain_path(xenstore, 0);
len = snprintf(path, sizeof(path), "%s/backend/%s/%d", dom0, type, dom);
free(dom0);
if (strncmp(path, watch, len) != 0) {
return;
}
if (sscanf(watch+len, "/%u/%255s", &dev, path) != 2) {
strcpy(path, "");
if (sscanf(watch+len, "/%u", &dev) != 1) {
dev = -1;
}
}
if (dev == -1) {
return;
}
xendev = xen_be_get_xendev(type, dom, dev, ops);
if (xendev != NULL) {
bepath = xs_read(xenstore, 0, xendev->be, &len);
if (bepath == NULL) {
xen_be_del_xendev(dom, dev);
} else {
free(bepath);
xen_be_backend_changed(xendev, path);
xen_be_check_state(xendev);
}
}
}
| 1threat
|
how to find Irregular string in a column of database (laravel) : I search for a way to find an Irregular string in a column of a database(MySQL ).
for example, I have a table named product and I have a product in this table named "Nike shoes"
know when I write for example "niksho" or "nsh" return to me "Nike shoes " or all things like this
| 0debug
|
int coroutine_fn bdrv_co_pwrite_zeroes(BlockDriverState *bs,
int64_t offset, int count,
BdrvRequestFlags flags)
{
trace_bdrv_co_pwrite_zeroes(bs, offset, count, flags);
if (!(bs->open_flags & BDRV_O_UNMAP)) {
flags &= ~BDRV_REQ_MAY_UNMAP;
}
return bdrv_co_pwritev(bs, offset, count, NULL,
BDRV_REQ_ZERO_WRITE | flags);
}
| 1threat
|
Global data with VueJs 2 : <p>Im relatively new with VueJS, and I've got no clue about how to make some data globally available. I would like to save data like API endpoints, user data and some other data that is retrieved from the API somewhere where each component can get to this data.<br>
I know I can just save this with just vanilla Javascript but I suppose there is a way to do this with VueJS. I may be able to use the event bus system to get the data but I don't know how I can implement this system to my needs.</p>
<p>I would appreciate it if somebody can help me with this.</p>
| 0debug
|
static int output_packet(AVFormatContext *ctx, int flush){
MpegMuxContext *s = ctx->priv_data;
AVStream *st;
StreamInfo *stream;
int i, avail_space=0, es_size, trailer_size;
int best_i= -1;
int best_score= INT_MIN;
int ignore_constraints=0;
int64_t scr= s->last_scr;
PacketDesc *timestamp_packet;
const int64_t max_delay= av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
retry:
for(i=0; i<ctx->nb_streams; i++){
AVStream *st = ctx->streams[i];
StreamInfo *stream = st->priv_data;
const int avail_data= av_fifo_size(stream->fifo);
const int space= stream->max_buffer_size - stream->buffer_index;
int rel_space= 1024LL*space / stream->max_buffer_size;
PacketDesc *next_pkt= stream->premux_packet;
if(s->packet_size > avail_data && !flush
&& st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
return 0;
if(avail_data==0)
continue;
av_assert0(avail_data>0);
if(space < s->packet_size && !ignore_constraints)
continue;
if(next_pkt && next_pkt->dts - scr > max_delay)
continue;
if(rel_space > best_score){
best_score= rel_space;
best_i = i;
avail_space= space;
}
}
if(best_i < 0){
int64_t best_dts= INT64_MAX;
for(i=0; i<ctx->nb_streams; i++){
AVStream *st = ctx->streams[i];
StreamInfo *stream = st->priv_data;
PacketDesc *pkt_desc= stream->predecode_packet;
if(pkt_desc && pkt_desc->dts < best_dts)
best_dts= pkt_desc->dts;
}
av_dlog(ctx, "bumping scr, scr:%f, dts:%f\n",
scr / 90000.0, best_dts / 90000.0);
if(best_dts == INT64_MAX)
return 0;
if(scr >= best_dts+1 && !ignore_constraints){
av_log(ctx, AV_LOG_ERROR, "packet too large, ignoring buffer limits to mux it\n");
ignore_constraints= 1;
}
scr= FFMAX(best_dts+1, scr);
if(remove_decoded_packets(ctx, scr) < 0)
return -1;
goto retry;
}
assert(best_i >= 0);
st = ctx->streams[best_i];
stream = st->priv_data;
assert(av_fifo_size(stream->fifo) > 0);
assert(avail_space >= s->packet_size || ignore_constraints);
timestamp_packet= stream->premux_packet;
if(timestamp_packet->unwritten_size == timestamp_packet->size){
trailer_size= 0;
}else{
trailer_size= timestamp_packet->unwritten_size;
timestamp_packet= timestamp_packet->next;
}
if(timestamp_packet){
av_dlog(ctx, "dts:%f pts:%f scr:%f stream:%d\n",
timestamp_packet->dts / 90000.0,
timestamp_packet->pts / 90000.0,
scr / 90000.0, best_i);
es_size= flush_packet(ctx, best_i, timestamp_packet->pts, timestamp_packet->dts, scr, trailer_size);
}else{
assert(av_fifo_size(stream->fifo) == trailer_size);
es_size= flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr, trailer_size);
}
if (s->is_vcd) {
int vcd_pad_bytes;
while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->premux_packet->pts) ) >= s->packet_size){
put_vcd_padding_sector(ctx);
s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL);
}
}
stream->buffer_index += es_size;
s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL);
while(stream->premux_packet && stream->premux_packet->unwritten_size <= es_size){
es_size -= stream->premux_packet->unwritten_size;
stream->premux_packet= stream->premux_packet->next;
}
if(es_size)
stream->premux_packet->unwritten_size -= es_size;
if(remove_decoded_packets(ctx, s->last_scr) < 0)
return -1;
return 1;
}
| 1threat
|
void ide_dma_cb(void *opaque, int ret)
{
IDEState *s = opaque;
int n;
int64_t sector_num;
bool stay_active = false;
if (ret < 0) {
int op = BM_STATUS_DMA_RETRY;
if (s->dma_cmd == IDE_DMA_READ)
op |= BM_STATUS_RETRY_READ;
else if (s->dma_cmd == IDE_DMA_TRIM)
op |= BM_STATUS_RETRY_TRIM;
if (ide_handle_rw_error(s, -ret, op)) {
return;
n = s->io_buffer_size >> 9;
if (n > s->nsector) {
n = s->nsector;
stay_active = true;
sector_num = ide_get_sector(s);
if (n > 0) {
dma_buf_commit(s);
sector_num += n;
ide_set_sector(s, sector_num);
s->nsector -= n;
if (s->nsector == 0) {
s->status = READY_STAT | SEEK_STAT;
ide_set_irq(s->bus);
goto eot;
n = s->nsector;
s->io_buffer_index = 0;
s->io_buffer_size = n * 512;
if (s->bus->dma->ops->prepare_buf(s->bus->dma, ide_cmd_is_read(s)) == 0) {
goto eot;
#ifdef DEBUG_AIO
printf("ide_dma_cb: sector_num=%" PRId64 " n=%d, cmd_cmd=%d\n",
sector_num, n, s->dma_cmd);
#endif
switch (s->dma_cmd) {
case IDE_DMA_READ:
s->bus->dma->aiocb = dma_bdrv_read(s->bs, &s->sg, sector_num,
ide_dma_cb, s);
break;
case IDE_DMA_WRITE:
s->bus->dma->aiocb = dma_bdrv_write(s->bs, &s->sg, sector_num,
ide_dma_cb, s);
break;
case IDE_DMA_TRIM:
s->bus->dma->aiocb = dma_bdrv_io(s->bs, &s->sg, sector_num,
ide_issue_trim, ide_dma_cb, s,
DMA_DIRECTION_TO_DEVICE);
break;
return;
eot:
if (s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) {
bdrv_acct_done(s->bs, &s->acct);
ide_set_inactive(s);
| 1threat
|
int kvm_has_xsave(void)
{
return kvm_state->xsave;
}
| 1threat
|
Frameworks for dynamically managing images in-browser in .NET : <p>Let me first explain what I am trying to achieve... I would like to develop a website that offers some product. This product consists of multiple parts (for example, say a car). The user selects different parts and an image is generated dynamically to preview what the product would look like. </p>
<p>I know how to set the website up, manage database connections, and do all of that. My question is simple: Is there an existing framework that would help me to manage the manipulation of the images easily? My intention is to have separate images of each part and to overlay them in a determined fashion to develop the full product. </p>
<p>I think this would be possible with some fancy manipulation of the basic image controls, but I thought I would see if there was anything to make my job easier. I haven't done much with images in .NET so I don't really know what is available to me as of yet. I am experienced with images in C++ and C. </p>
<p>Note: This is only for research purposes, I am not developing this for any client or job. I just want to see how to do it. I am open to using regular .NET or MVC, depending on which would be most helpful for this.</p>
<p>Thank you for any help that you can offer.</p>
| 0debug
|
C - Field has incomplete type : <p>In the below representation,</p>
<pre><code>struct Cat{
char *name;
struct Cat mother;
struct Cat *children;
};
</code></pre>
<hr>
<p>Compiler gives below error for second field, but not third field,</p>
<pre><code> error: field βmotherβ has incomplete type
struct Cat mother;
^
</code></pre>
<hr>
<p>How to understand this error?</p>
| 0debug
|
How do i fix success is not a function error : <p>I'm getting the following error in my console
Uncaught TypeError: success is not a function</p>
<p>The error gets caught in Chrome browser console here:
<strong>success();</strong></p>
<p>I figured success is not properly defined or is in the wrong area. The following JavaScript that I'm using is:</p>
<pre><code> if (jQuery === undefined) { // This ensures that jQuery is loaded before running document ready code:
getScript('/imagesrv/apps/common/js/jq/jquery-1.8.3.min.js', function() {
if (jQuery === undefined) { // Super failsafe - still somehow failed...
bindAllHandlers();
} else {
jQuery(document).ready(function(){
gpUtilsDocReady();
});
}
});
} else { // jQuery was already loaded
$(document).ready(function(){
gpUtilsDocReady();
});
}
function gpUtilsDocReady() {
$('div.headingarea').off('click').on('click', function() {
$(this).closest('div.analystgroup').find('div.expandblock').toggle('normal');
$(this).closest('div.headingarea').toggleClass('boldText');
$(this).closest('div.headingarea').find('div.arrowdown').toggleClass('arrowright','arrowdown');
});
$("div.expandblock:first").show();
$("div.arrowdown:first").toggleClass('arrowright','arrowdown');
$("div.headingarea:first").toggleClass('boldText');
}
function getScript(url, success) {
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0], done = false;
script.onload = script.onreadystatechange = function() { // Attach handlers for all browsers
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
};
};
head.appendChild(script);
}
function PTHTTPGETRequest_Replacement(url, functionOrDiv) {
if (arguments.length == 1) {
$.ajax(url);
}
else if (eval("typeof " + functionOrDiv + " == 'function'")) {
$.ajax(url).complete(window[functionOrDiv] );
}
else {
$("#" + functionOrDiv).load(url, helpCallback(functionOrDiv));
}
}
//popup window functions
function rawPopUp(url, width, height, features, target) {
// attempt to clean up all random js popups
var u = url;
var t = target;
var w = width;
var h = height;
var f = features;
// return if there is no URL
if (u == null) {
return false;
}
// set up default values if none passed
t = t ? t : "_blank";
w = w ? w : 990;
h = h ? h : 650;
f = f ? f : "resizable=yes,scrollbars=yes,toolbar=yes";
// find middle x and y position of the screen
var left = (window.screen.width - w)/2;
var top = (window.screen.height - h)/2;
var newWin=null;
var settings = 'width=' + w + ',height=' + h + ',top=' + top + ',left=' + left + ', ' + f;
newWin = window.open(u, t, settings);
newWin.focus();
return(newWin);
}
function openBio(href) {
// opens Analysts Bio
rawPopUp(href, '579', '450', 'scrollbars=yes,resizable=yes','_0');
return false;
}
var contentPopupInProgressMap = {};
/*
* containerId - The unique id of the popup container div. It must also
* contain a div with the id of <containerId>_content where
* the html content will be loaded. The entire container will
* be shown/hidden.
* uniqueId - An id that is unique to the page for identifying the popup.
* html - The html to display.
* url - The query url for the html to display.
* minDelayMs - The minimum delay until the popup is shown (hovering)
*
* Positioning is handled by the following pairs (if not supplied,
* the popup will not be positioned):
* absLeft/absCenter: Either the absolute left or center for the popup.
* absTop/absMiddle: Either the absolute top or middle for the popup.
*/
function showContentPopup(args) {
args = args || {};
var uniqueId = args.uniqueId;
// Clear the popup delay for this source from the map.
delete contentPopupInProgressMap[uniqueId];
var container = $('#' + args.containerId);
if (container) {
var popupInfo = jQuery.extend(true, {}, args);
delete popupInfo["html"];
delete popupInfo["url" ];
popupInfo.startTime = new Date().getTime();
// Add it to the inProgress map.
contentPopupInProgressMap[uniqueId]=popupInfo;
if ('html' in args && args.html) {
$('#' + popupInfo.containerId + '_content').html(args.html);
var minDelayMs = ('minDelayMs' in args && args.minDelayMs) ? args.minDelayMs : 0;
setTimeout("eval(" + "showContentPopup_callback('" + uniqueId + "')" + ")", minDelayMs);
}
else if ('url' in args && args.url) {
$.ajax({
url: args.url,
success: function(html) {
if(html) {
$('#' + popupInfo.containerId + '_content').html(html);
var minDelayMs = ('minDelayMs' in args && args.minDelayMs) ? args.minDelayMs : 0;
minDelayMs = Math.max((minDelayMs - (new Date().getTime() - popupInfo.startTime)), 0);
setTimeout("eval(" + "showContentPopup_callback('" + uniqueId + "')" + ")", minDelayMs);
}
}
});
}
}
}
function hideContentPopup(uniqueId) {
// Clear the delay.
var popupInfo = contentPopupInProgressMap[uniqueId];
if (popupInfo) {
$('#' + popupInfo.containerId).css('visibility', 'hidden');
}
delete contentPopupInProgressMap[uniqueId];
}
function showContentPopup_callback(uniqueId) {
// Show the popup if in progress.
var popupInfo = contentPopupInProgressMap[uniqueId];
if (popupInfo && !popupInfo.visibile) {
var container = $('#' + popupInfo.containerId);
if ('absCenter' in popupInfo && popupInfo.absCenter> 0) {
// Always keep the top edge of the container in view.
container.offset({ left: Math.max(popupInfo.absCenter - (container.width()/2), 2) });
}
else if ('absLeft' in popupInfo && popupInfo.absLeft >= 0) {
container.offset({ left: popupInfo.absLeft });
}
if ('absMiddle' in popupInfo && popupInfo.absMiddle > 0) {
// Always keep the left edge of the container in view.
container.offset({ top: Math.max(popupInfo.absMiddle - (container.height()/2), $(window).scrollTop() + 2) });
}
else if ('absTop' in popupInfo && popupInfo.absTop >= 0) {
container.offset({ top: popupInfo.absTop });
}
container.css('visibility', 'visible');
popupInfo.visibile = true;
}
}
function submitSearch(formName, location) {
rForm = eval('document.' + formName);
typeaheadTermType = document.getElementById("typeaheadTermType").value;
typeaheadTermId = document.getElementById("typeaheadTermId").value;
rForm.keywords.value = document.getElementById("keywords").value;
if (typeaheadTermType) {
if (typeaheadTermType.toLowerCase() == 'title') {
document.getElementById("typeaheadTermType").value = '';
document.getElementById("typeaheadTermId").value = '';
rForm.keywords.value = escape(document.getElementById("keywords").value);
window.location = documentdisplayurl + typeaheadTermId;
return false;
}
}
if (isValidKeyword(rForm.keywords.value)) {
rForm.submit();
return false;
}else if (isEmptyKeyword(rForm.keywords.value)) {
alert("Please provide keywords for your search");
return false;
} else {
alert("Your search is too general. Please provide keywords for your search.");
return false;
}
}
function isValidKeyword(keywords) {
if (keywords.match(/[A-Z]+/g) ||
keywords.match(/[a-z]+/g) ||
keywords.match(/[0-9]+/g)) {
return true;
}
if(keywords == "" || keywords == null)
{
return true;
}
return false;
}
function isEmpty(control) {
var s = control.value;
// Trim leading whitespace.
s = s.replace(/^\s+/g, '');
return (s.length == 0);
}
function isEmptyKeyword(keywords) {
if (keywords.match(/^ *$/)) {
return true;
}
if(keywords == "" || keywords == null)
{
return true;
}
return false;
}
<!-- Searchbox autocomplete-related functionality -->
function getkey(e) {
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
<!-- The submitSearch function must be implemented in the containing page. -->
function searchboxKeyPress(e, formName, location){
if (getkey(e)==13){
submitSearch(formName, location);
return false;
}
else {
return true;
}
}
if (window.hdrSearchBox_InitTypeAheadSearch2) {
function autocompleteCallbackSearchResults(searchboxName) {
var location = searchboxName.replace('/keywords/','');
submitSearch('gSearchForm', location)
}
//typeaheadsugurl is defined in header.ftl for search
dojo.addOnLoad(function() { hdrSearchBox_InitTypeAheadSearch(typeaheadsugurl,'gSearchForm', 'keywords', 'divSearchSuggestionsSearchResults', 'autocompleteCallbackSearchResults', 10); });
}
function hdrSearchBox_InitTypeAheadSearch(typeaheadLink, formName, searchboxName, suggestionsDivName, callbackFunctionName, numResults) {
//alert("personalized search:"+personalizedSearch);
var minChars = 3;
// Define an event handler to populate a hidden form field
// when an item gets selected
var typeaheadTermType = YAHOO.util.Dom.get("typeaheadTermType");
var typeaheadTermId = YAHOO.util.Dom.get("typeaheadTermId");
initTypeAheadSearch(
{ formName: formName,
searchboxName: searchboxName,
suggestionsDivName: suggestionsDivName,
minQueryLength : minChars,
url: typeaheadLink + '?num=' + numResults + '&minChars=' + minChars + '&keywords=',
requestSchema: {
resultsList : "suggestions",
fields : [
{ key: "term" },
{ key: "count" },
{ key: "separator" },
{ key: "id" },
{ key: "type" }
]
},
formatResultFunction : function(oResultData, sQuery, sResultMatch) {
document.getElementById("divSearchHistoryResults").innerHTML = '';
// Cast to Strings.
sQuery = String(sQuery);
// Preserve only alphanumerics, spaces, and the - symbol.
sQuery = sQuery.replace(/[^a-zA-Z0-9 -]|^\s+|\s+$/g, '');
// Collapse all duplicate spaces.
sQuery = sQuery.replace(/\s+/g, ' ');
var displayItem = String(oResultData.term);
var type = String(oResultData.type);
var idx = displayItem.toLowerCase().indexOf(sQuery.toLowerCase());
var pre = (idx> -1) ? displayItem.substr(0, idx) : '';
var sel = (idx> -1) ? displayItem.substr(idx, sQuery.length) : '';
var post = (idx> -1) ? displayItem.substr(idx + sQuery.length): displayItem;
var aMarkup = [''];
if( oResultData.separator && type != 'term') {
var header = "";
if (type == 'title') {
header = "Titles";
}
else if (type == 'analyst') {
header = "Analysts";
}
else if (type == 'vendor') {
header = "Vendors";
}
else if (type == 'term') {
header = "Keywords";
}
aMarkup = ['<div class=\"clusterTitle\"> <span class="TypeAheadBold">' + header + '</span></div><ul class=\"smartClusters\"><div class=\"TypeAheadWitdh\">',
pre,
'<span class="TypeAheadBold">',
sel,
'</span>',
post,
'</div></ul>'];
}
else {
aMarkup = ['<div class="TypeAheadWitdh">',
pre,
'<span class="TypeAheadBold">',
sel,
'</span>',
post,
'</div>'];
}
return (aMarkup.join(''));
},
itemSelectEventFunction:function(sType, aArgs ) {
var myAC = aArgs[0]; // reference back to the AC instance
var elLI = aArgs[1]; // reference to the selected LI element
var oData = aArgs[2]; // object literal of selected item's result data
// update hidden form fields with the selected item's id and type
typeaheadTermId.value = oData.id;
typeaheadTermType.value = oData.type;
// Disable autocomplete.
eval(searchboxName + 'Enabled' + '=false;');
// Set a timeout to re-enable the typeahead.
setTimeout(searchboxName + "Enabled=true", 3000);
// Execute the callback.
eval(callbackFunctionName + "('" + searchboxName + "')");
},
callbackFunction : callbackFunctionName,
// Turn off local cache.
queryMatchSubset : false,
maxResults: numResults });
}
// Basic type ahead configuration.
function initTypeAheadSearch(oArgs) {
// Create a var to track autocomplete enabled/disabled.
eval(oArgs.searchboxName + 'Enabled' + '=true');
function autocompleteIsDisbabled() {
return eval(oArgs.searchboxName + 'Enabled' + '==false');
}
// Trap form submit for the form containing the autocomplete.
YAHOO.util.Event.addListener(
YAHOO.util.Dom.get(oArgs.formName),
"submit",
function(e, myForm) {
YAHOO.util.Event.stopEvent(e);
// Disable autocomplete.
eval(oArgs.searchboxName + 'Enabled' + '=false;');
// Set a timeout to re-enable the typeahead.
setTimeout(oArgs.searchboxName + "Enabled=true", 3000);
}
);
// Datasource.
var ds = new YAHOO.util.XHRDataSource(oArgs.url);
ds.connTimeout=5000;
ds.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
ds.responseSchema = oArgs.requestSchema;
ds.connXhrMode = 'cancelStaleRequests';
ds.maxCacheEntries = oArgs.maxCacheEntries ? oArgs.maxCacheEntries : 10;
ds.queryMatchSubset = oArgs.queryMatchSubset ? oArgs.queryMatchSubset : false;
// Create and configure the control.
var autocomplete = new YAHOO.widget.AutoComplete(oArgs.searchboxName, oArgs.suggestionsDivName, ds);
// Only the item of interest should be returned
// (and thus appended to the url).
autocomplete.generateRequest = function(sQuery) {
return sQuery;
};
autocomplete.forceSelection = oArgs.forceSelection ? true : false;
autocomplete.maxResultsDisplayed = oArgs.maxResults ? oArgs.maxResults : 5;
autocomplete.minQueryLength = oArgs.minQueryLength ? oArgs.minQueryLength : 2;
autocomplete.queryDelay = oArgs.queryDelay ? oArgs.queryDelay :0.2;
autocomplete.typeAheadDelay = autocomplete.queryDelay + 0.1;
autocomplete.typeAhead=true;
if (oArgs.header) {
autocomplete.setHeader(oArgs.header);
}
if (oArgs.body) {
autocomplete.setBody(oArgs.body);
}
if (oArgs.footer) {
autocomplete.setFooter(oArgs.footer);
}
autocomplete.animVert = oArgs.animVert ? oArgs.animVert : true;
autocomplete.animHoriz = oArgs.animHoriz ? oArgs.animHoriz :false;
autocomplete.animSpeed = oArgs.animSpeed ? oArgs.animSpeed : 0.05;
autocomplete.autoHighlight = oArgs.autoHighlight ? oArgs.autoHighlight : false;
// Disable the browser's built-in autocomplete caching mechanism
autocomplete.allowBrowserAutocomplete = false;
autocomplete.prehighlightClassName = "yui-ac-prehighlight";
autocomplete.resultTypeList = false;
autocomplete.formatResult = oArgs.formatResultFunction;
// Block suggestion expansion of any in-progress requests.
autocomplete.doBeforeLoadData = function(oResultData, sQuery, sResultMatch) {
return !autocompleteIsDisbabled();
};
if (!autocomplete.forceSelection) {
// Hook the ENTER key to disable the autocomplete and execute the callback.
function checkReturn(e) {
var keyno = YAHOO.util.Event.getCharCode(e);
if (!autocompleteIsDisbabled() && keyno == 13) {
// Disable autocomplete.
eval(oArgs.searchboxName + 'Enabled' + '=false;');
// Set a timeout to reenable the typeahead.
setTimeout(oArgs.searchboxName + "Enabled=true", 3000);
return eval(oArgs.callbackFunction + "('" + oArgs.searchboxName + "')");
}
}
YAHOO.util.Event.addListener(autocomplete.getInputEl(), "keypress", checkReturn);
}
// Hook item selection to populate hidden fields and disable the autocomplete and execute the callback.
if (oArgs.itemSelectEventFunction) {
try {
autocomplete.itemSelectEvent.subscribe(oArgs.itemSelectEventFunction);
} catch (excep) { }
}else{
// Hook item selection to disable the autocomplete and execute the callback.
try {
autocomplete.itemSelectEvent.subscribe(function( oSelf , elItem , oData ) {
// Disable autocomplete.
eval(oArgs.searchboxName + 'Enabled' + '=false;');
// Set a timeout to re-enable the typeahead.
setTimeout(oArgs.searchboxName + "Enabled=true", 3000);
// Execute the callback.
eval(oArgs.callbackFunction + "('" + oArgs.searchboxName + "')");
});
} catch (excep) { }
}
}
function changeSearchView(viewId,isTabChange) {
//var arr = viewIdbaseUrl.split("|");
//var viewId = arr[0];
//var baseUrl = arr[1];
//TODO: Handle Browse URL redirection here based on the viewId
//Based on the viewId - determine the baseUrl - This is defined in main-nav.ftl
if(viewId == 2){
baseUrl = researchUrl;
}else if(viewId == 12){
baseUrl = analystUrl;
}
var keywords = document.getElementById("keywords").value
//Allow null keywords
var url = baseUrl + '?keywords=' + encodeURIComponent(keywords);
if(isTabChange) {
url += '&tabChg=true';
}
window.location = url;
}
function showSearchHistory() {
var keywords = document.getElementById("keywords").value
if(isEmptyKeyword(keywords)){
$.ajax({
type: 'GET',
url: searchhistoryurl,
success: function(htmlVal) {
document.getElementById("divSearchHistoryResults").innerHTML = htmlVal;
}
});
}
}
function submitSearchHistory(searchterm) {
document.getElementById("keywords").value = searchterm;
submitSearch('gSearchForm','');
return false;
}
</code></pre>
| 0debug
|
R : Add dynamic column name to row in R : <p>Sample Data :</p>
<pre><code>df <- data.frame(ProdCode = c("C1","C2"), ProdName = c("Product 1", "Product 2"), Category = c("Categ 1", "Categ 2"), "Jan-16" = c(3,2), "Apr-16" = c(3,""), "Jul-16" = c(5,2), "Oct-16" = c(5,2))
</code></pre>
<p>The value corresponding each month and product cell is rating for that product. That need to be in Rating column in output dataframe:</p>
<pre><code>> df
ProdCode ProdName Category Jan.16 Apr.16 Jul.16 Oct.16
1 C1 Product 1 Categ 1 3 3 5 5
2 C2 Product 2 Categ 2 2 2 2
</code></pre>
<p>I've above data which is required in below format:</p>
<pre><code>ProdCode Product.Name Category Rating.Date Rating
C1 Product 1 Categ 1 Jan-16 3
C1 Product 1 Categ 1 Apr-16 3
C1 Product 1 Categ 1 Jul-16 5
C1 Product 1 Categ 1 Oct-16 5
C2 Product 2 Categ 2 Jan-16 2
C2 Product 2 Categ 2 Jul-16 2
C2 Product 2 Categ 2 Oct-16 2
</code></pre>
<p>The month column are dynamic and it will increase such as in future as per product it will come as Jan-2017 etc. I could do it by using for loop but that won't worth of using R.</p>
| 0debug
|
static int opt_vstats(void *optctx, const char *opt, const char *arg)
{
char filename[40];
time_t today2 = time(NULL);
struct tm *today = localtime(&today2);
snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
today->tm_sec);
return opt_vstats_file(NULL, opt, filename);
}
| 1threat
|
int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
{
AVPacketList **next_point, *this_pktl;
AVStream *st = s->streams[pkt->stream_index];
int chunked = s->max_chunk_size || s->max_chunk_duration;
this_pktl = av_mallocz(sizeof(AVPacketList));
if (!this_pktl)
return AVERROR(ENOMEM);
this_pktl->pkt = *pkt;
pkt->destruct = NULL;
av_dup_packet(&this_pktl->pkt);
if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
next_point = &(st->last_in_packet_buffer->next);
} else {
next_point = &s->packet_buffer;
}
if (chunked) {
uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
st->interleaver_chunk_size += pkt->size;
st->interleaver_chunk_duration += pkt->duration;
if ( st->interleaver_chunk_size > s->max_chunk_size-1U
|| st->interleaver_chunk_duration > max-1U) {
st->interleaver_chunk_size =
st->interleaver_chunk_duration = 0;
this_pktl->pkt.flags |= CHUNK_START;
}
}
if (*next_point) {
if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
goto next_non_null;
if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
while ( *next_point
&& ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
|| !compare(s, &(*next_point)->pkt, pkt)))
next_point = &(*next_point)->next;
if (*next_point)
goto next_non_null;
} else {
next_point = &(s->packet_buffer_end->next);
}
}
av_assert1(!*next_point);
s->packet_buffer_end = this_pktl;
next_non_null:
this_pktl->next = *next_point;
s->streams[pkt->stream_index]->last_in_packet_buffer =
*next_point = this_pktl;
return 0;
}
| 1threat
|
Needed to make a tight O analysis of the algorithm please help me with this :
Make a tight big-O analysis of following code. I'm getting confused due to this array please help.
void main( )
{
int m,n,i,j,a[ ], b[ ], c[ ]; printf(''Enter value of m and n''); scanf(''%d %d'',&m, &n);
for (i = 0; I < n; i++)
{
a[i] = i;
b[i] = i*i;
c[i]= -i;
}
for (j = 0; j < m; j++)
{
printf(''%d\t %d\t %d\n'', a(j), b(j), c(j);
}
}
| 0debug
|
NodeJS Request how to send multipart/form-data POST request : <p>I'm trying to send a POST request to an API with an image in the request. I'm doing this with the request module but everything I try it isn't working. My current code:</p>
<pre><code>const options = {
method: "POST",
url: "https://api.LINK.com/file",
port: 443,
headers: {
"Authorization": "Basic " + auth,
"Content-Type": "multipart/form-data"
},
form : {
"image" : fs.readFileSync("./images/scr1.png")
}
};
request(options, function (err, res, body) {
if(err) console.log(err);
console.log(body);
});
</code></pre>
<p>But request uses <code>Content-Type: application/x-www-form-urlencoded</code> for some reason... How can I fix this?</p>
| 0debug
|
How to move a running process to background (UNIX) : <p>I have a terminal connected to an external machine through ssh and have a process running in it.
Is it possible move the execution to the background, so that I can close the ssh connection without the need to kill it? If so how?</p>
| 0debug
|
Getting key and vaue from local Storage and displaying using js :
i am not getting values getting only keys.
i want take key and values from local storage and display
in the paragraph while generating the paragraph dynamically
using java script .
`<body>
<p id="para1"></p>
<p id="para2"></p>
</body>
<script>
for(var i=0, len=localStorage.length; i<len; i++)
{
var p1= document.getElementById("para1");
var para = document.createElement("P");
var key = document.createTextNode(localStorage.key(0));
para.appendChild(key);
p1.appendChild(para);
console.log("key");
var p2= document.getElementById("para2");
var para2 = document.createElement("P");
var value = document.createTextNode(localStorage.getitem(key));
para2.appendChild(value);
p2.appendChild(para);
console.log("value");
}
</script>`
| 0debug
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.