problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
The shortest way to choose array with less elements : I have 2 array, which should be the shortest code to return array with less element ?
If (count($a)<count(b)) return $a;
else return $b;
| 0debug
|
static int read_data(void *opaque, uint8_t *buf, int buf_size)
{
struct playlist *v = opaque;
HLSContext *c = v->parent->priv_data;
int ret, i;
int just_opened = 0;
restart:
if (!v->needed)
return AVERROR_EOF;
if (!v->input) {
int64_t reload_interval;
struct segment *seg;
if (v->ctx && v->ctx->nb_streams) {
v->needed = 0;
for (i = 0; i < v->n_main_streams; i++) {
if (v->main_streams[i]->discard < AVDISCARD_ALL) {
v->needed = 1;
break;
}
}
}
if (!v->needed) {
av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
v->index);
return AVERROR_EOF;
}
reload_interval = default_reload_interval(v);
reload:
reload_count++;
if (reload_count > c->max_reload)
return AVERROR_EOF;
if (!v->finished &&
av_gettime_relative() - v->last_load_time >= reload_interval) {
if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
v->index);
return ret;
}
reload_interval = v->target_duration / 2;
}
if (v->cur_seq_no < v->start_seq_no) {
av_log(NULL, AV_LOG_WARNING,
"skipping %d segments ahead, expired from playlists\n",
v->start_seq_no - v->cur_seq_no);
v->cur_seq_no = v->start_seq_no;
}
if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
if (v->finished)
return AVERROR_EOF;
while (av_gettime_relative() - v->last_load_time < reload_interval) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_usleep(100*1000);
}
goto reload;
}
seg = current_segment(v);
ret = update_init_section(v, seg);
if (ret)
return ret;
ret = open_input(c, v, seg);
if (ret < 0) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
v->index);
v->cur_seq_no += 1;
goto reload;
}
just_opened = 1;
}
if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
memcpy(buf, v->init_sec_buf, copy_size);
v->init_sec_buf_read_offset += copy_size;
return copy_size;
}
ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL);
if (ret > 0) {
if (just_opened && v->is_id3_timestamped != 0) {
intercept_id3(v, buf, buf_size, &ret);
}
return ret;
}
ff_format_io_close(v->parent, &v->input);
v->cur_seq_no++;
c->cur_seq_no = v->cur_seq_no;
goto restart;
}
| 1threat
|
Vue CLI 3 sass-resources-loader - Options.loaders undefined : <p>I was able to successfully configure a new Vue project using the 3.0 version of the CLI to use <code>sass-resource-loader</code> a few weeks ago using the information posted here: <a href="https://stackoverflow.com/questions/49086021/using-sass-resources-loader-with-vue-cli-v3-x/50492650#50492650">Using sass-resources-loader with vue-cli v3.x</a></p>
<p>However, after updating everything today I'm encountering the following error when running <code>npm run serve</code>:</p>
<p><code>TypeError: Cannot read property 'scss' of undefined</code></p>
<p>the only options that seem to be getting passed into <code>.tap(options)</code> are: </p>
<p><code>{ compilerOptions: { preserveWhitespace: false } }</code></p>
<p>I don't currently know enough about <code>chainWebpack</code> to effectively debug, but I'm working on it. If anyone has any insights into what's changed to cause this error, it'd be greatly appreciated.</p>
<p>my <code>vue.config.js</code>:</p>
<pre><code>const path = require('path')
module.exports = {
chainWebpack: (config) => {
config
.module
.rule('vue')
.use('vue-loader')
.tap((options) => {
console.log(options)
options.loaders.scss = options.loaders.scss.concat({
loader: 'sass-resources-loader',
options: {
resources: [
path.resolve('./src/scss/_variables.scss'),
path.resolve('./src/scss/_mixins.scss')
]
},
})
return options
})
config
.module
.rule('scss')
.use('sass-resources-loader')
.loader('sass-resources-loader')
.options({
resources: [
path.resolve('./src/scss/_variables.scss'),
path.resolve('./src/scss/_mixins.scss')
]
})
}
}
</code></pre>
| 0debug
|
int spapr_tce_dma_zero(VIOsPAPRDevice *dev, uint64_t taddr, uint32_t size)
{
uint8_t zeroes[size];
#ifdef DEBUG_TCE
fprintf(stderr, "spapr_tce_dma_zero taddr=0x%llx size=0x%x\n",
(unsigned long long)taddr, size);
#endif
memset(zeroes, 0, size);
return spapr_tce_dma_write(dev, taddr, zeroes, size);
}
| 1threat
|
I want to change the css of a page on a the click of a link : <p>So I want to make different versions of my website (color wise) with only html and css if possible.</p>
<p>How do I make it so if someone clicks an icon the color of the page will change
Website: ibrepository.com</p>
| 0debug
|
How to pass Arrays from backing bean to java script to draw a chart using Chart.js in an Ajax call : I am using prime faces backing bean and Chart.js to draw a chart
I am selecting a row in the data table . On selection of row updating the Canvas which has the Chart in it. I am getting the values on Selection method and building two arrays one for X axis and another for y-axis. How can i pass these arrays to Java script to render the chart . I tried Prime faces JSON array to pass to java script. I could not get the values in java script
| 0debug
|
IF statement to control range of numbers using array C++ : I have created an array that holds 5 numbers, and the user inputs the numbers. If the mark is less than 0 and greater than 100, I want to print out "invalid mark number". How could I go about doing this? I thought about using an IF statement but didn't know how to go about it.
using namespace std;
int mark[5];
int main ()
{
cout << "enter mark 0: ";
cin >> mark[0];
cout << "enter mark 1: ";
cin >> mark[1];
cout << "enter mark 2: ";
cin >> mark[2];
cout << "enter mark 3: ";
cin >> mark[3];
cout << "enter mark 4: ";
cin >> mark[4];
}
| 0debug
|
Creating a bigger data frame by joining multiple data frames : <p>I currently have multiple data frames (named cont, cont2 .... cont7), and need to combine them</p>
<p>Each data frame has 2 columns; date and a mean temperature value (taken from a netcdf file)</p>
<p>The dates are monthly values, in
cont = 1951-1 to 1960-12
cont7 = 2011-1 to 2014-12
(basically monthly values split into groups of 10 years, from Jan 1951- Dec 2014)</p>
<p>How can I extent my data frame so all values are in 1 table? I want to make it continuous so as to plot a time series</p>
| 0debug
|
Efficiently merge two objects in python : <p>I have a two objects that I want to merge in such a way that all references to the two merged objects now point to the one merged object.</p>
<pre><code>#What I want
listOfObjects=[obj1, obj1, obj2, obj2, obj3]
mergeObjects(obj1, obj2)
#now
listofObjects==[merged, merged, merged, merged, obj3]
</code></pre>
<p>One way to accomplish it is this:</p>
<pre><code>def mergeObjects(obj1, obj2):
obj1.property1+=obj2.property1
obj1.property2+=obj2.property2
obj2=obj1
</code></pre>
<p>However, this has the downside that rather than having one merged object, I have a merged object and an identical copy of it. My program will merge dozens of objects with each other, so this will consume far too much memory.</p>
<p>Another way is:</p>
<pre><code>listOfObjects=[obj1, obj1, obj2, obj2, obj3]
mergeObjects(obj1, obj2)
for i in range(len(listOfObjects)):
if (listOfObjects[i]==obj2):
listOfObjects[i]==obj1
#now
listofObjects==[merged, merged, merged, merged, obj3]
#and obj2 is now free to be garbage collected
</code></pre>
<p>However, there are multiple references to these objects and iterating over every one of them each time I merge an object is also not optimal.</p>
<p>One thing I thought of is if I could use pointers. I could instead store a list of pointers to objects and then write:</p>
<pre><code>def mergeObjects(obj1_pointer, obj2_pointer):
obj1=&obj1_pointer
obj2=&obj2_pointer
obj1.property1+=obj2.property1
obj1.property2+=obj2.property2
obj2_pointer=obj1_pointer
#let's say the pointers are themselves objects so now we have:
listOfPointers==[obj1_pointer, obj1_pointer, obj1_pointer, obj1_pointer, obj3_pointer]
#obj1_pointer is now pointing to the merged object
#obj2 now has no references so is free to be deleted
</code></pre>
<p>Where I'm using & as the dereference operator.</p>
<p>So would writing my own pseudopointer object with a dereference method that returned an object be an efficient solution?</p>
<p>If not is there a cleaner way to do this (change object 1 to merged object, then have all references to object 2 instead be a reference to object 1)?</p>
| 0debug
|
static int bdrv_co_do_ioctl(BlockDriverState *bs, int req, void *buf)
{
BlockDriver *drv = bs->drv;
BdrvTrackedRequest tracked_req;
CoroutineIOCompletion co = {
.coroutine = qemu_coroutine_self(),
};
BlockAIOCB *acb;
tracked_request_begin(&tracked_req, bs, 0, 0, BDRV_TRACKED_IOCTL);
if (!drv || !drv->bdrv_aio_ioctl) {
co.ret = -ENOTSUP;
goto out;
}
acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
if (!acb) {
BdrvIoctlCompletionData *data = g_new(BdrvIoctlCompletionData, 1);
data->bh = aio_bh_new(bdrv_get_aio_context(bs),
bdrv_ioctl_bh_cb, data);
data->co = &co;
qemu_bh_schedule(data->bh);
}
qemu_coroutine_yield();
out:
tracked_request_end(&tracked_req);
return co.ret;
}
| 1threat
|
static hwaddr ppc_hash64_htab_lookup(PowerPCCPU *cpu,
ppc_slb_t *slb, target_ulong eaddr,
ppc_hash_pte64_t *pte)
{
CPUPPCState *env = &cpu->env;
hwaddr pte_offset;
hwaddr hash;
uint64_t vsid, epnmask, epn, ptem;
assert(slb->sps);
epnmask = ~((1ULL << slb->sps->page_shift) - 1);
if (slb->vsid & SLB_VSID_B) {
vsid = (slb->vsid & SLB_VSID_VSID) >> SLB_VSID_SHIFT_1T;
epn = (eaddr & ~SEGMENT_MASK_1T) & epnmask;
hash = vsid ^ (vsid << 25) ^ (epn >> slb->sps->page_shift);
} else {
vsid = (slb->vsid & SLB_VSID_VSID) >> SLB_VSID_SHIFT;
epn = (eaddr & ~SEGMENT_MASK_256M) & epnmask;
hash = vsid ^ (epn >> slb->sps->page_shift);
}
ptem = (slb->vsid & SLB_VSID_PTEM) | ((epn >> 16) & HPTE64_V_AVPN);
qemu_log_mask(CPU_LOG_MMU,
"htab_base " TARGET_FMT_plx " htab_mask " TARGET_FMT_plx
" hash " TARGET_FMT_plx "\n",
env->htab_base, env->htab_mask, hash);
qemu_log_mask(CPU_LOG_MMU,
"0 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx
" vsid=" TARGET_FMT_lx " ptem=" TARGET_FMT_lx
" hash=" TARGET_FMT_plx "\n",
env->htab_base, env->htab_mask, vsid, ptem, hash);
pte_offset = ppc_hash64_pteg_search(cpu, hash, slb, 0, ptem, pte);
if (pte_offset == -1) {
qemu_log_mask(CPU_LOG_MMU,
"1 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx
" vsid=" TARGET_FMT_lx " api=" TARGET_FMT_lx
" hash=" TARGET_FMT_plx "\n", env->htab_base,
env->htab_mask, vsid, ptem, ~hash);
pte_offset = ppc_hash64_pteg_search(cpu, ~hash, slb, 1, ptem, pte);
}
return pte_offset;
}
| 1threat
|
If statement to check array values : <p>I want to display an answer based on what value in an array the user input matches. So I want the if statement to see if what was entered matches any values in the array.</p>
| 0debug
|
Run a compiled C program on a computer where the headers don't exist : <p>I have written a code which includes the Windows.h header, and compiled it using Visual Studio.</p>
<p>I have then tried to run the EXE file alone on my other computer, which appears to lack the specified header.</p>
<p>How can I run it on the other computer without having to install VS?</p>
| 0debug
|
How to remove " " from text using regex-Python 3 : <p>So, I have a text string that I want to remove the "" from.</p>
<p><strong>Here is my text string:</strong></p>
<pre><code>string= 'Sample this is a string text with "ut" '
</code></pre>
<p><strong>Here is the output I want once using a regex expression:</strong></p>
<pre><code>string= 'Sample this is a string text with ut'
</code></pre>
<p><strong>Here is my overall code:</strong> </p>
<pre><code>import re
string= 'Sample this is a string text with "ut" '
re.sub('" "', '', string)
</code></pre>
<p>And the output just show the exact text in the string without any changes. Any suggestions?</p>
| 0debug
|
How to change the overall font of wordpress site? : I am using Duster as my theme. I wan to change the default font. Is there a way to do that?
| 0debug
|
static void gic_dist_writeb(void *opaque, hwaddr offset,
uint32_t value, MemTxAttrs attrs)
{
GICState *s = (GICState *)opaque;
int irq;
int i;
int cpu;
cpu = gic_get_current_cpu(s);
if (offset < 0x100) {
if (offset == 0) {
s->enabled = (value & 1);
DPRINTF("Distribution %sabled\n", s->enabled ? "En" : "Dis");
} else if (offset < 4) {
} else if (offset >= 0x80) {
} else {
goto bad_reg;
}
} else if (offset < 0x180) {
irq = (offset - 0x100) * 8 + GIC_BASE_IRQ;
if (irq >= s->num_irq)
goto bad_reg;
if (irq < GIC_NR_SGIS) {
value = 0xff;
}
for (i = 0; i < 8; i++) {
if (value & (1 << i)) {
int mask =
(irq < GIC_INTERNAL) ? (1 << cpu) : GIC_TARGET(irq + i);
int cm = (irq < GIC_INTERNAL) ? (1 << cpu) : ALL_CPU_MASK;
if (!GIC_TEST_ENABLED(irq + i, cm)) {
DPRINTF("Enabled IRQ %d\n", irq + i);
}
GIC_SET_ENABLED(irq + i, cm);
if (GIC_TEST_LEVEL(irq + i, mask)
&& !GIC_TEST_EDGE_TRIGGER(irq + i)) {
DPRINTF("Set %d pending mask %x\n", irq + i, mask);
GIC_SET_PENDING(irq + i, mask);
}
}
}
} else if (offset < 0x200) {
irq = (offset - 0x180) * 8 + GIC_BASE_IRQ;
if (irq >= s->num_irq)
goto bad_reg;
if (irq < GIC_NR_SGIS) {
value = 0;
}
for (i = 0; i < 8; i++) {
if (value & (1 << i)) {
int cm = (irq < GIC_INTERNAL) ? (1 << cpu) : ALL_CPU_MASK;
if (GIC_TEST_ENABLED(irq + i, cm)) {
DPRINTF("Disabled IRQ %d\n", irq + i);
}
GIC_CLEAR_ENABLED(irq + i, cm);
}
}
} else if (offset < 0x280) {
irq = (offset - 0x200) * 8 + GIC_BASE_IRQ;
if (irq >= s->num_irq)
goto bad_reg;
if (irq < GIC_NR_SGIS) {
value = 0;
}
for (i = 0; i < 8; i++) {
if (value & (1 << i)) {
GIC_SET_PENDING(irq + i, GIC_TARGET(irq + i));
}
}
} else if (offset < 0x300) {
irq = (offset - 0x280) * 8 + GIC_BASE_IRQ;
if (irq >= s->num_irq)
goto bad_reg;
if (irq < GIC_NR_SGIS) {
value = 0;
}
for (i = 0; i < 8; i++) {
if (value & (1 << i)) {
GIC_CLEAR_PENDING(irq + i, ALL_CPU_MASK);
}
}
} else if (offset < 0x400) {
goto bad_reg;
} else if (offset < 0x800) {
irq = (offset - 0x400) + GIC_BASE_IRQ;
if (irq >= s->num_irq)
goto bad_reg;
gic_set_priority(s, cpu, irq, value);
} else if (offset < 0xc00) {
if (s->num_cpu != 1 || s->revision == REV_11MPCORE) {
irq = (offset - 0x800) + GIC_BASE_IRQ;
if (irq >= s->num_irq) {
goto bad_reg;
}
if (irq < 29) {
value = 0;
} else if (irq < GIC_INTERNAL) {
value = ALL_CPU_MASK;
}
s->irq_target[irq] = value & ALL_CPU_MASK;
}
} else if (offset < 0xf00) {
irq = (offset - 0xc00) * 4 + GIC_BASE_IRQ;
if (irq >= s->num_irq)
goto bad_reg;
if (irq < GIC_NR_SGIS)
value |= 0xaa;
for (i = 0; i < 4; i++) {
if (s->revision == REV_11MPCORE || s->revision == REV_NVIC) {
if (value & (1 << (i * 2))) {
GIC_SET_MODEL(irq + i);
} else {
GIC_CLEAR_MODEL(irq + i);
}
}
if (value & (2 << (i * 2))) {
GIC_SET_EDGE_TRIGGER(irq + i);
} else {
GIC_CLEAR_EDGE_TRIGGER(irq + i);
}
}
} else if (offset < 0xf10) {
goto bad_reg;
} else if (offset < 0xf20) {
if (s->revision == REV_11MPCORE || s->revision == REV_NVIC) {
goto bad_reg;
}
irq = (offset - 0xf10);
s->sgi_pending[irq][cpu] &= ~value;
if (s->sgi_pending[irq][cpu] == 0) {
GIC_CLEAR_PENDING(irq, 1 << cpu);
}
} else if (offset < 0xf30) {
if (s->revision == REV_11MPCORE || s->revision == REV_NVIC) {
goto bad_reg;
}
irq = (offset - 0xf20);
GIC_SET_PENDING(irq, 1 << cpu);
s->sgi_pending[irq][cpu] |= value;
} else {
goto bad_reg;
}
gic_update(s);
return;
bad_reg:
qemu_log_mask(LOG_GUEST_ERROR,
"gic_dist_writeb: Bad offset %x\n", (int)offset);
}
| 1threat
|
Bash: How to remove all blank lines on all files with an extensions : <p><br/>
I'd need to remove all empty lines which are contained in all the files named "pom.xml". I've come up with this:</p>
<pre><code>find . -name 'pom.xml' -exec sed '/^$/d' {} \;
</code></pre>
<p>But it just prints out the output on the screen, which is by the way correct. I'd need however to change the files with that command. Any help?
Thanks </p>
| 0debug
|
static void load_linux(const char *kernel_filename,
const char *initrd_filename,
const char *kernel_cmdline)
{
uint16_t protocol;
uint32_t gpr[8];
uint16_t seg[6];
uint16_t real_seg;
int setup_size, kernel_size, initrd_size, cmdline_size;
uint32_t initrd_max;
uint8_t header[1024];
target_phys_addr_t real_addr, prot_addr, cmdline_addr, initrd_addr;
FILE *f, *fi;
cmdline_size = (strlen(kernel_cmdline)+16) & ~15;
f = fopen(kernel_filename, "rb");
if (!f || !(kernel_size = get_file_size(f)) ||
fread(header, 1, 1024, f) != 1024) {
fprintf(stderr, "qemu: could not load kernel '%s'\n",
kernel_filename);
exit(1);
}
#if 0
fprintf(stderr, "header magic: %#x\n", ldl_p(header+0x202));
#endif
if (ldl_p(header+0x202) == 0x53726448)
protocol = lduw_p(header+0x206);
else
protocol = 0;
if (protocol < 0x200 || !(header[0x211] & 0x01)) {
real_addr = 0x90000;
cmdline_addr = 0x9a000 - cmdline_size;
prot_addr = 0x10000;
} else if (protocol < 0x202) {
real_addr = 0x90000;
cmdline_addr = 0x9a000 - cmdline_size;
prot_addr = 0x100000;
} else {
real_addr = 0x10000;
cmdline_addr = 0x20000;
prot_addr = 0x100000;
}
#if 0
fprintf(stderr,
"qemu: real_addr = 0x" TARGET_FMT_plx "\n"
"qemu: cmdline_addr = 0x" TARGET_FMT_plx "\n"
"qemu: prot_addr = 0x" TARGET_FMT_plx "\n",
real_addr,
cmdline_addr,
prot_addr);
#endif
if (protocol >= 0x203)
initrd_max = ldl_p(header+0x22c);
else
initrd_max = 0x37ffffff;
if (initrd_max >= ram_size-ACPI_DATA_SIZE)
initrd_max = ram_size-ACPI_DATA_SIZE-1;
pstrcpy_targphys(cmdline_addr, 4096, kernel_cmdline);
if (protocol >= 0x202) {
stl_p(header+0x228, cmdline_addr);
} else {
stw_p(header+0x20, 0xA33F);
stw_p(header+0x22, cmdline_addr-real_addr);
}
if (protocol >= 0x200)
header[0x210] = 0xB0;
if (protocol >= 0x201) {
header[0x211] |= 0x80;
stw_p(header+0x224, cmdline_addr-real_addr-0x200);
}
if (initrd_filename) {
if (protocol < 0x200) {
fprintf(stderr, "qemu: linux kernel too old to load a ram disk\n");
exit(1);
}
fi = fopen(initrd_filename, "rb");
if (!fi) {
fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",
initrd_filename);
exit(1);
}
initrd_size = get_file_size(fi);
initrd_addr = (initrd_max-initrd_size) & ~4095;
fprintf(stderr, "qemu: loading initrd (%#x bytes) at 0x" TARGET_FMT_plx
"\n", initrd_size, initrd_addr);
if (!fread_targphys_ok(initrd_addr, initrd_size, fi)) {
fprintf(stderr, "qemu: read error on initial ram disk '%s'\n",
initrd_filename);
exit(1);
}
fclose(fi);
stl_p(header+0x218, initrd_addr);
stl_p(header+0x21c, initrd_size);
}
cpu_physical_memory_write(real_addr, header, 1024);
setup_size = header[0x1f1];
if (setup_size == 0)
setup_size = 4;
setup_size = (setup_size+1)*512;
kernel_size -= setup_size;
if (!fread_targphys_ok(real_addr+1024, setup_size-1024, f) ||
!fread_targphys_ok(prot_addr, kernel_size, f)) {
fprintf(stderr, "qemu: read error on kernel '%s'\n",
kernel_filename);
exit(1);
}
fclose(f);
real_seg = real_addr >> 4;
seg[0] = seg[2] = seg[3] = seg[4] = seg[4] = real_seg;
seg[1] = real_seg+0x20;
memset(gpr, 0, sizeof gpr);
gpr[4] = cmdline_addr-real_addr-16;
generate_bootsect(gpr, seg, 0);
}
| 1threat
|
static void do_smbios_option(const char *optarg)
{
if (smbios_entry_add(optarg) < 0) {
fprintf(stderr, "Wrong smbios provided\n");
exit(1);
}
}
| 1threat
|
How to use TensorFlow metrics in Keras : <p>There seem to be several threads/issues on this already but it doesn't appear to me that this has been solved:</p>
<p><a href="https://stackoverflow.com/questions/43158719/how-can-i-use-tensorflow-metric-function-within-keras-models">How can I use tensorflow metric function within keras models?</a></p>
<p><a href="https://github.com/fchollet/keras/issues/6050" rel="noreferrer">https://github.com/fchollet/keras/issues/6050</a></p>
<p><a href="https://github.com/fchollet/keras/issues/3230" rel="noreferrer">https://github.com/fchollet/keras/issues/3230</a></p>
<p>People seem to either run into problems around variable initialization or the metric being 0.</p>
<p>I need to calculate different segmentation metrics and would like to include <a href="https://www.tensorflow.org/api_docs/python/tf/metrics/mean_iou" rel="noreferrer">tf.metric.mean_iou</a> in my Keras model. This is the best I have been able to come up with so far:</p>
<pre><code>def mean_iou(y_true, y_pred):
score, up_opt = tf.metrics.mean_iou(y_true, y_pred, NUM_CLASSES)
K.get_session().run(tf.local_variables_initializer())
return score
model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=[mean_iou])
</code></pre>
<p>This code does not throw any errors but mean_iou always returns 0. I believe this is because <em>up_opt</em> is not evaluated. I have seen that prior to TF 1.3 <a href="https://github.com/fchollet/keras/issues/6050#issuecomment-301684525" rel="noreferrer">people have suggested</a> to use something along the lines of <em>control_flow_ops.with_dependencies([up_opt], score)</em> to achieve this. This does not seem possible in TF 1.3 anymore.</p>
<p>In summary, how do I evaluate TF 1.3 metrics in Keras 2.0.6? This seems like quite an important feature.</p>
| 0debug
|
How to Get value from toggle button in android? : <p>I want to get value from toggle button.so please help me to solve this problem.and give code with discription... </p>
| 0debug
|
Java - How to get items out of a list with String Arrays : <p>How do I get a specific item out of a "List" at a specific index?</p>
<pre><code>private List<String[]> rows;
</code></pre>
| 0debug
|
Single and double quotes in form fields will not write to Mysql database. Is there a solution? : <p>I have a registration form on a website. I'm using a pretty standard php form to send the form submission to me via email. I'm using a formhook to also insert those form entries into a mysql database. The only problem I have is when someone tries to include single or double quotes in a field. For instance one field asks for verbiage for the back of a t-shirt. Some people just seem to want to add quotes to their verbiage. This causes the information to not be inserted into the database. I'm somewhat new to sql and have been reading up on escaping quotes but still not grasping the solution. See my form below .. this is the formhook that inserts the information into the database. Is there a statement I can add to the php code that will allow both single and double quotes? Thank you!</p>
<pre><code>$con=mysql_connect($hostname,$username,$password);
if(! $con)
{
die('Connection Failed'.mysql_error());
}
mysql_select_db($database,$con);
//if submit is not blanked i.e. it is clicked.
{
$sql="insert into sponsors2015(realname, sponsorname, email, phone, shirtnameverbiage, platinum_2500, gold_2000, silver_1500, bronze_1000, beverage_500, longdrive_200, closest_to_pin_200, par3_150, hole_100) values('".$_REQUEST['realname']."', '".$_REQUEST['sponsorname']."', '".$_REQUEST['email']."', '".$_REQUEST['phone']."', '".$_REQUEST['shirtnameverbiage']."', '".$_REQUEST['platinum_2500']."', '".$_REQUEST['gold_2000']."', '".$_REQUEST['silver_1500']."', '".$_REQUEST['bronze_1000']."', '".$_REQUEST['beverage_500']."', '".$_REQUEST['longdrive_200']."', '".$_REQUEST['closest_to_pin_200']."', '".$_REQUEST['par3_150']."', '".$_REQUEST['hole_100']."')";
$res=mysql_query($sql);
if($res)
{
Echo header('Location: sponsor-registration-success.php');
}
Else
{
Echo header('Location: sponsor-registration-problem.php');
}
}
</code></pre>
| 0debug
|
Someone please explain contractions in Java code syntax : <p>A question from dummy.... What is the full version of code below?
How to interpret it in classic (long) version of code? </p>
<pre><code>FirebaseDatabase.getInstance()
.getReference()
.push()
.setValue(new ChatMessage(input.getText().toString(),
FirebaseAuth.getInstance()
.getCurrentUser()
.getDisplayName())
);
</code></pre>
| 0debug
|
How can i remove a sublist of a list in Ocaml? : the problem is the next: I want to delviver the first seven carts of a deck of cards. A cart is a string, and the player and the deck are lists of strings.
So i need to do a function that:
- Append the first seven strings of a list of strings (deck of cards) to other list of string (player)
- remove the first seven strings of a list of strings (deck of cards)
- it must return the player with the new cards and the deck of cards without those cards.
Thanks, i am new in Ocaml and i cant do it with loops or recursion, i cant, help.
| 0debug
|
Why is a password-protected root account a security issue in Amazon EC2? : <p>just asking this out of curiosity. i set up a free EC2 instance last night and as i was ssh-ing around the file system, i realized the root password hadn't been set, and that there was no <code>sudo</code> password. this is shocking to me, as i'm used to always setting a root/<code>sudo</code> password during the installation or post-install setup phase of any linux distribution.</p>
<p>amazon's documentation has <a href="https://aws.amazon.com/premiumsupport/knowledge-center/set-change-root-linux/" rel="nofollow noreferrer">an article on the topic</a>, where they discourage users from setting a root password at all:</p>
<blockquote>
<p>For security purposes, it's a best practice to avoid root passwords.</p>
</blockquote>
<p>why is an unsecured root account a "best practice?" and additionally, when would i want to use a temporary root password to perform a task as the article suggests?</p>
| 0debug
|
Unable to start activity ComponentInfo{com.ceit.worldofgravity/com.ceit.worldofgravity.MainMenu}: : java.lang.NullPointerException : <p>I really don't where does this NullPointerException takes place...
I checked my xml files and it's declaration..still there is a NULL...</p>
<p>This the CatLog..</p>
<pre><code>02-29 00:15:12.988: E/AndroidRuntime(1287): FATAL EXCEPTION: main
02-29 00:15:12.988: E/AndroidRuntime(1287): java.lang.RuntimeException:Unable to start activity ComponentInfo{com.ceit.worldofgravity/com.ceit.worldofgravity.MainMenu}: java.lang.NullPointerException
02-29 00:15:12.988: E/AndroidRuntime(1287): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
02-29 00:15:12.988: E/AndroidRuntime(1287): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-29 00:15:12.988: E/AndroidRuntime(1287): at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-29 00:15:12.988: E/AndroidRuntime(1287): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-29 00:15:12.988: E/AndroidRuntime(1287): at android.os.Handler.dispatchMessage(Handler.java:99)
02-29 00:15:12.988: E/AndroidRuntime(1287): at android.os.Looper.loop(Looper.java:137)
02-29 00:15:12.988: E/AndroidRuntime(1287): at android.app.ActivityThread.main(ActivityThread.java:5041)
02-29 00:15:12.988: E/AndroidRuntime(1287): at java.lang.reflect.Method.invokeNative(Native Method)
02-29 00:15:12.988: E/AndroidRuntime(1287): at java.lang.reflect.Method.invoke(Method.java:511)
02-29 00:15:12.988: E/AndroidRuntime(1287): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-29 00:15:12.988: E/AndroidRuntime(1287): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-29 00:15:12.988: E/AndroidRuntime(1287): at dalvik.system.NativeStart.main(Native Method)
02-29 00:15:12.988: E/AndroidRuntime(1287): Caused by: java.lang.NullPointerException
02-29 00:15:12.988: E/AndroidRuntime(1287): at com.ceit.worldofgravity.MainMenu.onCreate(MainMenu.java:33)
02-29 00:15:12.988: E/AndroidRuntime(1287): at android.app.Activity.performCreate(Activity.java:5104)
02-29 00:15:12.988: E/AndroidRuntime(1287): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-29 00:15:12.988: E/AndroidRuntime(1287): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
02-29 00:15:12.988: E/AndroidRuntime(1287): ... 11 more
</code></pre>
<p>Main Menu.java</p>
<p>=================================================================</p>
<pre><code>package com.ceit.worldofgravity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainMenu extends Activity{
RelativeLayout Btn;
ImageView ImageButton;
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Btn = (RelativeLayout) findViewById(R.id.btn_start);
ImageButton = (ImageView) findViewById(R.id.imageView2);
Typeface Custom = Typeface.createFromAsset(getAssets(),"Sketch 3D.otf");
txt.setTypeface(Custom);
Btn.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
return false;
}
});
Btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(MainMenu.this, Game.class);
startActivities(myIntent);
}
});
}
protected void startActivities(Intent myIntent) {
}
}
</code></pre>
<p>main.xml</p>
<pre><code> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bb"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainMenu" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="550dp"
android:layout_height="160dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@drawable/title" android:contentDescription="TODO"/>
<RelativeLayout
android:id="@+id/btn_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp" >
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/play" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/start_game"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
</code></pre>
<p></p>
| 0debug
|
After pulling from GIT files are shown in Windows File Explorer but files are exluded in Solution Explorer in Visual Studio : [Excluded in Solution Explorer.][1]
[2]: https://i.stack.imgur.com/C9t21.png
[Present in Windows Explorer][2]
[1]: https://i.stack.imgur.com/3shir.png
| 0debug
|
Eclipse Photon - Eclipse Marketplace not launching : <p>I just installed Eclipse Photon. I migraded one project from Oxygen to it - everything is working fine.</p>
<p>The problem I noticed is that I cannot open the Eclipse Marketplace. Whenever I click on it, I get the loading circle for 1-2 seconds then nothing happens.</p>
<p>I also tried this on a completely new empty workspace (so no old .metadata) - same behavior.
I also restarted PC - didn't help.</p>
<p>Any ideas? Is it me only that has this problem or is it a bug due to the new version?</p>
<p>Thanks.</p>
| 0debug
|
void qdev_prop_set_drive_nofail(DeviceState *dev, const char *name,
BlockDriverState *value)
{
if (qdev_prop_set_drive(dev, name, value) < 0) {
exit(1);
}
}
| 1threat
|
Component (unscoped) may not reference scoped bindings : <p>I've recently started using dagger-2 with kotlin. Unfortunately I have ecnountered a problem with sumbcomponants and I have trouble understanding why I get this gradle error:</p>
<pre><code>...NetComponent (unscoped) may not reference scoped bindings:
@dagger.Subcomponent(modules =
{com.example.kremik.cryptodroid.di.module.NetModule.class})
@Singleton @Provides com.example.kremik.cryptodroid.data.remote.CMCService com.example.kremik.cryptodroid.di.module.NetModule.providesCMCService(retrofit2.Retrofit)
@Singleton @Provides retrofit2.Retrofit com.example.kremik.cryptodroid.di.module.NetModule.providesRetrofit()
@org.jetbrains.annotations.NotNull @Singleton @Provides com.example.kremik.cryptodroid.data.service.CurrencyDataPresenter com.example.kremik.cryptodroid.di.module.NetModule.providesCurrencyDataPresenter(com.example.kremik.cryptodroid.data.local.CurrenciesProvider, com.example.kremik.cryptodroid.ui.LivePrices.LivePricesPresenter)
</code></pre>
<p>Module:app</p>
<pre><code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.example.kremik.cryptodroid"
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
// dataBinding {
// enabled = true
// }
kapt {
generateStubs = true
}
}
dependencies {
(...)
//Dagger2
implementation 'com.google.dagger:dagger:2.11'
implementation 'com.google.dagger:dagger-android-support:2.11'
implementation 'com.google.dagger:dagger-android-processor:2.11'
kapt 'com.google.dagger:dagger-compiler:2.11'
(...)
}
</code></pre>
<p>NetModule:
@Module
class NetModule(private val BASE_URL: String) {</p>
<pre><code>@Provides
@Singleton
fun providesCurrencyDataPresenter(provider: CurrenciesProvider,
pricesPresenter: LivePricesPresenter) =
CurrencyDataPresenter(provider, pricesPresenter)
@Provides
@Singleton
fun providesRetrofit() = Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
@Provides
@Singleton
fun providesCMCService(retrofit: Retrofit) =
retrofit.create(CMCService::class.java)
}
</code></pre>
<p>NetComponent:</p>
<pre><code>@Subcomponent(modules = arrayOf(NetModule::class))
interface NetComponent {
fun inject(service: CurrencyDownloaderService)
}
</code></pre>
<p>Does anyone know what could be the issue ?</p>
| 0debug
|
Connecting an API to an Angular 4 front-end application with JSON response : I am trying to connect my angular 4 app with backend api and getting response as and json object. Now want to show this json response to front end.
Please check below json which i am getting in response-
****{
"languages":[{"1":"Hindi"},{"2":"English"},{"3":"Metallica"}],
"status":"200"
}****
where languages tag is an json array and i want to show it in select option.
[enter image description here][1]
Please suggest
[1]: https://i.stack.imgur.com/uwW50.png
| 0debug
|
How should I fix this - 'int' object is not iterable? : <p>Unlike other questions, I'm getting this error <em>without</em> using a looping construct.</p>
<p>Here's the code</p>
<pre><code>def makes_twenty(n1,n2):
return ( (sum(n1, n2) == 20) or ((n1 == 20) or (n2 == 20)) )
</code></pre>
<p>The error I receive -
<code>'int' object is not iterable</code>
<a href="https://i.stack.imgur.com/hwPaN.png" rel="nofollow noreferrer">Screenshot of the code with error</a></p>
<p>The irony is, if I change this thing -
<code>sum(n1, n2)</code>
Into something like this -
<code>(n1 + n2)</code>
The code works fine.
<a href="https://i.stack.imgur.com/nw2YD.png" rel="nofollow noreferrer">Screenshot of corrected code</a>
I wonder what's happening here.</p>
| 0debug
|
How to make backgrund color animinate on scroll from left to right : This is my code
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<div class="titlediv" style='background:linear-gradient(90deg, #cc2900 79%, #b3b3b3 21%);'>
<h2> Hii
</div>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<p> My name is Josh and I need Help </p>
<div class="titlediv" style='background:linear-gradient(90deg, #cc2900 79%, #b3b3b3 21%);'>
<h2> Hii
</div>
<!-- end snippet -->
As you can see, their are 2 h2 with background colors.
I want to make the background color fill from left to right when it appears on screen.
Just like this website: http://preview.themeforest.net/item/movie-me-cinemamovie-bootstrap-3-html-template/full_screen_preview/8713045
Scroll down and see IMDB rating etc..
| 0debug
|
Draft refuses handshake when using java-websocket library to connect to the coinbase exchange websocket stream : <p>I am attempting to use the <a href="https://github.com/TooTallNate/Java-WebSocket" rel="noreferrer">Java-Websocket library by TooTallNate</a> to create a websocket client that receives messages from the <a href="https://docs.exchange.coinbase.com/" rel="noreferrer">coinbase exchange websocket stream</a>. I am porting a program I made in Python to Java because of parallelisation bottlenecks in Python and to my knowledge I am doing things the same in Java as I did in Python. Here is my code to open the connection in Python using <a href="https://github.com/liris/websocket-client" rel="noreferrer">this websocket lib</a> (This works as expected):</p>
<pre><code>ws = websocket.create_connection("wss://ws-feed.exchange.coinbase.com", 20)
ws.send(json.dumps({
"type": "subscribe",
"product_id": "BTC-USD"
}))
</code></pre>
<p>Here is my entire Java class:</p>
<pre><code>public class CoinbaseWebsocketClient extends WebSocketClient {
private final Gson gson = new Gson();
private CoinbaseWebsocketClient(URI serverURI) {
super(serverURI, new Draft_17());
connect();
}
private static URI uri;
private static CoinbaseWebsocketClient coinbaseWebsocketClient;
static {
try {
uri = new URI("wss://ws-feed.exchange.coinbase.com");
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
protected static CoinbaseWebsocketClient get() {
if (coinbaseWebsocketClient == null) {
coinbaseWebsocketClient = new CoinbaseWebsocketClient(uri);
}
return coinbaseWebsocketClient;
}
@Override
public void onOpen(ServerHandshake serverHandshake) {
System.out.println("Websocket open");
final JsonObject btcUSD_Request = new JsonObject();
btcUSD_Request.addProperty("type", "subscribe");
btcUSD_Request.addProperty("product_id", "BTC_USD");
final String requestString = gson.toJson(btcUSD_Request);
send(requestString);
}
@Override
public void onMessage(String s) {
System.out.println("Message received: " + s);
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("Websocket closed: " + reason);
}
@Override
public void onError(Exception e) {
System.err.println("an error occurred:" + e);
}
</code></pre>
<p>}</p>
<p>I know there isn't a totally fundamental issue with my Java code because it works as expected when I use ws://echo.websocket.org as the URI instead of wss://ws-feed.exchange.coinbase.com. However when I try to connect to wss://ws-feed.exchange.coinbase.com I get this error:</p>
<pre><code>Websocket closed: draft org.java_websocket.drafts.Draft_17@7ca2fefb refuses handshake
</code></pre>
<p>There is no authentication or anything like for this connection as far as I know (I didn't provide any in my Python program) so I'm at a loss as to what the source of this error is.</p>
| 0debug
|
static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
MOVStreamContext *sc;
int version;
char language[4] = {0};
unsigned lang;
int64_t creation_time;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
if (sc->time_scale) {
av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
return AVERROR_INVALIDDATA;
}
version = avio_r8(pb);
if (version > 1) {
avpriv_request_sample(c->fc, "Version %d", version);
return AVERROR_PATCHWELCOME;
}
avio_rb24(pb);
if (version == 1) {
creation_time = avio_rb64(pb);
avio_rb64(pb);
} else {
creation_time = avio_rb32(pb);
avio_rb32(pb);
}
mov_metadata_creation_time(&st->metadata, creation_time);
sc->time_scale = avio_rb32(pb);
if (sc->time_scale <= 0) {
av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d\n", sc->time_scale);
return AVERROR_INVALIDDATA;
}
st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
lang = avio_rb16(pb);
if (ff_mov_lang_to_iso639(lang, language))
av_dict_set(&st->metadata, "language", language, 0);
avio_rb16(pb);
return 0;
}
| 1threat
|
What is a simple explanation for displayfor and displaynamefor in asp.net? : <p>I have a class</p>
<pre><code>public class Item
{
public int ItemId { get; set; }
[Required(ErrorMessage = "Category is required")]
[Range(1, int.MaxValue, ErrorMessage = "Category is required")]
public int CategoryId { get; set; }
[Display(Name = "Current password")]
[Required(ErrorMessage = "Name is required")]
[StringLength(160)]
public string Name { get; set; }
[Required(ErrorMessage = "Price is required")]
[Range(0.01, 100.00,
ErrorMessage = "Price must be between 0.01 and 100.00")]
public decimal Price { get; set; }
public virtual Category Category { get; set; }
}
</code></pre>
<p>In my controller I pass an instance of this to view</p>
<pre><code>public ActionResult Index()
{
var model = new Item
{
CategoryId = 1,
Name = "aaa",
Price = 2
};
return View("Index", model);
}
</code></pre>
<p>then in view I try to display name using</p>
<pre><code>@model GenericShop.Models.Item
<p>
@Html.DisplayNameFor(m => m.Name)
</p>
</code></pre>
<p>and get the following error</p>
<blockquote>
<p>Compiler Error Message: CS1061:
'System.Web.Mvc.HtmlHelper' does not contain
a definition for 'DisplayNameFor' and no extension method
'DisplayNameFor' accepting a first argument of type
'System.Web.Mvc.HtmlHelper' could be found
(are you missing a using directive or an assembly reference?)</p>
</blockquote>
<p><code>@Html.DisplayFor(m => m.Name)</code> works fine, but I just cant see why </p>
<p><code>@Html.DisplayNameFor(m => m.Name)</code> does not.</p>
<p><code>DisplayFor</code> displays the value for the model item and <code>DisplayNameFor</code> simply displays the name of the property?</p>
| 0debug
|
React Native AsyncStorage storing values other than strings : <p>Is there any way to store values other than strings with AsyncStorage? I want to store simple boolean values for example.</p>
<pre><code>AsyncStorage.setItem('key', 'ok');
</code></pre>
<p>Is no problem, but:</p>
<pre><code>AsyncStorage.setItem('key', false);
</code></pre>
<p>Does not work..</p>
| 0debug
|
static void menelaus_pre_save(void *opaque)
{
MenelausState *s = opaque;
s->rtc_next_vmstate = s->rtc.next - qemu_get_clock(rt_clock);
}
| 1threat
|
In member function errors c++ : <p>I am receiving some errors when compiling my code. </p>
<pre><code>circleTypeImp.cpp: In member function âdouble circleType::getRadius() constâ:
circleTypeImp.cpp:10: error: argument of type âdouble (circleType::)()constâ does not match âdoubleâ
circleTypeImp.cpp: In member function âdouble circleType::setAreaCircle() constâ:
circleTypeImp.cpp:15: error: invalid use of member (did you forget the â&â ?)
circleTypeImp.cpp: In member function âdouble circleType::setCircumference() constâ:
circleTypeImp.cpp:20: error: invalid use of member (did you forget the â&â ?)
pointTypeImp.cpp: In member function âvoid pointType::setXCoordinate(double)â:
pointTypeImp.cpp:9: error: âxâ was not declared in this scope
pointTypeImp.cpp: In member function âvoid pointType::setYCoordinate(double)â:
pointTypeImp.cpp:14: error: âyâ was not declared in this scope
pointTypeImp.cpp: At global scope:
pointTypeImp.cpp:23: error: prototype for âdouble pointType::getXCoordinate(double)â does not match any in class âpointTypeâ
pointTypee.h:15: error: candidate is: double pointType::getXCoordinate() const
pointTypeImp.cpp:28: error: prototype for âdouble pointType::getYCoordinate(double)â does not match any in class âpointTypeâ
pointTypee.h:16: error: candidate is: double pointType::getYCoordinate() const
</code></pre>
<p>I have overlooked my code and I cant seem to see what is wrong with it. If someone could point it out to me what is needing to be done, I'd appreciate it. I am not looking for someone to do it for me, I am just needing some help figuring it out. </p>
<pre><code>//main.cpp
#include "pointTypee.h"
#include "circleTypee.h"
#include <iostream>
using namespace std;
int main()
{
pointType p;
circleType c;
double rad;
double area;
double circum;
double x;
double y;
cout << "Enter the x coordinate " << endl;
cin >> x;
cout << endl;
cout << "Enter the y coordinate " << endl;
cin >> y;
cout << endl;
cout << "The X & Y coordinates are: (" << x << "," << y << ")" << endl;
cout << "The area of the circle is: "; //Add
cout << "The circumference of the circle is: "; //Add
}
//PointType.cpp
#include "pointTypee.h"
#include <string>
#include <iostream>
void pointType::setXCoordinate (double xcoord)
{
xcoord = x;
}
void pointType::setYCoordinate (double ycoord)
{
ycoord= y;
}
void pointType::print() const
{
cout << "The center point is at (" << xcoord << "," << ycoord << ")" << endl;
cout << endl;
}
double pointType::getXCoordinate(double xcoord)
{
return xcoord;
}
double pointType::getYCoordinate(double ycoord)
{
return ycoord;
}
pointType::pointType(double xcoord, double ycoord)
{
xcoord=0;
ycoord=0;
}
//pointType.h
#ifndef POINTTYPEE_H
#define POINTTYPEE_H
#include <string>
using namespace std;
class pointType
{
public:
void print() const;
void setXCoordinate(double xcoord);
void setYCoordinate(double ycoord);
double getXCoordinate() const;
double getYCoordinate() const;
pointType(void);
pointType(double xcoord, double ycoord);
~pointType(void);
private:
double xcoord;
double ycoord;
};
#endif
//circleType.h
#ifndef CIRCLETYPEE_H
#define CIRCLETYPEE_H
#include "pointTypee.h"
class circleType : public pointType
{
public:
//circleType(double xcoord, double ycoord, double radius);
void print() const;
double setAreaCircle() const;
double setCircumference() const;
double getRadius() const;
circleType(double xcoord, double ycoord, double radius);
~circleType(void);
circleType();
//virtual ~circleType();
private:
double radius() const;
static double pie;
};
#endif
//circleTypeImp.cpp
#include "circleTypee.h"
#include "pointTypee.h"
#include <string>
#include <iostream>
double circleType::getRadius()const
{
return radius;
}
double circleType::setAreaCircle () const
{
return 3.14 * radius * radius;
}
double circleType::setCircumference() const
{
return 3.14 * 2 * radius;
}
circleType::circleType()
{
//circleType::circleType();
}
circleType::~circleType()
{
}
double pie = 3.14;
</code></pre>
| 0debug
|
static int cdrom_read_toc_raw(IDEState *s, uint8_t *buf, int msf,
int session_num)
{
uint8_t *q;
int nb_sectors, len;
q = buf + 2;
*q++ = 1;
*q++ = 1;
*q++ = 1;
*q++ = 0x14;
*q++ = 0;
*q++ = 0xa0;
*q++ = 0;
*q++ = 0;
*q++ = 0;
*q++ = 0;
*q++ = 1;
*q++ = 0x00;
*q++ = 0x00;
*q++ = 1;
*q++ = 0x14;
*q++ = 0;
*q++ = 0xa1;
*q++ = 0;
*q++ = 0;
*q++ = 0;
*q++ = 0;
*q++ = 1;
*q++ = 0x00;
*q++ = 0x00;
*q++ = 1;
*q++ = 0x14;
*q++ = 0;
*q++ = 0xa2;
*q++ = 0;
*q++ = 0;
*q++ = 0;
nb_sectors = s->nb_sectors >> 2;
if (msf) {
*q++ = 0;
lba_to_msf(q, nb_sectors);
q += 3;
} else {
cpu_to_ube32(q, nb_sectors);
q += 4;
}
*q++ = 1;
*q++ = 0x14;
*q++ = 0;
*q++ = 1;
*q++ = 0;
*q++ = 0;
*q++ = 0;
*q++ = 0;
*q++ = 0;
*q++ = 0;
*q++ = 0;
len = q - buf;
cpu_to_ube16(buf, len - 2);
return len;
}
| 1threat
|
How to force migrations to a DB if some tables already exist in Django? : <p>I have a Python/Django proyect. Due to some rolls back, and other mixed stuff we ended up in a kind of odd scenario.</p>
<p>The current scenario is like this:</p>
<ul>
<li>DB has the correct tables</li>
<li>DB can't be rolled back or dropped</li>
<li><p>Code is up to date</p></li>
<li><p>Migrations folder is <strong><em>behind</em></strong> the DB by one or two migrations. (These migrations were applied from somewhere else and that "somewhere else" doesn't exist anymore)</p></li>
<li><p>I add and alter some models</p></li>
<li>I run <em>makemigrations</em></li>
<li>New migrations are created, but it's a mix of new tables and some tables that already exist in the DB.</li>
<li>If I run <em>migrate</em> it will complain that some of the tables that I'm trying to create already exist.</li>
</ul>
<p>What I need:</p>
<p>To be able to run the migrations and kind of "ignore" the existing tables and apply the new ones. Or any alternative way to achieve this.</p>
<p>Is that possible?</p>
| 0debug
|
Who designed monokai color scheme? : <p>I am in love with Monokai color scheme. Did the makers of Sublime Text designed it or is it in use before sublime text arrived? </p>
<p>The second part of the question is that can I freely copy it for my own editor. Does anybody holds copyright over it? </p>
| 0debug
|
static void init_excp_4xx_real (CPUPPCState *env)
{
#if !defined(CONFIG_USER_ONLY)
env->excp_vectors[POWERPC_EXCP_CRITICAL] = 0x00000100;
env->excp_vectors[POWERPC_EXCP_MCHECK] = 0x00000200;
env->excp_vectors[POWERPC_EXCP_EXTERNAL] = 0x00000500;
env->excp_vectors[POWERPC_EXCP_ALIGN] = 0x00000600;
env->excp_vectors[POWERPC_EXCP_PROGRAM] = 0x00000700;
env->excp_vectors[POWERPC_EXCP_SYSCALL] = 0x00000C00;
env->excp_vectors[POWERPC_EXCP_PIT] = 0x00001000;
env->excp_vectors[POWERPC_EXCP_FIT] = 0x00001010;
env->excp_vectors[POWERPC_EXCP_WDT] = 0x00001020;
env->excp_vectors[POWERPC_EXCP_DEBUG] = 0x00002000;
env->excp_prefix = 0x00000000;
env->ivor_mask = 0x0000FFF0;
env->ivpr_mask = 0xFFFF0000;
env->hreset_vector = 0xFFFFFFFCUL;
#endif
}
| 1threat
|
void av_log_format_line(void *ptr, int level, const char *fmt, va_list vl,
char *line, int line_size, int *print_prefix)
{
char part[3][512];
format_line(ptr, level, fmt, vl, part, sizeof(part[0]), print_prefix, NULL);
snprintf(line, line_size, "%s%s%s", part[0], part[1], part[2]);
}
| 1threat
|
static uint16_t reloc_pc14_val(tcg_insn_unit *pc, tcg_insn_unit *target)
{
ptrdiff_t disp = tcg_ptr_byte_diff(target, pc);
assert(disp == (int16_t) disp);
return disp & 0xfffc;
}
| 1threat
|
Java setter and instane -- Change a variable : I'm trying to learn how to change an instance once it's already created. I have a constructor with a loop that prints my setting variable. Variable setting starts as 0 being unset, and the loop loops until the setting variable isn't 0. My obviously wrong expectations were that:
1. A new instance would be created named object.
2. The loop would run because the setting variable is 0.
3. The setting variable would be changed to 1.
4. The loop would stop.
I Ask:
1. Why isn't my while loop using the updated variable "setting"?
2. Is this the correct way to something that already instantiated?
3. If there's a better way please leave an example so I can learn.
public class test2 extends Thread
{
private int setting;
public void setSetting(int input)
{
this.setting = input;
}
public test2()
{
while (setting == 0) {
System.out.println(setting); }
}
public static void main(String[] args)
{
test2 object = new test2();
object.setSetting(1);
}
}
| 0debug
|
MSQL: Inserting row with default values : I have a table with something like 100 columns and now I would like to insert a row with some columns equal to some values and default values for all other columns. Is it possible?
| 0debug
|
Shared memory segment getting deleted? : <p>I'm using a simple pthreads process-shared mutex in a shared memory segment to coordinate multiple server instances.</p>
<p>Code is straightforward:<br>
On startup server attaches to shared memory segment if it exists, or creates it if it doesn't:<br>
<code>shm_open()</code>, <code>mmap(MAP_SHARED)</code> etc.</p>
<p>This works very well while testing, but once deployed after a while i come across cases where server instances don't coordinate at all. I can replicate this by deleting the shared memory segment after a server has started: future servers instances will create/use a new segment but the existing one is stuck with the old segment nobody uses so in effect it's isolated from the rest ...</p>
<p>So my guess is the shared memory segment in /dev/shm is getting deleted somehow, and not by me. This is the only thing that makes sense... What is going on here ??</p>
<p>Running debian with linux 4.9.</p>
| 0debug
|
Change button style on press in React Native : <p>I'd like the style of a button in my app to change when it is being pressed. What is the best way to do this?</p>
| 0debug
|
static int decode_extradata(ADTSContext *adts, uint8_t *buf, int size)
{
GetBitContext gb;
init_get_bits(&gb, buf, size * 8);
adts->objecttype = get_bits(&gb, 5) - 1;
adts->sample_rate_index = get_bits(&gb, 4);
adts->channel_conf = get_bits(&gb, 4);
adts->write_adts = 1;
return 0;
}
| 1threat
|
Safest way using Parameters Add with Value with Insert and Update in same query : I want to insert into sql and after that to update current table.
Till now i was made that with one query
example
SqlCommand cmd = new SqlCommand(Insert into CustomerTrans (Active) values @Active;Update Customers set Active=MyClass.Active,con);
cmd.ExecuteNonQuery();
So i want to handle this two queries together but also using parameters add with value.
I dont know how can i handle update query in Parameters...Is right the example below?
SqlCommand cmd = new SqlCommand(Insert into CustomerTrans (Active) values @Active;Update Customers set Active=@Active2,con);
cmd.Parameters.AddWithValue("@Active",1)
cmd.Parameters.AddWithValue("@Active2",myClass.Active)
cmd.ExecuteNonQuery();
I need the query to be executed at the same time
| 0debug
|
static int h264_mp4toannexb_filter(AVBitStreamFilterContext *bsfc,
AVCodecContext *avctx, const char *args,
uint8_t **poutbuf, int *poutbuf_size,
const uint8_t *buf, int buf_size,
int keyframe) {
H264BSFContext *ctx = bsfc->priv_data;
uint8_t unit_type;
uint32_t nal_size, cumul_size = 0;
if (!avctx->extradata || avctx->extradata_size < 6) {
*poutbuf = (uint8_t*) buf;
*poutbuf_size = buf_size;
return 0;
}
if (!ctx->sps_pps_data) {
uint16_t unit_size;
uint32_t total_size = 0;
uint8_t *out = NULL, unit_nb, sps_done = 0;
const uint8_t *extradata = avctx->extradata+4;
static const uint8_t nalu_header[4] = {0, 0, 0, 1};
ctx->length_size = (*extradata++ & 0x3) + 1;
if (ctx->length_size == 3)
return AVERROR(EINVAL);
unit_nb = *extradata++ & 0x1f;
if (!unit_nb) {
unit_nb = *extradata++;
sps_done++;
}
while (unit_nb--) {
unit_size = AV_RB16(extradata);
total_size += unit_size+4;
if (extradata+2+unit_size > avctx->extradata+avctx->extradata_size) {
av_free(out);
return AVERROR(EINVAL);
}
out = av_realloc(out, total_size);
if (!out)
return AVERROR(ENOMEM);
memcpy(out+total_size-unit_size-4, nalu_header, 4);
memcpy(out+total_size-unit_size, extradata+2, unit_size);
extradata += 2+unit_size;
if (!unit_nb && !sps_done++)
unit_nb = *extradata++;
}
ctx->sps_pps_data = out;
ctx->size = total_size;
ctx->first_idr = 1;
}
*poutbuf_size = 0;
*poutbuf = NULL;
do {
if (ctx->length_size == 1)
nal_size = buf[0];
else if (ctx->length_size == 2)
nal_size = AV_RB16(buf);
else
nal_size = AV_RB32(buf);
buf += ctx->length_size;
unit_type = *buf & 0x1f;
if (ctx->first_idr && unit_type == 5) {
alloc_and_copy(poutbuf, poutbuf_size,
ctx->sps_pps_data, ctx->size,
buf, nal_size);
ctx->first_idr = 0;
}
else {
alloc_and_copy(poutbuf, poutbuf_size,
NULL, 0,
buf, nal_size);
if (!ctx->first_idr && unit_type == 1)
ctx->first_idr = 1;
}
buf += nal_size;
cumul_size += nal_size + ctx->length_size;
} while (cumul_size < buf_size);
return 1;
}
| 1threat
|
PHP rand() vs. random_int() : <p>As <a href="http://php.net/manual/en/function.random-int.php" rel="noreferrer">php.net indicates:</a> <code>random_int()</code> function <em>Generates cryptographically secure pseudo-random integers</em>.</p>
<p>But, Can someone explain whats the difference between <code>rand()</code> & <code>random_int()</code>? Can I use <code>random_int()</code> instead of <code>rand()</code> when only requiring a random integer? Which one is faster?</p>
| 0debug
|
How to add up numbers from 1 to N using japascript and a FOR LOOP : This is the code I have currently, but it doesn't work! What's the problem with it? It SHOULD add all numbers from 1 to the base_number, but the code is not working. I am trying to learn how to code from the basics up. Thanks so much!
function start(){
var base_number = readInt("What is the base number? ");
function adding();
}
function adding(){
var sum = 0;
for (var i = 1; i < base_number + 1; i++){
sum += i;
}
return sum;
println(sum);
}
| 0debug
|
int av_samples_alloc(uint8_t **audio_data, int *linesize, int nb_channels,
int nb_samples, enum AVSampleFormat sample_fmt, int align)
{
uint8_t *buf;
int size = av_samples_get_buffer_size(NULL, nb_channels, nb_samples,
sample_fmt, align);
if (size < 0)
return size;
buf = av_mallocz(size);
if (!buf)
return AVERROR(ENOMEM);
size = av_samples_fill_arrays(audio_data, linesize, buf, nb_channels,
nb_samples, sample_fmt, align);
if (size < 0) {
av_free(buf);
return size;
}
return 0;
}
| 1threat
|
Migrating from django user model to a custom user model : <p>I am following these two references (<a href="https://code.djangoproject.com/ticket/25313" rel="noreferrer">one</a> and <a href="http://django-authtools.readthedocs.io/en/latest/how-to/migrate-to-a-custom-user-model.html" rel="noreferrer">two</a>) to have a custom user model in order to authenticate via email and also to add an extra field to it.</p>
<pre><code>class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
unique=True,
max_length=254,
)
mobile_number = models.IntegerField(unique=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
...
...
class Meta:
db_table = 'auth_user'
...
...
</code></pre>
<p>As you can see, I have added the <code>db_table='auth_user'</code> into the Meta fields of the class. Also, I have included <code>AUTH_USER_MODEL = 'accounts.User'</code> and User model app (i.e., accounts)into the <code>INSTALLED_APPS</code> in settings.py. Further more, I deleted the migrations folder from the app.</p>
<p>Then tried migrating:</p>
<pre><code>$ python manage.py makemigrations accounts
Migrations for 'accounts':
accounts/migrations/0001_initial.py:
- Create model User
$ python manage.py migrate accounts
</code></pre>
<p>Which gives me an error:</p>
<blockquote>
<p>django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'.</p>
</blockquote>
<p>How can I migrate from the existing django user model into a custom user model?</p>
| 0debug
|
Enter PEM pass phrase when converting PKCS#12 certificate into PEM : <p>I am using OpenSSL to convert my "me.p12" to PEM. When I generate "me.p12", I set a password for it. The "me.p12" contains a private key and a certificate. </p>
<p>When I convert it to PEM, I run command:</p>
<pre><code>openssl pkcs12 -in me.p12 -out me.pem
</code></pre>
<p>Then, it asked me for <code>Import Password</code>:</p>
<pre><code>Enter Import Password:
MAC verified OK
</code></pre>
<p>I entered the password I set to "me.p12", it was verified OK. But next, it ask me:</p>
<pre><code>Enter PEM pass phrase:
</code></pre>
<p>I have no idea what is that? When I generate "me.p12" I haven't set any other password. So, what is that? How to figure this out?</p>
| 0debug
|
static void dv_decode_ac(GetBitContext *gb, BlockInfo *mb, DCTELEM *block)
{
int last_index = get_bits_size(gb);
const uint8_t *scan_table = mb->scan_table;
const uint8_t *shift_table = mb->shift_table;
int pos = mb->pos;
int partial_bit_count = mb->partial_bit_count;
int level, pos1, run, vlc_len, index;
OPEN_READER(re, gb);
UPDATE_CACHE(re, gb);
if (partial_bit_count > 0) {
re_cache = ((unsigned)re_cache >> partial_bit_count) |
(mb->partial_bit_buffer << (sizeof(re_cache)*8 - partial_bit_count));
re_index -= partial_bit_count;
mb->partial_bit_count = 0;
}
for(;;) {
#ifdef VLC_DEBUG
printf("%2d: bits=%04x index=%d\n", pos, SHOW_UBITS(re, gb, 16), re_index);
#endif
index = NEG_USR32(re_cache, TEX_VLC_BITS);
vlc_len = dv_rl_vlc[index].len;
if (vlc_len < 0) {
index = NEG_USR32((unsigned)re_cache << TEX_VLC_BITS, -vlc_len) + dv_rl_vlc[index].level;
vlc_len = TEX_VLC_BITS - vlc_len;
}
level = dv_rl_vlc[index].level;
run = dv_rl_vlc[index].run;
if (re_index + vlc_len > last_index) {
mb->partial_bit_count = last_index - re_index;
mb->partial_bit_buffer = NEG_USR32(re_cache, mb->partial_bit_count);
re_index = last_index;
break;
}
re_index += vlc_len;
#ifdef VLC_DEBUG
printf("run=%d level=%d\n", run, level);
#endif
pos += run;
if (pos >= 64)
break;
if (level) {
pos1 = scan_table[pos];
block[pos1] = level << shift_table[pos1];
}
UPDATE_CACHE(re, gb);
}
CLOSE_READER(re, gb);
mb->pos = pos;
}
| 1threat
|
Realtime download optimization. How to find a leak? : <p>I'm using realtime firebase. The problem is that randomly it the graphic shows a high quantity of download on some period of time. The main question is not how to fix it. The main questions are:
1) What is the system of Download from Firebase? How does it work? What are the principles? and the Second question is 2) How to find a leak?
One more interesting fact is that app was published 17 of February BUT the highest leak was on 3rd of February that means it was while testing. It is basic chat app with profiles of users. Media is only photos. But each user got only 1 photo and total amount in storage so far is only 20mb. The size of the app is less than 50kb. So I don't understand how it is possible to download such amount of data and WHAT DATA WAS DOW
DOWNLOADED to make 5GB.
Below the graphic for 30 days
<a href="https://i.stack.imgur.com/kwTMY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kwTMY.jpg" alt="enter image description here"></a></p>
| 0debug
|
static void implicit_weight_table(H264Context *h){
MpegEncContext * const s = &h->s;
int ref0, ref1, i;
int cur_poc = s->current_picture_ptr->poc;
if( h->ref_count[0] == 1 && h->ref_count[1] == 1
&& h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
h->use_weight= 0;
h->use_weight_chroma= 0;
return;
}
h->use_weight= 2;
h->use_weight_chroma= 2;
h->luma_log2_weight_denom= 5;
h->chroma_log2_weight_denom= 5;
for (i = 0; i < 2; i++) {
h->luma_weight_flag[i] = 0;
h->chroma_weight_flag[i] = 0;
}
for(ref0=0; ref0 < h->ref_count[0]; ref0++){
int poc0 = h->ref_list[0][ref0].poc;
for(ref1=0; ref1 < h->ref_count[1]; ref1++){
int poc1 = h->ref_list[1][ref1].poc;
int td = av_clip(poc1 - poc0, -128, 127);
if(td){
int tb = av_clip(cur_poc - poc0, -128, 127);
int tx = (16384 + (FFABS(td) >> 1)) / td;
int dist_scale_factor = av_clip((tb*tx + 32) >> 6, -1024, 1023) >> 2;
if(dist_scale_factor < -64 || dist_scale_factor > 128)
h->implicit_weight[ref0][ref1] = 32;
else
h->implicit_weight[ref0][ref1] = 64 - dist_scale_factor;
}else
h->implicit_weight[ref0][ref1] = 32;
}
}
}
| 1threat
|
Weird error with NoClassDefFoundError in com.google.android.gms.ads.internal.util.aq.a : <p>I have got a weird crash report on my google console which seems to be related with google ad module.
Here is a stack trace reported on Google Console.</p>
<pre><code>java.lang.NoClassDefFoundError:
at jp.b (com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):3)
at jo.a (com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):3)
at jq.a (com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):19)
at com.google.android.gms.ads.internal.util.aq.a (com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):15)
at iu.a (com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):19)
at iu.run (com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):8)
Caused by: java.lang.ClassNotFoundException:
at dalvik.system.BaseDexClassLoader.findClass (BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass (ClassLoader.java:379)
at ad.loadClass (com.google.android.gms.dynamite_dynamiteloader@14799081@14.7.99 (100400-223214910):4)
at java.lang.ClassLoader.loadClass (ClassLoader.java:312)
</code></pre>
<p>This exception seems to be happened only on Android 9 devices. And I don't have got any clue about why this could happen.</p>
<p>I just want to know if there has been any update related with this ad module as per android 9.</p>
| 0debug
|
Is there a way to convert this json file? : <p>I have this json file:</p>
<pre><code>{
"spain" : "spanish.",
"usa" : "english",
"france" : "french",
"italy" : "italian",
...
}
</code></pre>
<p>Is there a fast way to convert that json file in this below?</p>
<pre><code>[
{ "country": "spain", "language": "spanish." }
{ "country": "usa", "language": "english." }
{ "country": "france", "language": "french." }
{ "country": "italy", "language": "italian." }
...
}
</code></pre>
| 0debug
|
static void radix_sort(RCCMPEntry *data, int size)
{
int buckets[RADIX_PASSES][NBUCKETS];
RCCMPEntry *tmp = av_malloc_array(size, sizeof(*tmp));
radix_count(data, size, buckets);
radix_sort_pass(tmp, data, size, buckets[0], 0);
radix_sort_pass(data, tmp, size, buckets[1], 1);
if (buckets[2][NBUCKETS - 1] || buckets[3][NBUCKETS - 1]) {
radix_sort_pass(tmp, data, size, buckets[2], 2);
radix_sort_pass(data, tmp, size, buckets[3], 3);
}
av_free(tmp);
}
| 1threat
|
Why does Postman show "Bad String" in this body of POST request : <p>As i was testing POST request on Postman with details shown in image. I am getting error when i Send this request.</p>
<blockquote>
<p>{
"FaultId": "Invalid post data, please correct the request",
"fault": "FAULT_INVALID_POST_REQUEST"
}</p>
</blockquote>
<p>Am i missing something.
Details:</p>
<p><a href="https://i.stack.imgur.com/Np9Zq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Np9Zq.png" alt="Error"></a></p>
| 0debug
|
static uint32_t unassigned_mem_readw(void *opaque, target_phys_addr_t addr)
{
#ifdef DEBUG_UNASSIGNED
printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);
#endif
#if defined(TARGET_ALPHA) || defined(TARGET_SPARC) || defined(TARGET_MICROBLAZE)
do_unassigned_access(addr, 0, 0, 0, 2);
#endif
return 0;
}
| 1threat
|
Perl reference Dereferencing for @var1 = [($a, $b)] : <p>I have below expression in perl</p>
<pre><code>@var1 = [($a, $b)]
</code></pre>
<p>Can anyone help me to deference the value stored in var1.</p>
| 0debug
|
I have a string that I want to get the JSON value from : <p>Hi I have a text string and I want to get the value Va rog sa ne trimiteti locatia out. </p>
<p>My text string is {"text":"Va rog sa ne trimiteti locatia"}</p>
<p>Thank you</p>
| 0debug
|
static void handle_s_without_atn(ESPState *s)
{
uint8_t buf[32];
int len;
if (s->dma && !s->dma_enabled) {
s->dma_cb = handle_s_without_atn;
return;
}
len = get_cmd(s, buf);
if (len) {
do_busid_cmd(s, buf, 0);
}
}
| 1threat
|
Variable inside variable Java : I would like to use the "int i", inside an if statement (where i wrote +i+), like so:
for (int i = 0; i <6; i++) {
if (mouseX > mindmap.c+i+mX - mindmap.c+i+.mD / 2 && mouseX < mindmap.c+i+.mX + mindmap.c+i+.mD / 2) {
if (mouseY > mindmap.c1.mY - mindmap.c1.mD / 2 && mouseY < mindmap.c1.mY + mindmap.c1.mD / 2) {
println("hej");
}
}
Can this be done?
We are using Processing as the tool.
| 0debug
|
how to get a number from an array? : question:
Suppose this is the number in my array 1,2,3,4,5,6,7,8
and each number is a position like ::
1=1 ,2=2 , 3=3, 4=4, 5=5, 6=6, 7=7, 8=8
It is not an array position just the number position
Now i want to remove the number in odd position then it becomes 2,4,6,8 ::
2=1, 4=2, 6=3, 8=4,
Now again i want to remove from the odd position so it becomes 4,8
4=1, 8=2
Now the answer is 8
so how to get this 8
Code:
int [] arr = new int [] {1, 2, 3, 4, 5, 6, 7, 8}; //I am taking certain
number in array
System.out.println("Elements of given array present on even position:");
for (int i = 1; i < arr.length; i = i+2)
{
System.out.println(arr[i]);
}
must get the value as 8 but in
output:
2
2
2
2
4
4
4
4
and so on
| 0debug
|
Docker-compose links vs external_links : <p>I believe it is simple question but I still do not get it from Docker-compose documentations. What is the difference between links and external_links?</p>
<p>I like external_links as I want to have core docker-compose and I want to extend it without overriding the core links. </p>
<p>What exactly I have, I am trying to setup logstash which depends on the elasticsearch. Elasticsearch is in the core docker-compose and the logstash is in the depending one. So I had to define the elastic search in the depended docker-compose as a reference as logstash need it as a link. BUT Elasticsearch has already its own links which I do not want to repeat them in the dependent one.</p>
<p>Can I do that with external_link instead of link?</p>
<p>I know that links will make sure that the link is up first before linking, does the external_link will do the same?</p>
<p>Any help is appreciated. Thanks.</p>
| 0debug
|
static void ehci_detach(USBPort *port)
{
EHCIState *s = port->opaque;
uint32_t *portsc = &s->portsc[port->index];
const char *owner = (*portsc & PORTSC_POWNER) ? "comp" : "ehci";
trace_usb_ehci_port_detach(port->index, owner);
if (*portsc & PORTSC_POWNER) {
USBPort *companion = s->companion_ports[port->index];
companion->ops->detach(companion);
companion->dev = NULL;
*portsc &= ~PORTSC_POWNER;
return;
}
ehci_queues_rip_device(s, port->dev, 0);
ehci_queues_rip_device(s, port->dev, 1);
*portsc &= ~(PORTSC_CONNECT|PORTSC_PED);
*portsc |= PORTSC_CSC;
ehci_raise_irq(s, USBSTS_PCD);
}
| 1threat
|
i need to get 2 decimal points in gb : i need to get decimal points in gband if any tb size there how can I retrive
below is my code
:: Example batch file to show free disk space on C:
@echo off
cls
echo.
echo Free Space on C:
echo ========================================
for /f "tokens=1-3" %%n in ('"WMIC LOGICALDISK GET Name,Size,FreeSpace | find /i "C:""') do set free=%%n& set total=%%p
echo.
rem echo %free% bytes free
set free=%free:~0,-3%
set /a free=%free%/1049
echo.
rem echo %free% MB free (approx and underestimated)
set /a free=%free%/1024
echo.
echo %free% GB free
pause > NUL
| 0debug
|
How to convert current time to Alphabetical order- Swift 3 : I am able to get current time, Now I want to current time to alphabets/Character view.
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("hours = \(hour):\(minutes):\(seconds)")
**How to get this like -**
10:30
It's half past ten
| 0debug
|
Warnings for uninitialized members disappear on the C++11 : <p>I compile this simple program:</p>
<pre><code>#include <cstdio>
#include <iostream>
using namespace std;
struct Foo
{
int a;
int b;
};
struct Bar
{
//Bar() = default;
int d;
};
int main()
{
Foo foo;
Bar bar;
printf("%d %d\n", foo.a, foo.b);
return 0;
}
</code></pre>
<p>and I get those warnings:</p>
<pre><code>$ g++ -std=c++11 -Wall -Wextra -Wpedantic foo.cpp -o foo
foo.cpp: In function ‘int main()’:
foo.cpp:21:9: warning: unused variable ‘bar’ [-Wunused-variable]
Bar bar;
^
foo.cpp:23:11: warning: ‘foo.Foo::b’ is used uninitialized in this function [-Wuninitialized]
printf("%d %d\n", foo.a, foo.b);
^
foo.cpp:23:11: warning: ‘foo.Foo::a’ is used uninitialized in this function [-Wuninitialized]
</code></pre>
<p>Of course, this is what we expect. But when I uncomment the <code>Bar</code> default ctor, there is a problem - all warnings disappear.</p>
<p>Why the <code>Bar</code> ctor disables warnings for <code>Foo</code>?</p>
<p>My GCC version is: <code>g++ (Ubuntu 5.4.0-6ubuntu1~16.04.2) 5.4.0 20160609</code>.</p>
<p>The problem does not occur on the C++03, only on the C++11 or newer.</p>
| 0debug
|
Change the value of imported variable in ES6 : <p>I'm using ES6 modules and am importing a variable from <code>moduleA</code> into <code>moduleB</code>:</p>
<pre><code>//moduleA.js
let a = 5;
let b;
export { a, b };
//moduleB.js
import { a, b } from './moduleA'
a = 6;
b = 1;
</code></pre>
<p>But on change/assignment in <code>moduleB</code> I'm getting error such as:</p>
<blockquote>
<p>a = 6;</p>
<p>ReferenceError: a is not defined</p>
</blockquote>
<p>On the other hand I can <code>console.log(a)</code> in <code>moduleB</code>.</p>
<p>It seams it is not possible to assign to imported variables? Is this true or am I missing the way to do it? Why is this not possible?</p>
| 0debug
|
static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,
uint64_t offset, uint64_t bytes,
QEMUIOVector *qiov, int flags)
{
BlockDriver *drv = bs->drv;
int64_t sector_num;
unsigned int nb_sectors;
int ret;
if (drv->bdrv_co_pwritev) {
ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov,
flags & bs->supported_write_flags);
flags &= ~bs->supported_write_flags;
goto emulate_flags;
}
sector_num = offset >> BDRV_SECTOR_BITS;
nb_sectors = bytes >> BDRV_SECTOR_BITS;
assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
if (drv->bdrv_co_writev_flags) {
ret = drv->bdrv_co_writev_flags(bs, sector_num, nb_sectors, qiov,
flags & bs->supported_write_flags);
flags &= ~bs->supported_write_flags;
} else if (drv->bdrv_co_writev) {
assert(!bs->supported_write_flags);
ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
} else {
BlockAIOCB *acb;
CoroutineIOCompletion co = {
.coroutine = qemu_coroutine_self(),
};
acb = bs->drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
bdrv_co_io_em_complete, &co);
if (acb == NULL) {
ret = -EIO;
} else {
qemu_coroutine_yield();
ret = co.ret;
}
}
emulate_flags:
if (ret == 0 && (flags & BDRV_REQ_FUA)) {
ret = bdrv_co_flush(bs);
}
return ret;
}
| 1threat
|
How can I implement a Hold button that calls a Javascript function? : I need to implement a Button and when I click and hold him for 5 seconds, I call a Javascript function and when I release the button cancel the call. How can I do that?
| 0debug
|
Gradle version 2.10 is required. Current version is 2.8 Error : <p>Following things are using in the project-</p>
<blockquote>
<p>The android studio version - 2.0 Preview 4.<br>
ANDROID_BUILD_MIN_SDK_VERSION=9<br>
ANDROID_BUILD_TARGET_SDK_VERSION=22<br>
ANDROID_BUILD_TOOLS_VERSION=22.0.1<br>
ANDROID_BUILD_SDK_VERSION=22<br></p>
</blockquote>
<pre><code>classpath 'com.android.tools.build:gradle:2.0.0-alpha9'
</code></pre>
<p>As per the error I changed the distribution url <br></p>
<pre><code>https\://services.gradle.org/distributions/gradle-2.8-all.zip
</code></pre>
<p>to</p>
<pre><code>https\://services.gradle.org/distributions/gradle-2.10-all.zip
</code></pre>
<p>but still getting the following error<br><br></p>
<blockquote>
<p>Error:(1, 1) A problem occurred evaluating project ':app'.
Failed to apply plugin [id 'com.android.application']
Gradle version 2.10 is required. Current version is 2.8. If using the gradle wrapper, try editing the distributionUrl in /Users/manishpathak/Project/live/code/ICCCricketWorldCup2015Schedule/gradle/wrapper/gradle-wrapper.properties to gradle-2.10-all.zip</p>
</blockquote>
| 0debug
|
How I can make a window and an input box in Python? : <p>Make a window 400*400
And there is an input box there
I can't do anything right now
Can you help me with my programming?</p>
| 0debug
|
javscript click and tap detection IOS, Browser : In 2018 what is the best way of simply detecting a "click" or mobile "tap" event, it has to be native, not reliant of a framework, or could be a small foot print libray. The only one I can find is [hammerjs][1] which seem overkill for just tap and click detection.
[1]: https://hammerjs.github.io/
| 0debug
|
How to debounce Textfield onChange in Dart? : <p>I'm trying to develop a TextField that update the data on a Firestore database when they change. It seems to work but I need to prevent the onChange event to fire multiple times.</p>
<p>In JS I would use lodash _debounce() but in Dart i don't know how to do it. I've read of some debounce libraries but i can't figure out how they works.</p>
<p>That's my code, it's only a test so something may be strange:</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class ClientePage extends StatefulWidget {
String idCliente;
ClientePage(this.idCliente);
@override
_ClientePageState createState() => new _ClientePageState();
}
class _ClientePageState extends State<ClientePage> {
TextEditingController nomeTextController = new TextEditingController();
void initState() {
super.initState();
// Start listening to changes
nomeTextController.addListener(((){
_updateNomeCliente(); // <- Prevent this function from run multiple times
}));
}
_updateNomeCliente = (){
print("Aggiorno nome cliente");
Firestore.instance.collection('clienti').document(widget.idCliente).setData( {
"nome" : nomeTextController.text
}, merge: true);
}
@override
Widget build(BuildContext context) {
return new StreamBuilder<DocumentSnapshot>(
stream: Firestore.instance.collection('clienti').document(widget.idCliente).snapshots(),
builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (!snapshot.hasData) return new Text('Loading...');
nomeTextController.text = snapshot.data['nome'];
return new DefaultTabController(
length: 3,
child: new Scaffold(
body: new TabBarView(
children: <Widget>[
new Column(
children: <Widget>[
new Padding(
padding: new EdgeInsets.symmetric(
vertical : 20.00
),
child: new Container(
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new Text(snapshot.data['cognome']),
new Text(snapshot.data['ragionesociale']),
],
),
),
),
new Expanded(
child: new Container(
decoration: new BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20.00),
topRight: Radius.circular(20.00)
),
color: Colors.brown,
),
child: new ListView(
children: <Widget>[
new ListTile(
title: new TextField(
style: new TextStyle(
color: Colors.white70
),
controller: nomeTextController,
decoration: new InputDecoration(labelText: "Nome")
),
)
]
)
),
)
],
),
new Text("La seconda pagina"),
new Text("La terza pagina"),
]
),
appBar: new AppBar(
title: Text(snapshot.data['nome'] + ' oh ' + snapshot.data['cognome']),
bottom: new TabBar(
tabs: <Widget>[
new Tab(text: "Informazioni"), // 1st Tab
new Tab(text: "Schede cliente"), // 2nd Tab
new Tab(text: "Altro"), // 3rd Tab
],
),
),
)
);
},
);
print("Il widget id è");
print(widget.idCliente);
}
}
</code></pre>
| 0debug
|
Difference between ExpoKit and React Native project : <p>I did a lot of research now to find out the exact differences and trade-offs between a React Native project, CRNA and an Expo project.</p>
<p>My main guidance was <a href="https://stackoverflow.com/questions/39170622/what-is-the-difference-between-expo-and-react-native/49324689#49324689">this</a></p>
<p>However I still don't understand what (dis-)advantages I have using ExpoKit with native code vs. a normal React Native project with native code, apart from the fact that I can't use Expo APIs in a normal React Native project. </p>
<p>I know that when I start a project in Expo I can eject it either as ExpoKit project or as React Native project.
In both I can use native code. In ExpoKit I can still use the Expo APIs in a normal React Native project I can't.</p>
<p>So my questions:</p>
<ol>
<li><p>What would be my interest to use a react native project if I can use native code and all Expo APIs in an ExpoKit project? In an ExpoKit project I can still use all Expo APIs and all React Native APIs, right?!</p></li>
<li><p>Could I use Expo APIs in a React Native project if I install expo with <code>npm install --save expo</code>?</p></li>
<li><p>What is the difference between React Native API and Expo API?</p></li>
</ol>
| 0debug
|
Call a function inside a function? Help to fix : <p>I'm not sure how to fix my code, could someone help!
It prints this --> "NameError: free variable 'info' referenced before assignment in enclosing scope", I don't know how to make info a global variable, i think that is the problem...Someone please help!</p>
<pre><code>import time
import random
admincode = ["26725","79124","18042","17340"]
stulogin = ["NikWad","StanBan","ChrPang","JaiPat","JusChan","AkibSidd","VijSam"]
teachercode = ["KGV"]
def main():
def accesscontrol():
global teachercode, stulogin, admincode
print("Enter: Student,Teacher or Admin")
option = input("--> ")
if option == "Student":
info()
elif option == "Teacher":
print("Enter you teacher code(xxx)")
option = input
if option == teachercode:
print("Access Granted")
info()
else:
print("Please input the correct code!")
accesscontrol()
elif option == "Admin":
print("Enter your admin code(xxxxx)")
option = input("--> ")
if option == admincode:
print("access granted, my master!")
else:
accesscontrol()
accesscontrol()
def info():
print("Hello, enter your information below")
usname = input("Username: ")
pwname = input("Password: ")
done = False
while not done:
print("Is this the information correct?[Y/N]")
option = input("--> ")
if option == "Y":
print("Information saved")
print("Username :",usname,"\nPassword:",pwname)
done = True
else:
main()
return info()
info()
main()
</code></pre>
| 0debug
|
css rule not applying 100% to height : CSS rule not working..
> #wrapper{
height:100%;
width:100%;
background-color: aliceblue;
}
not working for height.
| 0debug
|
static void bcm2835_peripherals_realize(DeviceState *dev, Error **errp)
{
BCM2835PeripheralState *s = BCM2835_PERIPHERALS(dev);
Object *obj;
MemoryRegion *ram;
Error *err = NULL;
uint32_t ram_size, vcram_size;
int n;
obj = object_property_get_link(OBJECT(dev), "ram", &err);
if (obj == NULL) {
error_setg(errp, "%s: required ram link not found: %s",
__func__, error_get_pretty(err));
return;
}
ram = MEMORY_REGION(obj);
ram_size = memory_region_size(ram);
memory_region_init_alias(&s->peri_mr_alias, OBJECT(s),
"bcm2835-peripherals", &s->peri_mr, 0,
memory_region_size(&s->peri_mr));
memory_region_add_subregion_overlap(&s->gpu_bus_mr, BCM2835_VC_PERI_BASE,
&s->peri_mr_alias, 1);
for (n = 0; n < 4; n++) {
memory_region_init_alias(&s->ram_alias[n], OBJECT(s),
"bcm2835-gpu-ram-alias[*]", ram, 0, ram_size);
memory_region_add_subregion_overlap(&s->gpu_bus_mr, (hwaddr)n << 30,
&s->ram_alias[n], 0);
}
object_property_set_bool(OBJECT(&s->ic), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
memory_region_add_subregion(&s->peri_mr, ARMCTRL_IC_OFFSET,
sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->ic), 0));
sysbus_pass_irq(SYS_BUS_DEVICE(s), SYS_BUS_DEVICE(&s->ic));
qdev_prop_set_chr(DEVICE(s->uart0), "chardev", serial_hds[0]);
object_property_set_bool(OBJECT(s->uart0), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
memory_region_add_subregion(&s->peri_mr, UART0_OFFSET,
sysbus_mmio_get_region(s->uart0, 0));
sysbus_connect_irq(s->uart0, 0,
qdev_get_gpio_in_named(DEVICE(&s->ic), BCM2835_IC_GPU_IRQ,
INTERRUPT_UART));
qdev_prop_set_chr(DEVICE(&s->aux), "chardev", serial_hds[1]);
object_property_set_bool(OBJECT(&s->aux), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
memory_region_add_subregion(&s->peri_mr, UART1_OFFSET,
sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->aux), 0));
sysbus_connect_irq(SYS_BUS_DEVICE(&s->aux), 0,
qdev_get_gpio_in_named(DEVICE(&s->ic), BCM2835_IC_GPU_IRQ,
INTERRUPT_AUX));
object_property_set_bool(OBJECT(&s->mboxes), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
memory_region_add_subregion(&s->peri_mr, ARMCTRL_0_SBM_OFFSET,
sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->mboxes), 0));
sysbus_connect_irq(SYS_BUS_DEVICE(&s->mboxes), 0,
qdev_get_gpio_in_named(DEVICE(&s->ic), BCM2835_IC_ARM_IRQ,
INTERRUPT_ARM_MAILBOX));
vcram_size = (uint32_t)object_property_get_int(OBJECT(s), "vcram-size",
&err);
if (err) {
error_propagate(errp, err);
return;
}
object_property_set_int(OBJECT(&s->fb), ram_size - vcram_size,
"vcram-base", &err);
if (err) {
error_propagate(errp, err);
return;
}
object_property_set_bool(OBJECT(&s->fb), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
memory_region_add_subregion(&s->mbox_mr, MBOX_CHAN_FB << MBOX_AS_CHAN_SHIFT,
sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->fb), 0));
sysbus_connect_irq(SYS_BUS_DEVICE(&s->fb), 0,
qdev_get_gpio_in(DEVICE(&s->mboxes), MBOX_CHAN_FB));
object_property_set_bool(OBJECT(&s->property), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
memory_region_add_subregion(&s->mbox_mr,
MBOX_CHAN_PROPERTY << MBOX_AS_CHAN_SHIFT,
sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->property), 0));
sysbus_connect_irq(SYS_BUS_DEVICE(&s->property), 0,
qdev_get_gpio_in(DEVICE(&s->mboxes), MBOX_CHAN_PROPERTY));
object_property_set_bool(OBJECT(&s->rng), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
memory_region_add_subregion(&s->peri_mr, RNG_OFFSET,
sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->rng), 0));
object_property_set_int(OBJECT(&s->sdhci), BCM2835_SDHC_CAPAREG, "capareg",
&err);
if (err) {
error_propagate(errp, err);
return;
}
object_property_set_bool(OBJECT(&s->sdhci), true, "pending-insert-quirk",
&err);
if (err) {
error_propagate(errp, err);
return;
}
object_property_set_bool(OBJECT(&s->sdhci), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
memory_region_add_subregion(&s->peri_mr, EMMC_OFFSET,
sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->sdhci), 0));
sysbus_connect_irq(SYS_BUS_DEVICE(&s->sdhci), 0,
qdev_get_gpio_in_named(DEVICE(&s->ic), BCM2835_IC_GPU_IRQ,
INTERRUPT_ARASANSDIO));
object_property_add_alias(OBJECT(s), "sd-bus", OBJECT(&s->sdhci), "sd-bus",
&err);
if (err) {
error_propagate(errp, err);
return;
}
object_property_set_bool(OBJECT(&s->dma), true, "realized", &err);
if (err) {
error_propagate(errp, err);
return;
}
memory_region_add_subregion(&s->peri_mr, DMA_OFFSET,
sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->dma), 0));
memory_region_add_subregion(&s->peri_mr, DMA15_OFFSET,
sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->dma), 1));
for (n = 0; n <= 12; n++) {
sysbus_connect_irq(SYS_BUS_DEVICE(&s->dma), n,
qdev_get_gpio_in_named(DEVICE(&s->ic),
BCM2835_IC_GPU_IRQ,
INTERRUPT_DMA0 + n));
}
}
| 1threat
|
Swift - Protocol extensions - Property default values : <p>Let's say that I have the following protocol:</p>
<pre><code>protocol Identifiable {
var id: Int {get}
var name: String {get}
}
</code></pre>
<p>And that I have the following structs:</p>
<pre><code>struct A: Identifiable {
var id: Int
var name: String
}
struct B: Identifiable {
var id: Int
var name: String
}
</code></pre>
<p>As you can see, I had to 'conform' to the Identifiable protocol in struct A and struct B. But imagine if I had N more structs that needs to conform to this protocol... I don't want to 'copy/paste' the conformance (var id: Int, var name: String)</p>
<p>So I create a <strong>protocol extension</strong>:</p>
<pre><code>extension Identifiable {
var id: Int {
return 0
}
var name: String {
return "default"
}
}
</code></pre>
<p>With this extension now I can create a struct that conforms to the Identifiable protocol without having to implement both properties:</p>
<pre><code>struct C: Identifiable {
}
</code></pre>
<p>Now the problem is that I can't set a value to the id property or the name property:</p>
<pre><code>var c: C = C()
c.id = 12 // Cannot assign to property: 'id' is a get-only property
</code></pre>
<p>This happens because in the Identifiable protocol, id and name are only gettable. Now if I change the id and name properties to <strong>{get set}</strong> I get the following error:</p>
<p><em>Type 'C' does not conform to protocol 'Identifiable'</em></p>
<p>This error happens because I haven't implemented a setter in the protocol extension... So I change the protocol extension:</p>
<pre><code>extension Identifiable {
var id: Int {
get {
return 0
}
set {
}
}
var name: String {
get {
return "default"
}
set {
}
}
}
</code></pre>
<p>Now the error goes away but if I set a new value to id or name, it gets the default value (getter). Of course, <strong>the setter is empty</strong>.</p>
<p>My question is:
<strong>What piece of code do I have to put inside the setter?</strong> Because if I add <em>self.id = newValue</em> it crashes (recursive).</p>
<p>Thanks in advance.</p>
| 0debug
|
Deleting emails via POP3/IMAP in Powershell : <p>My question here is how exactly do I go about deleting emails by id in gmail utilizing POP3 or IMAP without utilizing Netcmdlets or another external dependency. If it helps, I have some C# code which does a variety of mailbox functions, but I have no idea how to translate it into Powershell because I have never worked with C# before.
<a href="https://github.com/andyedinborough/aenetmail/blob/master/Pop3Client.cs" rel="nofollow noreferrer">https://github.com/andyedinborough/aenetmail/blob/master/Pop3Client.cs</a></p>
| 0debug
|
void qemu_tcg_configure(QemuOpts *opts, Error **errp)
{
const char *t = qemu_opt_get(opts, "thread");
if (t) {
if (strcmp(t, "multi") == 0) {
if (TCG_OVERSIZED_GUEST) {
error_setg(errp, "No MTTCG when guest word size > hosts");
} else if (use_icount) {
error_setg(errp, "No MTTCG when icount is enabled");
} else {
if (!check_tcg_memory_orders_compatible()) {
error_report("Guest expects a stronger memory ordering "
"than the host provides");
error_printf("This may cause strange/hard to debug errors");
}
mttcg_enabled = true;
}
} else if (strcmp(t, "single") == 0) {
mttcg_enabled = false;
} else {
error_setg(errp, "Invalid 'thread' setting %s", t);
}
} else {
mttcg_enabled = default_mttcg_enabled();
}
}
| 1threat
|
alert('Hello ' + user_input);
| 1threat
|
static int nut_write_header(AVFormatContext *s)
{
NUTContext *nut = s->priv_data;
ByteIOContext *bc = &s->pb;
AVCodecContext *codec;
int i, j, tmp_time, tmp_flags,tmp_stream, tmp_mul, tmp_size, tmp_fields;
nut->avf= s;
nut->stream =
av_mallocz(sizeof(StreamContext)*s->nb_streams);
put_buffer(bc, ID_STRING, strlen(ID_STRING));
put_byte(bc, 0);
nut->packet_start[2]= url_ftell(bc);
put_be64(bc, MAIN_STARTCODE);
put_packetheader(nut, bc, 120+5*256, 1);
put_v(bc, 2);
put_v(bc, s->nb_streams);
put_v(bc, MAX_DISTANCE);
put_v(bc, MAX_SHORT_DISTANCE);
put_v(bc, nut->rate_num=1);
put_v(bc, nut->rate_den=2);
put_v(bc, nut->short_startcode=0x4EFE79);
build_frame_code(s);
assert(nut->frame_code['N'].flags == FLAG_INVALID);
tmp_time= tmp_flags= tmp_stream= tmp_mul= tmp_size= INT_MAX;
for(i=0; i<256;){
tmp_fields=0;
tmp_size= 0;
if(tmp_time != nut->frame_code[i].timestamp_delta) tmp_fields=1;
if(tmp_mul != nut->frame_code[i].size_mul ) tmp_fields=2;
if(tmp_stream != nut->frame_code[i].stream_id_plus1) tmp_fields=3;
if(tmp_size != nut->frame_code[i].size_lsb ) tmp_fields=4;
tmp_time = nut->frame_code[i].timestamp_delta;
tmp_flags = nut->frame_code[i].flags;
tmp_stream= nut->frame_code[i].stream_id_plus1;
tmp_mul = nut->frame_code[i].size_mul;
tmp_size = nut->frame_code[i].size_lsb;
for(j=0; i<256; j++,i++){
if(nut->frame_code[i].timestamp_delta != tmp_time ) break;
if(nut->frame_code[i].flags != tmp_flags ) break;
if(nut->frame_code[i].stream_id_plus1 != tmp_stream) break;
if(nut->frame_code[i].size_mul != tmp_mul ) break;
if(nut->frame_code[i].size_lsb != tmp_size+j) break;
}
if(j != tmp_mul - tmp_size) tmp_fields=6;
put_v(bc, tmp_flags);
put_v(bc, tmp_fields);
if(tmp_fields>0) put_s(bc, tmp_time);
if(tmp_fields>1) put_v(bc, tmp_mul);
if(tmp_fields>2) put_v(bc, tmp_stream);
if(tmp_fields>3) put_v(bc, tmp_size);
if(tmp_fields>4) put_v(bc, 0 );
if(tmp_fields>5) put_v(bc, j);
}
update_packetheader(nut, bc, 0, 1);
for (i = 0; i < s->nb_streams; i++)
{
int nom, denom, gcd;
codec = &s->streams[i]->codec;
put_be64(bc, STREAM_STARTCODE);
put_packetheader(nut, bc, 120 + codec->extradata_size, 1);
put_v(bc, i );
put_v(bc, (codec->codec_type == CODEC_TYPE_AUDIO) ? 32 : 0);
if (codec->codec_tag)
put_vb(bc, codec->codec_tag);
else if (codec->codec_type == CODEC_TYPE_VIDEO)
{
put_vb(bc, codec_get_bmp_tag(codec->codec_id));
}
else if (codec->codec_type == CODEC_TYPE_AUDIO)
{
put_vb(bc, codec_get_wav_tag(codec->codec_id));
}
else
put_vb(bc, 0);
if (codec->codec_type == CODEC_TYPE_VIDEO)
{
nom = codec->time_base.den;
denom = codec->time_base.num;
}
else
{
nom = codec->sample_rate;
if(codec->frame_size>0)
denom= codec->frame_size;
else
denom= 1;
}
gcd= ff_gcd(nom, denom);
nom /= gcd;
denom /= gcd;
nut->stream[i].rate_num= nom;
nut->stream[i].rate_den= denom;
av_set_pts_info(s->streams[i], 60, denom, nom);
put_v(bc, codec->bit_rate);
put_vb(bc, 0);
put_v(bc, nom);
put_v(bc, denom);
if(nom / denom < 1000)
nut->stream[i].msb_timestamp_shift = 7;
else
nut->stream[i].msb_timestamp_shift = 14;
put_v(bc, nut->stream[i].msb_timestamp_shift);
put_v(bc, codec->has_b_frames);
put_byte(bc, 0);
if(codec->extradata_size){
put_v(bc, 1);
put_v(bc, codec->extradata_size);
put_buffer(bc, codec->extradata, codec->extradata_size);
}
put_v(bc, 0);
switch(codec->codec_type)
{
case CODEC_TYPE_AUDIO:
put_v(bc, codec->sample_rate);
put_v(bc, 1);
put_v(bc, codec->channels);
break;
case CODEC_TYPE_VIDEO:
put_v(bc, codec->width);
put_v(bc, codec->height);
put_v(bc, codec->sample_aspect_ratio.num);
put_v(bc, codec->sample_aspect_ratio.den);
put_v(bc, 0);
break;
default:
break;
}
update_packetheader(nut, bc, 0, 1);
}
put_be64(bc, INFO_STARTCODE);
put_packetheader(nut, bc, 30+strlen(s->author)+strlen(s->title)+
strlen(s->comment)+strlen(s->copyright)+strlen(LIBAVFORMAT_IDENT), 1);
if (s->author[0])
{
put_v(bc, 9);
put_str(bc, s->author);
}
if (s->title[0])
{
put_v(bc, 10);
put_str(bc, s->title);
}
if (s->comment[0])
{
put_v(bc, 11);
put_str(bc, s->comment);
}
if (s->copyright[0])
{
put_v(bc, 12);
put_str(bc, s->copyright);
}
if(!(s->streams[0]->codec.flags & CODEC_FLAG_BITEXACT)){
put_v(bc, 13);
put_str(bc, LIBAVFORMAT_IDENT);
}
put_v(bc, 0);
update_packetheader(nut, bc, 0, 1);
put_flush_packet(bc);
return 0;
}
| 1threat
|
pandas DataFrame, how to apply function to a specific column? : <p>I have read the docs of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="noreferrer">DataFrame.apply</a></p>
<blockquote>
<p>DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)¶
Applies function along input axis of DataFrame.</p>
</blockquote>
<p>So, How can I apply a function to a specific column?</p>
<pre><code>In [1]: import pandas as pd
In [2]: data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
In [3]: df = pd.DataFrame(data)
In [4]: df
Out[4]:
A B C
0 1 4 7
1 2 5 8
2 3 6 9
In [5]: def addOne(v):
...: v += 1
...: return v
...:
In [6]: df.apply(addOne, axis=1)
Out[6]:
A B C
0 2 5 8
1 3 6 9
2 4 7 10
</code></pre>
<p>I want to addOne to every value in <code>df['A']</code>, not all columns. How can I do that with <code>DataFrame.apply</code>.</p>
<p>Thanks for help! </p>
| 0debug
|
Error after update: Cannot resolve module 'react/lib/ReactMount' : <p>So I was trying to put my react-webpack app on Heroku when I started getting the error that ReactMount was not at React/lib/ReactMount. Then I tried a lot of different stuff and ended up trying to create a new project with the same react-webpack generater. And now I get the same mistake even when running on localhost meaning that it must be due to an update somewhere, right?</p>
<p>Does anyone know anything about this?</p>
<p>I have the following dependencies:</p>
<pre><code> "devDependencies": {
"babel-core": "^6.0.0",
"babel-eslint": "^6.0.0",
"babel-loader": "^6.0.0",
"babel-polyfill": "^6.3.14",
"babel-preset-es2015": "^6.0.15",
"babel-preset-react": "^6.0.15",
"babel-preset-stage-0": "^6.5.0",
"bower-webpack-plugin": "^0.1.9",
"chai": "^3.2.0",
"copyfiles": "^1.0.0",
"css-loader": "^0.23.0",
"eslint": "^3.0.0",
"eslint-loader": "^1.0.0",
"eslint-plugin-react": "^6.0.0",
"file-loader": "^0.9.0",
"glob": "^7.0.0",
"isparta-instrumenter-loader": "^1.0.0",
"karma": "^1.0.0",
"karma-chai": "^0.1.0",
"karma-coverage": "^1.0.0",
"karma-mocha": "^1.0.0",
"karma-mocha-reporter": "^2.0.0",
"karma-phantomjs-launcher": "^1.0.0",
"karma-sourcemap-loader": "^0.3.5",
"karma-webpack": "^1.7.0",
"minimist": "^1.2.0",
"mocha": "^3.0.0",
"null-loader": "^0.1.1",
"open": "0.0.5",
"phantomjs-prebuilt": "^2.0.0",
"react-addons-test-utils": "^15.0.0",
"react-hot-loader": "^1.2.9",
"rimraf": "^2.4.3",
"style-loader": "^0.13.0",
"url-loader": "^0.5.6",
"webpack": "^1.12.0",
"webpack-dev-server": "^1.12.0"
"dependencies": {
"core-js": "^2.0.0",
"firebase": "^3.5.2",
"input-moment": "^0.3.0",
"moment": "^2.15.2",
"normalize.css": "^4.0.0",
"react": "^15.0.0",
"react-bootstrap-datetimepicker": "0.0.22",
"react-datetimepicker-bootstrap": "^1.1.2",
"react-dom": "^15.0.0",
"webpack": "^1.13.3"
</code></pre>
| 0debug
|
DriveInfo *drive_get_by_id(const char *id)
{
DriveInfo *dinfo;
TAILQ_FOREACH(dinfo, &drives, next) {
if (strcmp(id, dinfo->id))
continue;
return dinfo;
}
return NULL;
}
| 1threat
|
I need a Convert PostgreSql to SQL : Ok right to do,
This is the expression i need to "translate"
case when position('.' in campo30) >= 1
then CAST(replace(replace(CAMPO30,'.',''),',','.') AS FLOAT)
else CAST(replace(CAMPO30,',','.') AS FLOAT)
end
Any people can i Help me?
Thanks
| 0debug
|
int load_vmstate(const char *name)
{
BlockDriverState *bs, *bs_vm_state;
QEMUSnapshotInfo sn;
QEMUFile *f;
int ret;
if (!bdrv_all_can_snapshot(&bs)) {
error_report("Device '%s' is writable but does not support snapshots.",
bdrv_get_device_name(bs));
return -ENOTSUP;
}
bs_vm_state = find_vmstate_bs();
if (!bs_vm_state) {
error_report("No block device supports snapshots");
return -ENOTSUP;
}
ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
if (ret < 0) {
return ret;
} else if (sn.vm_state_size == 0) {
error_report("This is a disk-only snapshot. Revert to it offline "
"using qemu-img.");
return -EINVAL;
}
bs = NULL;
while ((bs = bdrv_next(bs))) {
if (!bdrv_can_snapshot(bs)) {
continue;
}
ret = bdrv_snapshot_find(bs, &sn, name);
if (ret < 0) {
error_report("Device '%s' does not have the requested snapshot '%s'",
bdrv_get_device_name(bs), name);
return ret;
}
}
bdrv_drain_all();
ret = bdrv_all_goto_snapshot(name, &bs);
if (ret < 0) {
error_report("Error %d while activating snapshot '%s' on '%s'",
ret, name, bdrv_get_device_name(bs));
return ret;
}
f = qemu_fopen_bdrv(bs_vm_state, 0);
if (!f) {
error_report("Could not open VM state file");
return -EINVAL;
}
qemu_system_reset(VMRESET_SILENT);
migration_incoming_state_new(f);
ret = qemu_loadvm_state(f);
qemu_fclose(f);
migration_incoming_state_destroy();
if (ret < 0) {
error_report("Error %d while loading VM state", ret);
return ret;
}
return 0;
}
| 1threat
|
db.execute('SELECT * FROM employees WHERE id = ' + user_input)
| 1threat
|
Force Outlook Add-in popup to open with embedded browser : <p>I'm seeing an issue with my Outlook Add-in (running in Outlook 2016) where when I open a popup window using <code>window.open</code>, it sometimes opens in the user's default browser (e.g. Chrome) instead of the browser running the add-in (e.g. the IE11 web view embedded in Outlook 2016). This is a problem because it prevents the popup window from communicating with the add-in, which is necessary for clickjacking protection.</p>
<p>Is there a way to force the popup window to be opened in the same browser that is running the add-in, without using the Dialog API? I would like to support requirement set 1.3.</p>
| 0debug
|
START_TEST(qdict_get_try_int_test)
{
int ret;
const int value = 100;
const char *key = "int";
qdict_put(tests_dict, key, qint_from_int(value));
ret = qdict_get_try_int(tests_dict, key, 0);
fail_unless(ret == value);
}
| 1threat
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.