problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
how to check overlapping of multiple number ranges injavascript : <p>I have a problem in javascript in which i need to determine if the set of number ranges has overlapping.
examples : </p>
<p>1 - 5,
4 - 6,
7 - 8
(has overlap)</p>
<p>1 - 5,
6 - 8,
9 - 12
(has no overlap)</p>
<p>thanks in advance!</p>
| 0debug
|
static void pxa2xx_lcdc_write(void *opaque, hwaddr offset,
uint64_t value, unsigned size)
{
PXA2xxLCDState *s = (PXA2xxLCDState *) opaque;
int ch;
switch (offset) {
case LCCR0:
if ((s->control[0] & LCCR0_ENB) && !(value & LCCR0_ENB))
s->status[0] |= LCSR0_QD;
if (!(s->control[0] & LCCR0_LCDT) && (value & LCCR0_LCDT))
printf("%s: internal frame buffer unsupported\n", __FUNCTION__);
if ((s->control[3] & LCCR3_API) &&
(value & LCCR0_ENB) && !(value & LCCR0_LCDT))
s->status[0] |= LCSR0_ABC;
s->control[0] = value & 0x07ffffff;
pxa2xx_lcdc_int_update(s);
s->dma_ch[0].up = !!(value & LCCR0_ENB);
s->dma_ch[1].up = (s->ovl1c[0] & OVLC1_EN) || (value & LCCR0_SDS);
break;
case LCCR1:
s->control[1] = value;
break;
case LCCR2:
s->control[2] = value;
break;
case LCCR3:
s->control[3] = value & 0xefffffff;
s->bpp = LCCR3_BPP(value);
break;
case LCCR4:
s->control[4] = value & 0x83ff81ff;
break;
case LCCR5:
s->control[5] = value & 0x3f3f3f3f;
break;
case OVL1C1:
if (!(s->ovl1c[0] & OVLC1_EN) && (value & OVLC1_EN))
printf("%s: Overlay 1 not supported\n", __FUNCTION__);
s->ovl1c[0] = value & 0x80ffffff;
s->dma_ch[1].up = (value & OVLC1_EN) || (s->control[0] & LCCR0_SDS);
break;
case OVL1C2:
s->ovl1c[1] = value & 0x000fffff;
break;
case OVL2C1:
if (!(s->ovl2c[0] & OVLC1_EN) && (value & OVLC1_EN))
printf("%s: Overlay 2 not supported\n", __FUNCTION__);
s->ovl2c[0] = value & 0x80ffffff;
s->dma_ch[2].up = !!(value & OVLC1_EN);
s->dma_ch[3].up = !!(value & OVLC1_EN);
s->dma_ch[4].up = !!(value & OVLC1_EN);
break;
case OVL2C2:
s->ovl2c[1] = value & 0x007fffff;
break;
case CCR:
if (!(s->ccr & CCR_CEN) && (value & CCR_CEN))
printf("%s: Hardware cursor unimplemented\n", __FUNCTION__);
s->ccr = value & 0x81ffffe7;
s->dma_ch[5].up = !!(value & CCR_CEN);
break;
case CMDCR:
s->cmdcr = value & 0xff;
break;
case TRGBR:
s->trgbr = value & 0x00ffffff;
break;
case TCR:
s->tcr = value & 0x7fff;
break;
case 0x200 ... 0x1000:
ch = (offset - 0x200) >> 4;
if (!(ch >= 0 && ch < PXA_LCDDMA_CHANS))
goto fail;
switch (offset & 0xf) {
case DMA_FDADR:
s->dma_ch[ch].descriptor = value & 0xfffffff0;
break;
default:
goto fail;
}
break;
case FBR0:
s->dma_ch[0].branch = value & 0xfffffff3;
break;
case FBR1:
s->dma_ch[1].branch = value & 0xfffffff3;
break;
case FBR2:
s->dma_ch[2].branch = value & 0xfffffff3;
break;
case FBR3:
s->dma_ch[3].branch = value & 0xfffffff3;
break;
case FBR4:
s->dma_ch[4].branch = value & 0xfffffff3;
break;
case FBR5:
s->dma_ch[5].branch = value & 0xfffffff3;
break;
case FBR6:
s->dma_ch[6].branch = value & 0xfffffff3;
break;
case BSCNTR:
s->bscntr = value & 0xf;
break;
case PRSR:
break;
case LCSR0:
s->status[0] &= ~(value & 0xfff);
if (value & LCSR0_BER)
s->status[0] &= ~LCSR0_BERCH(7);
break;
case LCSR1:
s->status[1] &= ~(value & 0x3e3f3f);
break;
default:
fail:
hw_error("%s: Bad offset " REG_FMT "\n", __FUNCTION__, offset);
}
}
| 1threat
|
Uses of a Virtual destructor in C++(other than desctruction order correctness) : <p>Every C++ programmer knows that, virtual destructor is used to ensure the proper destruction order of objects in inheritance hierarchy.</p>
<p>Where else "Virtual Destructors" are used/can be used in realtime scenarios?</p>
| 0debug
|
Python and Regex - Replace Date : <p>I have multiple strings in the form of : </p>
<pre><code>AM-2019-04-22 06-47-57865BCBFB-9414907A-4450BB24
</code></pre>
<p>And I need the month from the date part replaced with something else, for example:</p>
<pre><code>AM-2019-07-22 06-47-57865BCBFB-9414907A-4450BB24
</code></pre>
<p>How can I achieve this using python and regex?</p>
<p>Also, I have multiple text files that contain a line similar to this:</p>
<pre><code>LocalTime: 21/4/2019 21:48:41
</code></pre>
<p>And I need to do the same thing as above (replace the month with something else).</p>
| 0debug
|
Java - grouping identical exceptions in logs : <p>Is there any logging solution with exception grouping feature? What I want to achieve is when some exception is logged for example 100 times in 10 seconds I don't want to log 100 stack traces. I want to log something like <code>RuntimeException was thrown 100 times: single stack trace here</code>. It'd perfect to have something integrated with <code>log4j</code>.</p>
<p>Ofc there is an option to create some logging facade with exception queue inside but maybe there is something already implemented.</p>
| 0debug
|
How do I convert an entire nested hash (key and values) to lowercase in Ruby? : I have a nested hash(Ruby)
Hash = { "abc" => { "def" => { "count" => 120 } } ,
"ABC" => {"DEF" => { "COUNT" => 100 } },
"sample" => {"samplecode" => {"COUNT" => 3 } } }
I want to convert the entire hash to lowercase and after converting if any duplicates exists I want to add the count value i.e.,
the resulting hash should be
Result = { "abc" => { "def" => { "count" => 220 } } ,
"sample" => { "samplecode" => { "count" => 3} } }
Thanks in advance :)
| 0debug
|
How can i schedule a VBA Macro to run once a day at a specific time without opening the excel sheet or the vba macro : I don't know where to even begin,your help will be much appreciated.
| 0debug
|
void ppc_store_msr_32 (CPUPPCState *env, uint32_t value)
{
do_store_msr(env,
(do_load_msr(env) & ~0xFFFFFFFFULL) | (value & 0xFFFFFFFF));
}
| 1threat
|
static int pcm_dvd_parse_header(AVCodecContext *avctx, const uint8_t *header)
{
static const uint32_t frequencies[4] = { 48000, 96000, 44100, 32000 };
PCMDVDContext *s = avctx->priv_data;
int header_int = (header[0] & 0xe0) | (header[1] << 8) | (header[2] << 16);
if (s->last_header == header_int)
return 0;
if (avctx->debug & FF_DEBUG_PICT_INFO)
av_dlog(avctx, "pcm_dvd_parse_header: header = %02x%02x%02x\n",
header[0], header[1], header[2]);
s->extra_sample_count = 0;
avctx->bits_per_coded_sample = 16 + (header[1] >> 6 & 3) * 4;
if (avctx->bits_per_coded_sample == 28) {
av_log(avctx, AV_LOG_ERROR,
"PCM DVD unsupported sample depth %i\n",
avctx->bits_per_coded_sample);
return AVERROR_INVALIDDATA;
}
avctx->sample_fmt = avctx->bits_per_coded_sample == 16 ? AV_SAMPLE_FMT_S16
: AV_SAMPLE_FMT_S32;
avctx->bits_per_raw_sample = avctx->bits_per_coded_sample;
avctx->sample_rate = frequencies[header[1] >> 4 & 3];
avctx->channels = 1 + (header[1] & 7);
avctx->bit_rate = avctx->channels *
avctx->sample_rate *
avctx->bits_per_coded_sample;
if (avctx->bits_per_coded_sample == 16) {
s->samples_per_block = 1;
s->block_size = avctx->channels * 2;
} else {
switch (avctx->channels) {
case 1:
case 2:
case 4:
s->block_size = 4 * avctx->bits_per_coded_sample / 8;
s->samples_per_block = 4 / avctx->channels;
s->groups_per_block = 1;
break;
case 8:
s->block_size = 8 * avctx->bits_per_coded_sample / 8;
s->samples_per_block = 1;
s->groups_per_block = 2;
break;
default:
s->block_size = 4 * avctx->channels *
avctx->bits_per_coded_sample / 8;
s->samples_per_block = 4;
s->groups_per_block = avctx->channels;
break;
}
}
if (avctx->debug & FF_DEBUG_PICT_INFO)
av_dlog(avctx,
"pcm_dvd_parse_header: %d channels, %d bits per sample, %d Hz, %d bit/s\n",
avctx->channels, avctx->bits_per_coded_sample,
avctx->sample_rate, avctx->bit_rate);
s->last_header = header_int;
return 0;
}
| 1threat
|
Very low GPU usage during training in Tensorflow : <p>I am trying to train a simple multi-layer perceptron for a 10-class image classification task, which is a part of the assignment for the Udacity Deep-Learning course. To be more precise, the task is to classify letters rendered from various fonts (the dataset is called notMNIST).</p>
<p>The code I ended up with looks fairly simple, but no matter what I always get very low GPU usage during training. I measure load with GPU-Z and it shows just 25-30%.</p>
<p>Here is my current code:</p>
<pre><code>graph = tf.Graph()
with graph.as_default():
tf.set_random_seed(52)
# dataset definition
dataset = Dataset.from_tensor_slices({'x': train_data, 'y': train_labels})
dataset = dataset.shuffle(buffer_size=20000)
dataset = dataset.batch(128)
iterator = dataset.make_initializable_iterator()
sample = iterator.get_next()
x = sample['x']
y = sample['y']
# actual computation graph
keep_prob = tf.placeholder(tf.float32)
is_training = tf.placeholder(tf.bool, name='is_training')
fc1 = dense_batch_relu_dropout(x, 1024, is_training, keep_prob, 'fc1')
fc2 = dense_batch_relu_dropout(fc1, 300, is_training, keep_prob, 'fc2')
fc3 = dense_batch_relu_dropout(fc2, 50, is_training, keep_prob, 'fc3')
logits = dense(fc3, NUM_CLASSES, 'logits')
with tf.name_scope('accuracy'):
accuracy = tf.reduce_mean(
tf.cast(tf.equal(tf.argmax(y, 1), tf.argmax(logits, 1)), tf.float32),
)
accuracy_percent = 100 * accuracy
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
# ensures that we execute the update_ops before performing the train_op
# needed for batch normalization (apparently)
train_op = tf.train.AdamOptimizer(learning_rate=1e-3, epsilon=1e-3).minimize(loss)
with tf.Session(graph=graph) as sess:
tf.global_variables_initializer().run()
step = 0
epoch = 0
while True:
sess.run(iterator.initializer, feed_dict={})
while True:
step += 1
try:
sess.run(train_op, feed_dict={keep_prob: 0.5, is_training: True})
except tf.errors.OutOfRangeError:
logger.info('End of epoch #%d', epoch)
break
# end of epoch
train_l, train_ac = sess.run(
[loss, accuracy_percent],
feed_dict={x: train_data, y: train_labels, keep_prob: 1, is_training: False},
)
test_l, test_ac = sess.run(
[loss, accuracy_percent],
feed_dict={x: test_data, y: test_labels, keep_prob: 1, is_training: False},
)
logger.info('Train loss: %f, train accuracy: %.2f%%', train_l, train_ac)
logger.info('Test loss: %f, test accuracy: %.2f%%', test_l, test_ac)
epoch += 1
</code></pre>
<p>Here's what I tried so far:</p>
<ol>
<li><p>I changed the input pipeline from simple <code>feed_dict</code> to <code>tensorflow.contrib.data.Dataset</code>. As far as I understood, it is supposed to take care of the efficiency of the input, e.g. load data in a separate thread. So there should not be any bottleneck associated with the input.</p></li>
<li><p>I collected traces as suggested here: <a href="https://github.com/tensorflow/tensorflow/issues/1824#issuecomment-225754659" rel="noreferrer">https://github.com/tensorflow/tensorflow/issues/1824#issuecomment-225754659</a>
However, these traces didn't really show anything interesting. >90% of the train step is matmul operations.</p></li>
<li><p>Changed batch size. When I change it from 128 to 512 the load increases from ~30% to ~38%, when I increase it further to 2048, the load goes to ~45%. I have 6Gb GPU memory and dataset is single channel 28x28 images. Am I really supposed to use such a big batch size? Should I increase it further?</p></li>
</ol>
<p>Generally, should I worry about the low load, is it really a sign that I am training inefficiently?</p>
<p>Here's the GPU-Z screenshots with 128 images in the batch. You can see low load with occasional spikes to 100% when I measure accuracy on the entire dataset after each epoch.</p>
<p><a href="https://i.stack.imgur.com/0x0MS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0x0MS.png" alt="GPU load"></a> </p>
| 0debug
|
i am new to android programming does anyone tell me why the program shows error that it cant resolve setText : this is the program.The last line it shows error like it cannot resolve settext and tostring.
public void onButtonClick(View v){}
EditText e1=(EditText)findViewById(R.id.editText);
EditText e2=(EditText)findViewById(R.id.editText2);
TextView t1=(TextView)findViewById(R.id.textView);
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int sum = num1 + num2;
t1.setText(Integer.toString(sum));
| 0debug
|
I need some assistance writing to a excel file : <p>I am programming a task in which a user will enter a sentence (no punctuation), and the program will store the words in a list, and then replace each word with the position of the word in the list that was created.
I do not have much of an idea about how to approach this, as I am new to python, however I am assuming that I should first store the words in an Excel database and then position them in the list.
If I could have some help with this I would greatly appreciate it, thanks.</p>
<p>For more information about the task, view this screenshot:<a href="http://i.stack.imgur.com/8pQNQ.png" rel="nofollow">Task Details</a></p>
| 0debug
|
How to find files taking up disk space in Linux : <p>I'm trying to find the largest files on my 25GB Linux server which has been steadily running out of space and is now 99.5% full. I assumed it was log files since I wasn't doing anything with the sites, and the database sizes are small and static.</p>
<p>Log files were a 100MB or so, nothing major.</p>
<p>I've tried the command found here (<a href="https://www.cyberciti.biz/faq/linux-find-largest-file-in-directory-recursively-using-find-du/" rel="nofollow noreferrer">https://www.cyberciti.biz/faq/linux-find-largest-file-in-directory-recursively-using-find-du/</a>) to recursively find the biggest files but its not giving me anything useful:</p>
<pre><code>root@127:~# du -a / | sort -n -r | head -n 20
du: cannot access '/proc/12377/task/12377/fd/4': No such file or directory
du: cannot access '/proc/12377/task/12377/fdinfo/4': No such file or directory
du: cannot access '/proc/12377/fd/3': No such file or directory
du: cannot access '/proc/12377/fdinfo/3': No such file or directory
sort: write failed: /tmp/sortnI7YzR: No space left on device
</code></pre>
<p>I'm a Linux novice so would appreciate any help. </p>
| 0debug
|
void qemu_spice_destroy_primary_surface(SimpleSpiceDisplay *ssd,
uint32_t id, qxl_async_io async)
{
if (async != QXL_SYNC) {
#if SPICE_INTERFACE_QXL_MINOR >= 1
spice_qxl_destroy_primary_surface_async(&ssd->qxl, id, 0);
#else
abort();
#endif
} else {
ssd->worker->destroy_primary_surface(ssd->worker, id);
}
}
| 1threat
|
static int iscsi_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
IscsiLun *iscsilun = bs->opaque;
struct iscsi_context *iscsi = NULL;
struct iscsi_url *iscsi_url = NULL;
struct scsi_task *task = NULL;
struct scsi_inquiry_standard *inq = NULL;
struct scsi_inquiry_supported_pages *inq_vpd;
char *initiator_name = NULL;
QemuOpts *opts;
Error *local_err = NULL;
const char *filename;
int i, ret;
if ((BDRV_SECTOR_SIZE % 512) != 0) {
error_setg(errp, "iSCSI: Invalid BDRV_SECTOR_SIZE. "
"BDRV_SECTOR_SIZE(%lld) is not a multiple "
"of 512", BDRV_SECTOR_SIZE);
return -EINVAL;
}
opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
qemu_opts_absorb_qdict(opts, options, &local_err);
if (local_err) {
error_propagate(errp, local_err);
ret = -EINVAL;
goto out;
}
filename = qemu_opt_get(opts, "filename");
iscsi_url = iscsi_parse_full_url(iscsi, filename);
if (iscsi_url == NULL) {
error_setg(errp, "Failed to parse URL : %s", filename);
ret = -EINVAL;
goto out;
}
memset(iscsilun, 0, sizeof(IscsiLun));
initiator_name = parse_initiator_name(iscsi_url->target);
iscsi = iscsi_create_context(initiator_name);
if (iscsi == NULL) {
error_setg(errp, "iSCSI: Failed to create iSCSI context.");
ret = -ENOMEM;
goto out;
}
if (iscsi_set_targetname(iscsi, iscsi_url->target)) {
error_setg(errp, "iSCSI: Failed to set target name.");
ret = -EINVAL;
goto out;
}
if (iscsi_url->user != NULL) {
ret = iscsi_set_initiator_username_pwd(iscsi, iscsi_url->user,
iscsi_url->passwd);
if (ret != 0) {
error_setg(errp, "Failed to set initiator username and password");
ret = -EINVAL;
goto out;
}
}
parse_chap(iscsi, iscsi_url->target, &local_err);
if (local_err != NULL) {
error_propagate(errp, local_err);
ret = -EINVAL;
goto out;
}
if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
error_setg(errp, "iSCSI: Failed to set session type to normal.");
ret = -EINVAL;
goto out;
}
iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
parse_header_digest(iscsi, iscsi_url->target, &local_err);
if (local_err != NULL) {
error_propagate(errp, local_err);
ret = -EINVAL;
goto out;
}
if (iscsi_full_connect_sync(iscsi, iscsi_url->portal, iscsi_url->lun) != 0) {
error_setg(errp, "iSCSI: Failed to connect to LUN : %s",
iscsi_get_error(iscsi));
ret = -EINVAL;
goto out;
}
iscsilun->iscsi = iscsi;
iscsilun->aio_context = bdrv_get_aio_context(bs);
iscsilun->lun = iscsi_url->lun;
iscsilun->has_write_same = true;
task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 0, 0,
(void **) &inq, errp);
if (task == NULL) {
ret = -EINVAL;
goto out;
}
iscsilun->type = inq->periperal_device_type;
scsi_free_scsi_task(task);
task = NULL;
if (iscsilun->type == TYPE_DISK && (flags & BDRV_O_RDWR) &&
iscsi_is_write_protected(iscsilun)) {
error_setg(errp, "Cannot open a write protected LUN as read-write");
ret = -EACCES;
goto out;
}
iscsi_readcapacity_sync(iscsilun, &local_err);
if (local_err != NULL) {
error_propagate(errp, local_err);
ret = -EINVAL;
goto out;
}
bs->total_sectors = sector_lun2qemu(iscsilun->num_blocks, iscsilun);
bs->request_alignment = iscsilun->block_size;
if (iscsilun->type != TYPE_DISK && iscsilun->type != TYPE_ROM) {
bs->sg = 1;
}
task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
SCSI_INQUIRY_PAGECODE_SUPPORTED_VPD_PAGES,
(void **) &inq_vpd, errp);
if (task == NULL) {
ret = -EINVAL;
goto out;
}
for (i = 0; i < inq_vpd->num_pages; i++) {
struct scsi_task *inq_task;
struct scsi_inquiry_logical_block_provisioning *inq_lbp;
struct scsi_inquiry_block_limits *inq_bl;
switch (inq_vpd->pages[i]) {
case SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING:
inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
SCSI_INQUIRY_PAGECODE_LOGICAL_BLOCK_PROVISIONING,
(void **) &inq_lbp, errp);
if (inq_task == NULL) {
ret = -EINVAL;
goto out;
}
memcpy(&iscsilun->lbp, inq_lbp,
sizeof(struct scsi_inquiry_logical_block_provisioning));
scsi_free_scsi_task(inq_task);
break;
case SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS:
inq_task = iscsi_do_inquiry(iscsilun->iscsi, iscsilun->lun, 1,
SCSI_INQUIRY_PAGECODE_BLOCK_LIMITS,
(void **) &inq_bl, errp);
if (inq_task == NULL) {
ret = -EINVAL;
goto out;
}
memcpy(&iscsilun->bl, inq_bl,
sizeof(struct scsi_inquiry_block_limits));
scsi_free_scsi_task(inq_task);
break;
default:
break;
}
}
scsi_free_scsi_task(task);
task = NULL;
iscsi_attach_aio_context(bs, iscsilun->aio_context);
if (iscsilun->bl.opt_unmap_gran * iscsilun->block_size >= 4 * 1024 &&
iscsilun->bl.opt_unmap_gran * iscsilun->block_size <= 16 * 1024 * 1024) {
iscsilun->cluster_sectors = (iscsilun->bl.opt_unmap_gran *
iscsilun->block_size) >> BDRV_SECTOR_BITS;
if (iscsilun->lbprz && !(bs->open_flags & BDRV_O_NOCACHE)) {
iscsilun->allocationmap = iscsi_allocationmap_init(iscsilun);
if (iscsilun->allocationmap == NULL) {
ret = -ENOMEM;
}
}
}
out:
qemu_opts_del(opts);
g_free(initiator_name);
if (iscsi_url != NULL) {
iscsi_destroy_url(iscsi_url);
}
if (task != NULL) {
scsi_free_scsi_task(task);
}
if (ret) {
if (iscsi != NULL) {
iscsi_destroy_context(iscsi);
}
memset(iscsilun, 0, sizeof(IscsiLun));
}
return ret;
}
| 1threat
|
Make value of another table become column and value : I have 2 table as bellow, i need select *topic_id* = 1.
If *website* = 1 and *store* = 1, *topic.title* must be "Title 1, web 1, store 1", this is *value* of *config_id* = 1, and *field*=title will become *topic.title*. How can i get this?
https://i.stack.imgur.com/KqgY3.png
https://i.stack.imgur.com/REOLi.png
| 0debug
|
static int xen_pt_bar_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
uint32_t *val, uint32_t dev_value,
uint32_t valid_mask)
{
XenPTRegInfo *reg = cfg_entry->reg;
XenPTRegion *base = NULL;
PCIDevice *d = &s->dev;
const PCIIORegion *r;
uint32_t writable_mask = 0;
uint32_t bar_emu_mask = 0;
uint32_t bar_ro_mask = 0;
uint32_t r_size = 0;
int index = 0;
index = xen_pt_bar_offset_to_index(reg->offset);
if (index < 0 || index >= PCI_NUM_REGIONS) {
XEN_PT_ERR(d, "Internal error: Invalid BAR index [%d].\n", index);
return -1;
}
r = &d->io_regions[index];
base = &s->bases[index];
r_size = xen_pt_get_emul_size(base->bar_flag, r->size);
switch (s->bases[index].bar_flag) {
case XEN_PT_BAR_FLAG_MEM:
bar_emu_mask = XEN_PT_BAR_MEM_EMU_MASK;
if (!r_size) {
bar_ro_mask = XEN_PT_BAR_ALLF;
} else {
bar_ro_mask = XEN_PT_BAR_MEM_RO_MASK | (r_size - 1);
}
break;
case XEN_PT_BAR_FLAG_IO:
bar_emu_mask = XEN_PT_BAR_IO_EMU_MASK;
bar_ro_mask = XEN_PT_BAR_IO_RO_MASK | (r_size - 1);
break;
case XEN_PT_BAR_FLAG_UPPER:
bar_emu_mask = XEN_PT_BAR_ALLF;
bar_ro_mask = r_size ? r_size - 1 : 0;
break;
default:
break;
}
writable_mask = bar_emu_mask & ~bar_ro_mask & valid_mask;
cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);
switch (s->bases[index].bar_flag) {
case XEN_PT_BAR_FLAG_UPPER:
case XEN_PT_BAR_FLAG_MEM:
break;
case XEN_PT_BAR_FLAG_IO:
break;
default:
break;
}
*val = XEN_PT_MERGE_VALUE(*val, dev_value, 0);
return 0;
}
| 1threat
|
How to build a multiple input graph with tensor flow? : <p>is it possible to define a TensorFlow graph with more than one input?
For instance, I want to give the graph two images and one text, each one is processed by a bunch of layers with a fc layer at the end. Then there is a node that computes a lossy function that takes into account the three representations. The aim is to let the three nets to backpropagate considering the joint representation lossy.
Is it possible? any example/tutorial about it?
thanks in advance!</p>
| 0debug
|
int ff_listen_bind(int fd, const struct sockaddr *addr,
socklen_t addrlen, int timeout, URLContext *h)
{
int ret;
int reuse = 1;
struct pollfd lp = { fd, POLLIN, 0 };
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))) {
av_log(NULL, AV_LOG_WARNING, "setsockopt(SO_REUSEADDR) failed\n");
}
ret = bind(fd, addr, addrlen);
if (ret)
return ff_neterrno();
ret = listen(fd, 1);
if (ret)
return ff_neterrno();
ret = ff_poll_interrupt(&lp, 1, timeout, &h->interrupt_callback);
if (ret < 0)
return ret;
ret = accept(fd, NULL, NULL);
if (ret < 0)
return ff_neterrno();
closesocket(fd);
ff_socket_nonblock(ret, 1);
return ret;
}
| 1threat
|
AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)
{
AVStream *st;
int i;
AVStream **streams;
if (s->nb_streams >= INT_MAX/sizeof(*streams))
streams = av_realloc_array(s->streams, s->nb_streams + 1, sizeof(*streams));
if (!streams)
s->streams = streams;
st = av_mallocz(sizeof(AVStream));
if (!st)
if (!(st->info = av_mallocz(sizeof(*st->info)))) {
st->info->last_dts = AV_NOPTS_VALUE;
st->codec = avcodec_alloc_context3(c);
if (s->iformat) {
st->codec->bit_rate = 0;
avpriv_set_pts_info(st, 33, 1, 90000);
st->index = s->nb_streams;
st->start_time = AV_NOPTS_VALUE;
st->duration = AV_NOPTS_VALUE;
st->cur_dts = s->iformat ? RELATIVE_TS_BASE : 0;
st->first_dts = AV_NOPTS_VALUE;
st->probe_packets = MAX_PROBE_PACKETS;
st->pts_wrap_reference = AV_NOPTS_VALUE;
st->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
st->last_IP_pts = AV_NOPTS_VALUE;
st->last_dts_for_order_check = AV_NOPTS_VALUE;
for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
st->pts_buffer[i] = AV_NOPTS_VALUE;
st->sample_aspect_ratio = (AVRational) { 0, 1 };
#if FF_API_R_FRAME_RATE
st->info->last_dts = AV_NOPTS_VALUE;
#endif
st->info->fps_first_dts = AV_NOPTS_VALUE;
st->info->fps_last_dts = AV_NOPTS_VALUE;
st->inject_global_side_data = s->internal->inject_global_side_data;
s->streams[s->nb_streams++] = st;
return st;
| 1threat
|
void *av_malloc(size_t size)
{
void *ptr = NULL;
#if CONFIG_MEMALIGN_HACK
long diff;
#endif
if(size > (INT_MAX-32) )
return NULL;
#if CONFIG_MEMALIGN_HACK
ptr = malloc(size+32);
if(!ptr)
return ptr;
diff= ((-(long)ptr - 1)&31) + 1;
ptr = (char*)ptr + diff;
((char*)ptr)[-1]= diff;
#elif HAVE_POSIX_MEMALIGN
if (posix_memalign(&ptr,32,size))
ptr = NULL;
#elif HAVE_MEMALIGN
ptr = memalign(32,size);
#else
ptr = malloc(size);
#endif
return ptr;
}
| 1threat
|
how current location android? : I've used setLocation(); inside this method but location is null
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try {
//location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
setLocation(location, post);
} else {
Toast.makeText(ViewAdActivity.this, getResources().getString(R.string.location_not_available), Toast.LENGTH_SHORT).show();
}
} catch (SecurityException e) {
}
}
| 0debug
|
static inline TCGv load_reg(DisasContext *s, int reg)
{
TCGv tmp = new_tmp();
load_reg_var(s, tmp, reg);
return tmp;
}
| 1threat
|
static int hds_write_packet(AVFormatContext *s, AVPacket *pkt)
{
HDSContext *c = s->priv_data;
AVStream *st = s->streams[pkt->stream_index];
OutputStream *os = &c->streams[s->streams[pkt->stream_index]->id];
int64_t end_dts = (os->fragment_index) * c->min_frag_duration;
int ret;
if (st->first_dts == AV_NOPTS_VALUE)
st->first_dts = pkt->dts;
if ((!os->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
av_compare_ts(pkt->dts - st->first_dts, st->time_base,
end_dts, AV_TIME_BASE_Q) >= 0 &&
pkt->flags & AV_PKT_FLAG_KEY && os->packets_written) {
if ((ret = hds_flush(s, os, 0, pkt->dts)) < 0)
return ret;
}
if (!os->packets_written)
os->frag_start_ts = pkt->dts;
os->last_ts = pkt->dts;
os->packets_written++;
return ff_write_chained(os->ctx, pkt->stream_index - os->first_stream, pkt, s);
}
| 1threat
|
static void load_linux(FWCfgState *fw_cfg,
const char *kernel_filename,
const char *initrd_filename,
const char *kernel_cmdline,
hwaddr max_ram_size)
{
uint16_t protocol;
int setup_size, kernel_size, initrd_size = 0, cmdline_size;
uint32_t initrd_max;
uint8_t header[8192], *setup, *kernel, *initrd_data;
hwaddr real_addr, prot_addr, cmdline_addr, initrd_addr = 0;
FILE *f;
char *vmode;
cmdline_size = (strlen(kernel_cmdline)+16) & ~15;
f = fopen(kernel_filename, "rb");
if (!f || !(kernel_size = get_file_size(f)) ||
fread(header, 1, MIN(ARRAY_SIZE(header), kernel_size), f) !=
MIN(ARRAY_SIZE(header), kernel_size)) {
fprintf(stderr, "qemu: could not load kernel '%s': %s\n",
kernel_filename, strerror(errno));
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 {
if (load_multiboot(fw_cfg, f, kernel_filename, initrd_filename,
kernel_cmdline, kernel_size, header)) {
return;
}
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 >= max_ram_size-ACPI_DATA_SIZE)
initrd_max = max_ram_size-ACPI_DATA_SIZE-1;
fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_ADDR, cmdline_addr);
fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, strlen(kernel_cmdline)+1);
fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, 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);
}
vmode = strstr(kernel_cmdline, "vga=");
if (vmode) {
unsigned int video_mode;
vmode += 4;
if (!strncmp(vmode, "normal", 6)) {
video_mode = 0xffff;
} else if (!strncmp(vmode, "ext", 3)) {
video_mode = 0xfffe;
} else if (!strncmp(vmode, "ask", 3)) {
video_mode = 0xfffd;
} else {
video_mode = strtol(vmode, NULL, 0);
}
stw_p(header+0x1fa, video_mode);
}
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);
}
initrd_size = get_image_size(initrd_filename);
if (initrd_size < 0) {
fprintf(stderr, "qemu: error reading initrd %s: %s\n",
initrd_filename, strerror(errno));
exit(1);
}
initrd_addr = (initrd_max-initrd_size) & ~4095;
initrd_data = g_malloc(initrd_size);
load_image(initrd_filename, initrd_data);
fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);
fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);
fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, initrd_data, initrd_size);
stl_p(header+0x218, initrd_addr);
stl_p(header+0x21c, initrd_size);
}
setup_size = header[0x1f1];
if (setup_size == 0) {
setup_size = 4;
}
setup_size = (setup_size+1)*512;
kernel_size -= setup_size;
setup = g_malloc(setup_size);
kernel = g_malloc(kernel_size);
fseek(f, 0, SEEK_SET);
if (fread(setup, 1, setup_size, f) != setup_size) {
fprintf(stderr, "fread() failed\n");
exit(1);
}
if (fread(kernel, 1, kernel_size, f) != kernel_size) {
fprintf(stderr, "fread() failed\n");
exit(1);
}
fclose(f);
memcpy(setup, header, MIN(sizeof(header), setup_size));
fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, prot_addr);
fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);
fw_cfg_add_bytes(fw_cfg, FW_CFG_KERNEL_DATA, kernel, kernel_size);
fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_ADDR, real_addr);
fw_cfg_add_i32(fw_cfg, FW_CFG_SETUP_SIZE, setup_size);
fw_cfg_add_bytes(fw_cfg, FW_CFG_SETUP_DATA, setup, setup_size);
option_rom[nb_option_roms].name = "linuxboot.bin";
option_rom[nb_option_roms].bootindex = 0;
nb_option_roms++;
}
| 1threat
|
static int spapr_phb_init(SysBusDevice *s)
{
sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(s);
PCIHostState *phb = PCI_HOST_BRIDGE(s);
char *namebuf;
int i;
PCIBus *bus;
sphb->dtbusname = g_strdup_printf("pci@%" PRIx64, sphb->buid);
namebuf = alloca(strlen(sphb->dtbusname) + 32);
sprintf(namebuf, "%s.mmio", sphb->dtbusname);
memory_region_init(&sphb->memspace, namebuf, INT64_MAX);
sprintf(namebuf, "%s.mmio-alias", sphb->dtbusname);
memory_region_init_alias(&sphb->memwindow, namebuf, &sphb->memspace,
SPAPR_PCI_MEM_WIN_BUS_OFFSET, sphb->mem_win_size);
memory_region_add_subregion(get_system_memory(), sphb->mem_win_addr,
&sphb->memwindow);
sprintf(namebuf, "%s.io", sphb->dtbusname);
memory_region_init(&sphb->iospace, namebuf, SPAPR_PCI_IO_WIN_SIZE);
memory_region_add_subregion(get_system_io(), 0, &sphb->iospace);
sprintf(namebuf, "%s.io-alias", sphb->dtbusname);
memory_region_init_io(&sphb->iowindow, &spapr_io_ops, sphb,
namebuf, SPAPR_PCI_IO_WIN_SIZE);
memory_region_add_subregion(get_system_memory(), sphb->io_win_addr,
&sphb->iowindow);
if (msi_supported) {
sprintf(namebuf, "%s.msi", sphb->dtbusname);
memory_region_init_io(&sphb->msiwindow, &spapr_msi_ops, sphb,
namebuf, SPAPR_MSIX_MAX_DEVS * 0x10000);
memory_region_add_subregion(get_system_memory(), sphb->msi_win_addr,
&sphb->msiwindow);
}
bus = pci_register_bus(DEVICE(s),
sphb->busname ? sphb->busname : sphb->dtbusname,
pci_spapr_set_irq, pci_spapr_map_irq, sphb,
&sphb->memspace, &sphb->iospace,
PCI_DEVFN(0, 0), PCI_NUM_PINS);
phb->bus = bus;
sphb->dma_liobn = SPAPR_PCI_BASE_LIOBN | (pci_find_domain(bus) << 16);
sphb->dma_window_start = 0;
sphb->dma_window_size = 0x40000000;
sphb->dma = spapr_tce_new_dma_context(sphb->dma_liobn, sphb->dma_window_size);
pci_setup_iommu(bus, spapr_pci_dma_context_fn, sphb);
QLIST_INSERT_HEAD(&spapr->phbs, sphb, list);
for (i = 0; i < PCI_NUM_PINS; i++) {
uint32_t irq;
irq = spapr_allocate_lsi(0);
if (!irq) {
return -1;
}
sphb->lsi_table[i].irq = irq;
}
return 0;
}
| 1threat
|
How to get the initialisation value for a Java Class reference : <p>I have a <code>Class<?></code> reference for an arbitrary type. How to get that type's initialisation value? Is there some library method for this or do I have to roll my own, such as:</p>
<pre><code>Class<?> klass = ...
Object init =
(klass == boolean.class)
? false
: (klass == byte.class)
? (byte) 0
...
: (Object) null;
</code></pre>
<p>The use case is I have an arbitrary <code>java.lang.reflect.Method</code> reference, which I want to call using arbitrary parameters (for some testing), which may not be <code>null</code> in case the parameter is a primitive type, so I need to specify some value of that type.</p>
| 0debug
|
MySQL JSON_EXTRACT path expression error : <p>The syntax looks right to me, any help would be appreciated!</p>
<pre><code>mysql> select fieldnames from tablename limit 5;
+--------------------------------------------------------+
| fieldnames |
+--------------------------------------------------------+
| {"example-field-1": "val2"} |
| {"example-field-2": "val1"} |
| {"example-field-1": "val1", "example-field-3": "val1"} |
| {"example-field-2": "val1"} |
| {"example-field-2": "val2"} |
+--------------------------------------------------------+
mysql> select JSON_EXTRACT(fieldnames, '$.example-field-1') from tablename;
ERROR 3143 (42000): Invalid JSON path expression. The error is around character position 17 in '$.example-field-1'.
</code></pre>
<p>MySQL 5.7.10</p>
| 0debug
|
def check_greater(test_tup1, test_tup2):
res = all(x < y for x, y in zip(test_tup1, test_tup2))
return (res)
| 0debug
|
Does calling View Model methods in Code Behind events break the MVVM? : <p>I wonder if that would break the MVVM pattern and, if so, why and why is it so bad?</p>
<p><strong>WPF:</strong></p>
<pre><code><Button Click="Button_Click" />
</code></pre>
<p><strong>Code Behind:</strong></p>
<pre><code>private void Button_Click(object sender, RoutedEventArgs e)
{
ViewModel.CallMethod();
}
</code></pre>
<p><strong>View Model:</strong></p>
<pre><code>public void CallMethod()
{
// Some code
}
</code></pre>
<p>IMHO, it keeps the code behind quite simple, the view model is still agnostic about the view and code behind and a change to the view doesn't affect the business logic.</p>
<p>It seems to me more simple and clear than <code>Commands</code> or <code>CallMethodAction</code>.</p>
<p>I don't want the kind of answer "it is not how it should be done". I need a proper and logical reason of why doing so could lead to maintenance or comprehension problems.</p>
| 0debug
|
find elements from an array such that no two are adjacent and whose sum is maximum : <p>Find a sequence containing elements of given array such that no two elements are adjacent and we are required to maximise the sum of the sequence formed.</p>
<p>input :- { 4 , 1 , 3 , 4 }</p>
<p>output :- 4 4</p>
| 0debug
|
When making a set out of sorted list, the output set is not sorted : <p>Could anyone please explain to me why making a set out of a sorted list results in a set which is NOT sorted? </p>
<p><strong>list.sort()</strong> should sort the list in place, as it does.
<strong>set(list)</strong> should return unique values of the list, as it does. </p>
<p>But why is the resulting set not sorted? Do I need to make a set, turn it back into list2 and then sort list2? </p>
<p>(Using Python 2.7.6)</p>
<p><strong>Code:</strong></p>
<pre><code>def longest(s1, s2):
list = []
s = s1 + s2
for letter in s:
list.append(letter)
print list
list.sort()
print list
unique = set(list)
print unique
s4 = ""
for item in unique:
s4 = s4 + item
print s4
return s4
</code></pre>
<p><strong>Console output:</strong></p>
<pre><code>['a', 'r', 'e', 't', 'h', 'e', 'y', 'h', 'e', 'r', 'e', 'y', 'e', 's', 't', 'h', 'e', 'y', 'a', 'r', 'e', 'h', 'e', 'r', 'e']
['a', 'a', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'h', 'h', 'h', 'h', 'r', 'r', 'r', 'r', 's', 't', 't', 'y', 'y', 'y']
set(['a', 'e', 'h', 's', 'r', 't', 'y'])
aehsrty
</code></pre>
| 0debug
|
static uint32_t omap_l4_io_readw(void *opaque, target_phys_addr_t addr)
{
unsigned int i = (addr - OMAP2_L4_BASE) >> TARGET_PAGE_BITS;
return omap_l4_io_readw_fn[i](omap_l4_io_opaque[i], addr);
}
| 1threat
|
static av_cold int wmv2_decode_init(AVCodecContext *avctx)
{
Wmv2Context *const w = avctx->priv_data;
int ret;
if ((ret = ff_msmpeg4_decode_init(avctx)) < 0)
return ret;
ff_wmv2_common_init(w);
return ff_intrax8_common_init(&w->x8, &w->s.idsp, &w->s);
}
| 1threat
|
static void tcg_out_tb_finalize(TCGContext *s)
{
static const void * const helpers[8] = {
helper_ret_stb_mmu,
helper_le_stw_mmu,
helper_le_stl_mmu,
helper_le_stq_mmu,
helper_ret_ldub_mmu,
helper_le_lduw_mmu,
helper_le_ldul_mmu,
helper_le_ldq_mmu,
};
tcg_insn_unit *thunks[8] = { };
TCGLabelQemuLdst *l;
for (l = s->be->labels; l != NULL; l = l->next) {
long x = l->is_ld * 4 + l->size;
tcg_insn_unit *dest = thunks[x];
if (dest == NULL) {
uintptr_t *desc = (uintptr_t *)helpers[x];
uintptr_t func = desc[0], gp = desc[1], disp;
thunks[x] = dest = s->code_ptr;
tcg_out_bundle(s, mlx,
INSN_NOP_M,
tcg_opc_l2 (gp),
tcg_opc_x2 (TCG_REG_P0, OPC_MOVL_X2,
TCG_REG_R1, gp));
tcg_out_bundle(s, mii,
INSN_NOP_M,
INSN_NOP_I,
tcg_opc_i22(TCG_REG_P0, OPC_MOV_I22,
l->is_ld ? TCG_REG_R35 : TCG_REG_R36,
TCG_REG_B0));
disp = (tcg_insn_unit *)func - s->code_ptr;
tcg_out_bundle(s, mLX,
INSN_NOP_M,
tcg_opc_l3 (disp),
tcg_opc_x3 (TCG_REG_P0, OPC_BRL_SPTK_MANY_X3, disp));
}
reloc_pcrel21b_slot2(l->label_ptr, dest);
}
}
| 1threat
|
Regex: Match upto at the end of a string only one optional word character if found : I want to match an optional "s" if present at the end of the string. Other than "s", it cannot have any "word" character. Digits, Symbols are fine.
**Note:** It could be a two or three word search as well, for example "he_mans" or "he mans" while "he manity" or "he manned" etc are wrong. What I care about is how it **ends**
**True examples**
// This two examples below must return true
"fsl_mdl" matches ".*" + "mdl" + "[^a-rt-z][s]?.*" // returns false
"eco_mdl_pipe" matches ".*" + "mdl" + "[^a-rt-z][s]?.*" // returns false"
**False examples**
// The example must return false
"fonneded" matches ".*" + "fonned" + "[^a-rt-z][s]?.*"
| 0debug
|
static int nbd_establish_connection(BlockDriverState *bs)
{
BDRVNBDState *s = bs->opaque;
int sock;
int ret;
off_t size;
size_t blocksize;
if (s->host_spec[0] == '/') {
sock = unix_socket_outgoing(s->host_spec);
} else {
sock = tcp_socket_outgoing_spec(s->host_spec);
}
if (sock < 0) {
logout("Failed to establish connection to NBD server\n");
return -errno;
}
ret = nbd_receive_negotiate(sock, s->export_name, &s->nbdflags, &size,
&blocksize);
if (ret < 0) {
logout("Failed to negotiate with the NBD server\n");
closesocket(sock);
return ret;
}
socket_set_nonblock(sock);
qemu_aio_set_fd_handler(s->sock, nbd_reply_ready, NULL,
nbd_have_request, s);
s->sock = sock;
s->size = size;
s->blocksize = blocksize;
logout("Established connection with NBD server\n");
return 0;
}
| 1threat
|
How to assign a nested property of an object given an array of keys : <p>I have an object that resembles this:</p>
<pre><code>const obj = {
prop1: {
prop2: {
value: 'something',
...otherProps
}
},
...otherProps
}
</code></pre>
<p>And an array that looks like this:</p>
<pre><code>const history = ['prop1', 'prop2', 'value']
</code></pre>
<p>How do I assign the property <code>value</code> of <code>prop2</code> a new value in a way that would also work for any other depth. </p>
| 0debug
|
Python: Selection of Face of a STL by Face Normal values : I want to write a script in Python which can generate facegroups in a STL as per the Face Normal value condition. For example, Provided is the snap of Stl, Different colour signifies the face group containing the triangular faces satisfying my given face normal threshold. Is there any simple way to do this in python?
[Face Group STL][1]
[1]: https://i.stack.imgur.com/rRpWA.jpg
| 0debug
|
Is there a constant for max/min int/double value in dart? : <p>Is there a constant in dart that tells us what is the max/min int/double value ?</p>
<p>Something like <code>double.infinity</code> but instead <code>double.maxValue</code> ?</p>
| 0debug
|
static void default_qemu_fd_register(int fd)
{
}
| 1threat
|
Why does JavaScript have the Math object? : <p>In many languages, to find cosine, you use <code>cos(x)</code>. But in JavaScript, you must use <code>Math.cos(x)</code>. Why doesn't JavaScript spare us the 5 characters in <code>Math.</code>, both making it easier to type and easier to read?</p>
<p>I have tried to Google this multiple times, and found no answers. Is there any practical reason for this that I have not yet found?</p>
<p>So far, there are three reasons I can think of:</p>
<ol>
<li><p>The creators of JavaScript want to ensure that the math functions do not coincide with other functions users create (Like a function called 'cos()` that calculates, say, cosecant)</p></li>
<li><p>The creators of JavaScript thought that <code>Math</code> would make the code more readable</p></li>
<li><p>The creators of JavaScript perhaps didn't want any functions that have <code>window</code> as a parent (Though <code>alert</code> and <code>prompt</code> make this unlikely)</p></li>
</ol>
| 0debug
|
static void GCC_FMT_ATTR(2, 3) blkverify_err(BlkverifyAIOCB *acb,
const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "blkverify: %s sector_num=%" PRId64 " nb_sectors=%d ",
acb->is_write ? "write" : "read", acb->sector_num,
acb->nb_sectors);
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
exit(1);
}
| 1threat
|
How does the performance relate to the voltage in digital electronics? : <p>I am studying some techniques to reduce power in digital circuits, and one way was to reduce the applied voltage but the trade off is the delay of the circuit will increase, I would appreciate if someone could explain how the delay is related to the voltage applied.</p>
| 0debug
|
static NetSocketState *net_socket_fd_init_dgram(NetClientState *peer,
const char *model,
const char *name,
int fd, int is_connected,
const char *mcast,
Error **errp)
{
struct sockaddr_in saddr;
int newfd;
NetClientState *nc;
NetSocketState *s;
if (is_connected && mcast != NULL) {
if (parse_host_port(&saddr, mcast, errp) < 0) {
goto err;
}
if (saddr.sin_addr.s_addr == 0) {
error_setg(errp, "can't setup multicast destination address");
goto err;
}
newfd = net_socket_mcast_create(&saddr, NULL, errp);
if (newfd < 0) {
goto err;
}
dup2(newfd, fd);
close(newfd);
}
nc = qemu_new_net_client(&net_dgram_socket_info, peer, model, name);
s = DO_UPCAST(NetSocketState, nc, nc);
s->fd = fd;
s->listen_fd = -1;
s->send_fn = net_socket_send_dgram;
net_socket_rs_init(&s->rs, net_socket_rs_finalize, false);
net_socket_read_poll(s, true);
if (is_connected) {
s->dgram_dst = saddr;
snprintf(nc->info_str, sizeof(nc->info_str),
"socket: fd=%d (cloned mcast=%s:%d)",
fd, inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
} else {
snprintf(nc->info_str, sizeof(nc->info_str),
"socket: fd=%d", fd);
}
return s;
err:
closesocket(fd);
return NULL;
}
| 1threat
|
How do i implement the algorithm below : Get a list of numbers L1, L2, L3....LN as argument
Assume L1 is the largest, Largest = L1
Take next number Li from the list and do the following
If Largest is less than Li
Largest = Li
If Li is last number from the list then
return Largest and come out
Else repeat same process starting from step 3
Create a function prime_number that does the following
Takes as parameter an integer and
Returns boolean value true if the value is prime or
Returns boolean value false if the value is not prime
So far my code is :
def get_algorithm_result(num_list):
largest =num_list[0]
for item in range(0,len(num_list)):
if largest < num_list[item]:
largest = num_list[item]
return largest
def prime_number(integer):
if integer%2==0:
return False
else:
return True
After executing the code i get
"Test Spec Failed
Your solution failed to pass all the tests"
where I'm i going wrong because i believe my code is correct
| 0debug
|
static void ide_atapi_cmd_read_pio(IDEState *s, int lba, int nb_sectors,
int sector_size)
{
s->lba = lba;
s->packet_transfer_size = nb_sectors * sector_size;
s->elementary_transfer_size = 0;
s->io_buffer_index = sector_size;
s->cd_sector_size = sector_size;
s->status = READY_STAT | SEEK_STAT;
ide_atapi_cmd_reply_end(s);
}
| 1threat
|
Order of operations not correct? (C++) : <p>I was writing a small Least common multiple algorithm and encountered something I don't understand. This is the first and last part of the code:</p>
<pre><code>long a = 14159572;
long b = 63967072;
int rest = 4;
long long ans;
.
. // Some other code here that is not very interesting.
.
else
{
//This appears correct, prints out correct answer.
ans = b/rest;
std::cout << a*ans;
}
</code></pre>
<p>But if I change the last "else" to this it gives an answer that is much smaller and incorrect:</p>
<pre><code> else
{
std::cout << a*(b/rest);
}
</code></pre>
<p>Anyone know why this is? I don't think it's an overflow since it was no negative number that came out wrong, but rather just a much smaller integer (around 6*10^8) than the actual answer (around 2.2*10^14). As far as I understand it should calculate "b/rest" first in both cases, so the answers shouldn't differ?</p>
| 0debug
|
Javascript: How to give String to onclick function : I want to give a String Parameter to a function
function test(p)
{
}
...innerHTML = '<div onclick="test(p)"><div>';
That does not work how to do it?
| 0debug
|
static void pmac_ide_flush(DBDMA_io *io)
{
MACIOIDEState *m = io->opaque;
if (m->aiocb) {
bdrv_drain_all();
}
}
| 1threat
|
Java recursion executing after return statement : <p>I would like to know why my recursive method executes even after it has executed the <code>return</code> statement. I am trying to write a simple program to calculate the factorial of the input, but the factorial of "4" returns "48" because it multiplies the "2" twice. Please find my code below.</p>
<pre><code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int soln=0;
static boolean start = true;
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
int n=sn.nextInt();
System.out.println(multx(n));
}
public static int multx(int n){
if (start){
soln = n;
start = false;
}
while(n>2)
{
n--;
soln = soln*n;
multx(n);
}
return soln;
}
}
</code></pre>
<p>Why does it execute <code>return soln</code> and then go back to <code>multx(n)</code>?</p>
| 0debug
|
Why is this total number doesn't equal to 1000? : I have the only problem that when I run it, the totally number does not equal to 1000. I have no idea where is wrong.
It shows like this: In 1000 tosses of a dice, there were 180 for 1 and 136 for 2 and 121 for 3 and 97 for 4 and 72 for 5 and 60 for 6.
I am trying to be specific, if there is anything I am not clear about, please let me know. And thanks everyone:)
#this is a program that simulate how many times that there will be for every sides of a dice, when I trying to throw it 1,000 times.
from random import randrange
def toss():
if randrange(6) == 0:
return "1"
elif randrange(6) ==1:
return "2"
elif randrange(6) ==2:
return "3"
elif randrange(6) ==3:
return "4"
elif randrange(6) ==4:
return "5"
elif randrange(6) ==5:
return "6"
def roll_dice(n):
count1 = 0
count2 = 0
count3 = 0
count4 = 0
count5 = 0
count6 = 0
for i in range(n):
dice = toss()
if dice == "1":
count1 = count1 + 1
if dice == "2":
count2 = count2 + 1
if dice == "3":
count3 = count3 + 1
if dice =="4":
count4 = count4 + 1
if dice == "5":
count5 = count5 + 1
if dice == "6":
count6 = count6 + 1
print ("In", n, "tosses of a dice, there were", count1, "for 1 and",
count2, "for 2 and", count3, "for 3 and", count4, "for 4 and", count5, "for
5 and",count6, "for 6.")
roll_dice(1000)
| 0debug
|
static int decode_init(AVCodecContext * avctx)
{
MPADecodeContext *s = avctx->priv_data;
static int init=0;
int i, j, k;
#if defined(USE_HIGHPRECISION) && defined(CONFIG_AUDIO_NONSHORT)
avctx->sample_fmt= SAMPLE_FMT_S32;
#else
avctx->sample_fmt= SAMPLE_FMT_S16;
#endif
if(avctx->antialias_algo != FF_AA_FLOAT)
s->compute_antialias= compute_antialias_integer;
else
s->compute_antialias= compute_antialias_float;
if (!init && !avctx->parse_only) {
for(i=0;i<64;i++) {
int shift, mod;
shift = (i / 3);
mod = i % 3;
scale_factor_modshift[i] = mod | (shift << 2);
}
for(i=0;i<15;i++) {
int n, norm;
n = i + 2;
norm = ((int64_t_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
scale_factor_mult[i][0] = MULL(FIXR(1.0 * 2.0), norm);
scale_factor_mult[i][1] = MULL(FIXR(0.7937005259 * 2.0), norm);
scale_factor_mult[i][2] = MULL(FIXR(0.6299605249 * 2.0), norm);
dprintf("%d: norm=%x s=%x %x %x\n",
i, norm,
scale_factor_mult[i][0],
scale_factor_mult[i][1],
scale_factor_mult[i][2]);
}
ff_mpa_synth_init(window);
for(i=1;i<16;i++) {
const HuffTable *h = &mpa_huff_tables[i];
int xsize, x, y;
unsigned int n;
uint8_t tmp_bits [256];
uint16_t tmp_codes[256];
memset(tmp_bits , 0, sizeof(tmp_bits ));
memset(tmp_codes, 0, sizeof(tmp_codes));
xsize = h->xsize;
n = xsize * xsize;
j = 0;
for(x=0;x<xsize;x++) {
for(y=0;y<xsize;y++){
tmp_bits [(x << 4) | y]= h->bits [j ];
tmp_codes[(x << 4) | y]= h->codes[j++];
}
}
init_vlc(&huff_vlc[i], 7, 256,
tmp_bits, 1, 1, tmp_codes, 2, 2, 1);
}
for(i=0;i<2;i++) {
init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1, 1);
}
for(i=0;i<9;i++) {
k = 0;
for(j=0;j<22;j++) {
band_index_long[i][j] = k;
k += band_size_long[i][j];
}
band_index_long[i][22] = k;
}
table_4_3_exp= av_mallocz_static(TABLE_4_3_SIZE * sizeof(table_4_3_exp[0]));
if(!table_4_3_exp)
return -1;
table_4_3_value= av_mallocz_static(TABLE_4_3_SIZE * sizeof(table_4_3_value[0]));
if(!table_4_3_value)
return -1;
int_pow_init();
for(i=1;i<TABLE_4_3_SIZE;i++) {
double f, fm;
int e, m;
f = pow((double)(i/4), 4.0 / 3.0) * pow(2, (i&3)*0.25);
fm = frexp(f, &e);
m = (uint32_t)(fm*(1LL<<31) + 0.5);
e+= FRAC_BITS - 31 + 5;
table_4_3_value[i] = m;
table_4_3_exp[i] = -e;
}
for(i=0; i<512*16; i++){
int exponent= (i>>4)-400;
double f= pow(i&15, 4.0 / 3.0) * pow(2, exponent*0.25 + FRAC_BITS + 5);
expval_table[exponent+400][i&15]= lrintf(f);
if((i&15)==1)
exp_table[exponent+400]= lrintf(f);
}
for(i=0;i<7;i++) {
float f;
int v;
if (i != 6) {
f = tan((double)i * M_PI / 12.0);
v = FIXR(f / (1.0 + f));
} else {
v = FIXR(1.0);
}
is_table[0][i] = v;
is_table[1][6 - i] = v;
}
for(i=7;i<16;i++)
is_table[0][i] = is_table[1][i] = 0.0;
for(i=0;i<16;i++) {
double f;
int e, k;
for(j=0;j<2;j++) {
e = -(j + 1) * ((i + 1) >> 1);
f = pow(2.0, e / 4.0);
k = i & 1;
is_table_lsf[j][k ^ 1][i] = FIXR(f);
is_table_lsf[j][k][i] = FIXR(1.0);
dprintf("is_table_lsf %d %d: %x %x\n",
i, j, is_table_lsf[j][0][i], is_table_lsf[j][1][i]);
}
}
for(i=0;i<8;i++) {
float ci, cs, ca;
ci = ci_table[i];
cs = 1.0 / sqrt(1.0 + ci * ci);
ca = cs * ci;
csa_table[i][0] = FIXHR(cs/4);
csa_table[i][1] = FIXHR(ca/4);
csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
csa_table_float[i][0] = cs;
csa_table_float[i][1] = ca;
csa_table_float[i][2] = ca + cs;
csa_table_float[i][3] = ca - cs;
}
for(i=0;i<36;i++) {
for(j=0; j<4; j++){
double d;
if(j==2 && i%3 != 1)
continue;
d= sin(M_PI * (i + 0.5) / 36.0);
if(j==1){
if (i>=30) d= 0;
else if(i>=24) d= sin(M_PI * (i - 18 + 0.5) / 12.0);
else if(i>=18) d= 1;
}else if(j==3){
if (i< 6) d= 0;
else if(i< 12) d= sin(M_PI * (i - 6 + 0.5) / 12.0);
else if(i< 18) d= 1;
}
d*= 0.5 / cos(M_PI*(2*i + 19)/72);
if(j==2)
mdct_win[j][i/3] = FIXHR((d / (1<<5)));
else
mdct_win[j][i ] = FIXHR((d / (1<<5)));
}
}
for(j=0;j<4;j++) {
for(i=0;i<36;i+=2) {
mdct_win[j + 4][i] = mdct_win[j][i];
mdct_win[j + 4][i + 1] = -mdct_win[j][i + 1];
}
}
#if defined(DEBUG)
for(j=0;j<8;j++) {
av_log(avctx, AV_LOG_DEBUG, "win%d=\n", j);
for(i=0;i<36;i++)
av_log(avctx, AV_LOG_DEBUG, "%f, ", (double)mdct_win[j][i] / FRAC_ONE);
av_log(avctx, AV_LOG_DEBUG, "\n");
}
#endif
init = 1;
}
s->inbuf_index = 0;
s->inbuf = &s->inbuf1[s->inbuf_index][BACKSTEP_SIZE];
s->inbuf_ptr = s->inbuf;
#ifdef DEBUG
s->frame_count = 0;
#endif
if (avctx->codec_id == CODEC_ID_MP3ADU)
s->adu_mode = 1;
return 0;
}
| 1threat
|
static void vnc_init_timer(VncDisplay *vd)
{
vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
if (vd->timer == NULL && !QTAILQ_EMPTY(&vd->clients)) {
vd->timer = qemu_new_timer(rt_clock, vnc_refresh, vd);
vnc_dpy_resize(vd->ds);
vnc_refresh(vd);
}
}
| 1threat
|
have_autoneg(E1000State *s)
{
return (s->compat_flags & E1000_FLAG_AUTONEG) &&
(s->phy_reg[PHY_CTRL] & MII_CR_AUTO_NEG_EN);
}
| 1threat
|
Unit testing ag-grid in Angular 2 : <p>Has someone worked on unit testing ag-grid components in Angular 2?</p>
<p>For me, this.gridOptions.api remains undefined when the test cases run.</p>
| 0debug
|
i am getting this error in this code. "System.FormatException: 'Input string was not in a correct format.'" : string[] rounds = cols[5].Split('|');
foreach (string round in rounds)
{
//splitting each round on "^"
string[] msText = round.Split('^');
//create a new list in text file
List<MatchupModel> ms = new List<MatchupModel>();
foreach (string matchupModelTextId in msText)
{
this is the line on which i am getting "error.System.FormatException: 'Input string was not in a correct format.'
ms.Add(matchups.Where(x => x.Id == int.Parse(matchupModelTextId)).First());
}
tm.Rounds.Add(ms);
}
| 0debug
|
Checking the value of a key in an hasmap : I would like to know how to check the value of a specific key in an hashmap, for example,
if the hashmap "map" contains the key "Key" then what is the value of the key "Key"?
| 0debug
|
db.execute('SELECT * FROM employees WHERE id = ' + user_input)
| 1threat
|
static void pxb_register_bus(PCIDevice *dev, PCIBus *pxb_bus, Error **errp)
{
PCIBus *bus = dev->bus;
int pxb_bus_num = pci_bus_num(pxb_bus);
if (bus->parent_dev) {
error_setg(errp, "PXB devices can be attached only to root bus");
return;
}
QLIST_FOREACH(bus, &bus->child, sibling) {
if (pci_bus_num(bus) == pxb_bus_num) {
error_setg(errp, "Bus %d is already in use", pxb_bus_num);
return;
}
}
QLIST_INSERT_HEAD(&dev->bus->child, pxb_bus, sibling);
}
| 1threat
|
Equivalent Kotlin code to my F# functional code : <p>Can any one help me converting my below <code>F#</code> code into <code>Kotlin</code>:</p>
<pre><code>//namespace SysIO
open System.Collections.Generic // for Dictionary
printf "Hi, Let's start \n"
let series = [|30;21;29;31;40;48;53;47;37;39;31;29;17;9;20;24;27;35;41;38;
27;31;27;26;21;13;21;18;33;35;40;36;22;24;21;20;17;14;17;19;
26;29;40;31;20;24;18;26;17;9;17;21;28;32;46;33;23;28;22;27;
18;8;17;21;31;34;44;38;31;30;26;32|]
let initialSeasonalComponents (series : int []) slen : IDictionary<int, double> =
let nSeasons = float (series.Length / slen)
let grouped =
series
|> Array.map float
|> Array.chunkBySize slen
let seasonAverages = grouped |> Array.map Array.average
Array.init slen (fun i -> i, (Array.zip grouped seasonAverages
|> Array.fold (fun s (els, av) -> els.[i] + s - av) 0.)
/ nSeasons) |> dict
printfn "Seasons Averageß: \n %A" (initialSeasonalComponents series 12)
let initialTrend (series : int []) (slen : int) : double =
series |> Array.windowed slen
|> Array.fold (fun s x ->
(x |> Array.rev |> Array.head) - (x |> Array.head) + s) 0
|> float
|> fun x -> x / (float slen)
printfn "Initial Trend: \n %A" (initialTrend series 12)
let tripleExponentialSmoothing series slen alpha beta gamma nPreds =
let mutable smooth = 0.
let mutable trend = 0.
let seasonals = initialSeasonalComponents series 12 |> Dictionary
seq {
for i in 0..(series.Length+nPreds-1) do
match i with
| 0 -> // initial values
smooth <- series |> Array.head |> float
trend <- initialTrend series slen
yield series |> Array.head |> float
| i when i >= series.Length -> // we are forecasting
let m = i - series.Length + 1
yield (smooth + float m * trend) + seasonals.[i%slen]
| _ ->
let v = series |> Array.head |> float
let lastSmooth = smooth
smooth <- alpha*(v-seasonals.Item(i%slen)) + (1.-alpha)*(smooth+trend)
trend <- beta * (smooth-lastSmooth) + (1.-beta)*trend
seasonals.[i%slen] <- gamma*(v-smooth) + (1.-gamma)*seasonals.[i%slen]
yield smooth + trend + seasonals.Item(i%slen) }
// result
let f = tripleExponentialSmoothing series 12 0.716 0.029 0.993 24
printfn "Forecast: \n %A" f
</code></pre>
| 0debug
|
Print floowing out in single row in java : <p>How to print the following output with only one for-loop in java?</p>
<pre><code>1, 5, 9, 13, 17, 21, 25, 29.....till < 1000
</code></pre>
| 0debug
|
LINUX C PROGRAM - reading current directory, printing results based on file type (directory, executable program, ordinary file) : I am having a bit of trouble creating a C program that reads the current directory, prints the file path, and contents.
For each file found in the directory the contents should be printed based on whether they are a directory, a file, or executable.
I have the main components working just unsure how to sort the files output after using the opendir() / closedir() command
eg. end output:
/home/documents/folder1
File: help.txt
File: me.txt
Executable: plz
File: thankyou.c
| 0debug
|
loop for multiple database and user creation in sql, need to assign the user to the database. anyone please help me with that code :
> ***after creating login using windows authentication ,
need to assign user to the database
and provide permissions to that user.
Could anyone please help me with that.
Thanks in advance.***
-- BULK INSERT tempNames.dbo.tempNames
-- FROM 'C:\Users\Videos\file.txt'
-- WITH
-- (
-- ROWTERMINATOR ='\n'--
-- )
USE [master]
GO
DECLARE @NameCursor as CURSOR;
DECLARE @NAME AS NVARCHAR(50);
DECLARE @NAME2 AS NVARCHAR(50);
DECLARE @NIUNT AS NVARCHAR(50);
SET @NIUNT ='niunt';
SET @NameCursor = CURSOR FOR
SELECT id
FROM test.dbo.Sheet1$
OPEN @NameCursor;
FETCH NEXT FROM @NameCursor INTO @Name;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @Name
## Creating database using @name ##
set @name2 ='create database '+@Name + ';'
exec (@name2)
BEGIN
SET NOCOUNT ON
DECLARE @SQL NVARCHAR(4000);
## Creating login using @name ##
SET @SQL = 'CREATE LOGIN [' +@NIUNT +'\'+ @NAME + '] from windows';
exec(@SQL);
-END;
FETCH NEXT FROM @NameCursor INTO @Name;
END
GO
| 0debug
|
Measurable indicator for usability : <p>I am starting a new project and I have the problem with the measurability of the requirement usability.</p>
<p>With is an good atomic measurable indicator for usability?</p>
| 0debug
|
Calling Javascript variable inside javascript code : <p>I have the following code </p>
<pre><code>dt.ajax.url( 'test.php?status=' ).load();
</code></pre>
<p>I defined a variable </p>
<pre><code>var status= 55
</code></pre>
<p>I wand to add <code>status_2</code> in the link like this </p>
<pre><code>dt.ajax.url( 'test.php?status=&status' ).load();
</code></pre>
<p>How can I do it ? </p>
| 0debug
|
Remove blank linesin powershell output : When I run any command like:
Get-Host | Select Name, Version | Format-List
It returns the output with lots of blank lines.
tried to add -ExpandProperty to my code so it looks like:
Get-Host | Select -ExpandProperty Name, Version | Format-List
but it still leaves me with one blank line at the end of the output. any way to remove also the last blank line?
| 0debug
|
Issues Getting My Spring Boot Index Page and Controller Mappings To Work when Returning JSP View Name : I am using Spring Boot and JSP to learn some quick tutorials in Spring Security but my **controller mappings** and `index.jsp` are not working. It seems it can't locate the `JSP` pages. Here is my config and project structure::::
springsecurity-for-reactive-apps [boot] - Project folder
- src/main/java
- com.springsecurity
- SpringsecurityForReactiveAppsApplication.java
- com.springsecurity.config
- ApplicationConfig.java
- SecurityWebApplicationInitializer.java
- SpringMvcWebApplicationInitializer.java
- SpringSecurityConfig.java
- WebApplicationConfig.java
- src
- main
- webapp
- WEB-INF
- view
- home.jsp
- index.jsp
- **com.springsecurity** package contains ::
@SpringBootApplication
public class SpringsecurityForReactiveAppsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringsecurityForReactiveAppsApplication.class, args);
}
}
**- com.springsecurity.config** package contains the following classes
@Configuration
public class ApplicationConfig {
@Value("${spring.datasource.driver-class-name}")
private String DB_DRIVER;
@Value("${spring.datasource.password}")
private String DB_PASSWORD;
@Value("${spring.datasource.url}")
private String DB_URL;
@Value("${spring.datasource.username}")
private String DB_USERNAME;
@Autowired
private Environment env;
@Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}
}
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{
}
public class SpringMvcWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { WebApplicationConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
@Configuration
@EnableWebSecurity
//@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class })
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private DataSource dataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username, password, enabled"
+ " from users where username = ?")
.authoritiesByUsernameQuery("select username, authority "
+ "from authorities where username = ?")
.passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().hasAnyRole("ADMIN", "USER")
.and()
.httpBasic(); // Use Basic authentication
}
}
@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {"com.springsecurity"})
public class WebApplicationConfig implements WebMvcConfigurer{
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp().prefix("/WEB-INF/view/").suffix(".jsp");
}
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
**- com.springsecurity.controller** contains:::
@Controller
public class HomeController {
@GetMapping("/home")
public String home(Model model, Principal principal) {
System.out.println("___________home()___________________");
return "home";
}
@GetMapping("/error")
public String error(Model model, Principal principal) {
System.out.println("___________ERROR-<<error___________________");
return "home";
}
}
**POM.xml**
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springsecurity</groupId>
<artifactId>springsecurity-for-reactive-apps</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springsecurity-for-reactive-apps</name>
<description>Spring security for reactive applications</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring dependencies START-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<!-- Servlet and JSP related dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- For datasource configuration -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
</dependency>
<!-- We will be using MySQL as our database server -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- Spring dependencies END -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I have spent almost two days googling but couldn't find answer.
Any help will be appreciated
thanks
| 0debug
|
How to use Cake.net with Gitlab CI? : <p>I have an ASP.NET MVC application. I am trying to implement CI and CD using Gitlab and Cake.net.</p>
<p>In order to test more easily, I installed Gitlab CI multi runner on my machine. I registered it with 'shell' as executor.</p>
<p>I am trying to execute the Cake.net build.ps1 file from .gitlab-ci.yml, but it doesn't execute the script. When it reaches the build.ps1 line it only opens the file with notepad and then it says Build succeeded.</p>
<p><strong>What am I missing? Why isn't the script executed?</strong></p>
<p>Here is the code:</p>
<p><strong>.gitlab-ci.yml</strong></p>
<pre><code>stages:
- build
build:
stage: build
script:
- build.ps1
only:
- develop
</code></pre>
<p><strong>Gitlab CI multi runner config.toml</strong></p>
<pre><code>concurrent = 1
check_interval = 0
[[runners]]
name = "Development runner"
url = "https://gitlab.com/ci"
token = "***"
executor = "shell"
shell = "powershell"
</code></pre>
<p><strong>build.cake</strong></p>
<pre><code>#tool "nuget:?package=xunit.runner.console"
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var version = Argument("releaseNumber", "");
var solution = "src/Pentrugatit.sln";
var binFolder = "src/Presentation/Nop.Web/bin/";
var pluginsFolder = "src/Presentation/Nop.Web/Plugins/";
Task("Clean")
.Does(() => {
CleanDirectories(binFolder);
CleanDirectories(pluginsFolder);
});
Task("NuGetRestore")
.Does(() => NuGetRestore(solution));
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("NuGetRestore")
.Does(() => MSBuild(solution, new MSBuildSettings { Configuration = configuration }));
Task("Default")
.IsDependentOn("Build");
RunTarget(target);
</code></pre>
<p><strong>build.ps1 (Cake.net default file)</strong></p>
<pre><code><#
.SYNOPSIS
This is a Powershell script to bootstrap a Cake build.
.DESCRIPTION
This Powershell script will download NuGet if missing, restore NuGet tools (including Cake)
and execute your Cake build script with the parameters you provide.
.PARAMETER Target
The build script target to run.
.PARAMETER Configuration
The build configuration to use.
.PARAMETER Verbosity
Specifies the amount of information to be displayed.
.PARAMETER WhatIf
Performs a dry run of the build script.
No tasks will be executed.
.PARAMETER ScriptArgs
Remaining arguments are added here.
.LINK
http://cakebuild.net
#>
[CmdletBinding()]
Param(
[string]$Target = "Default",
[ValidateSet("Release", "Debug")]
[string]$Configuration = "Release",
[ValidateSet("Quiet", "Minimal", "Normal", "Verbose", "Diagnostic")]
[string]$Verbosity = "Verbose",
[switch]$WhatIf,
[Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)]
[string[]]$ScriptArgs
)
$CakeVersion = "0.17.0"
$DotNetChannel = "preview";
$DotNetVersion = "1.0.0-preview2-003121";
$DotNetInstallerUri = "https://raw.githubusercontent.com/dotnet/cli/rel/1.0.0-preview2/scripts/obtain/dotnet-install.ps1";
$NugetUrl = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
# Make sure tools folder exists
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
$ToolPath = Join-Path $PSScriptRoot "tools"
if (!(Test-Path $ToolPath)) {
Write-Verbose "Creating tools directory..."
New-Item -Path $ToolPath -Type directory | out-null
}
###########################################################################
# INSTALL .NET CORE CLI
###########################################################################
Function Remove-PathVariable([string]$VariableToRemove)
{
$path = [Environment]::GetEnvironmentVariable("PATH", "User")
if ($path -ne $null)
{
$newItems = $path.Split(';', [StringSplitOptions]::RemoveEmptyEntries) | Where-Object { "$($_)" -inotlike $VariableToRemove }
[Environment]::SetEnvironmentVariable("PATH", [System.String]::Join(';', $newItems), "User")
}
$path = [Environment]::GetEnvironmentVariable("PATH", "Process")
if ($path -ne $null)
{
$newItems = $path.Split(';', [StringSplitOptions]::RemoveEmptyEntries) | Where-Object { "$($_)" -inotlike $VariableToRemove }
[Environment]::SetEnvironmentVariable("PATH", [System.String]::Join(';', $newItems), "Process")
}
}
# Get .NET Core CLI path if installed.
$FoundDotNetCliVersion = $null;
if (Get-Command dotnet -ErrorAction SilentlyContinue) {
$FoundDotNetCliVersion = dotnet --version;
}
if($FoundDotNetCliVersion -ne $DotNetVersion) {
$InstallPath = Join-Path $PSScriptRoot ".dotnet"
if (!(Test-Path $InstallPath)) {
mkdir -Force $InstallPath | Out-Null;
}
(New-Object System.Net.WebClient).DownloadFile($DotNetInstallerUri, "$InstallPath\dotnet-install.ps1");
& $InstallPath\dotnet-install.ps1 -Channel $DotNetChannel -Version $DotNetVersion -InstallDir $InstallPath;
Remove-PathVariable "$InstallPath"
$env:PATH = "$InstallPath;$env:PATH"
$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1
$env:DOTNET_CLI_TELEMETRY_OPTOUT=1
}
###########################################################################
# INSTALL NUGET
###########################################################################
# Make sure nuget.exe exists.
$NugetPath = Join-Path $ToolPath "nuget.exe"
if (!(Test-Path $NugetPath)) {
Write-Host "Downloading NuGet.exe..."
(New-Object System.Net.WebClient).DownloadFile($NugetUrl, $NugetPath);
}
###########################################################################
# INSTALL CAKE
###########################################################################
# Make sure Cake has been installed.
$CakePath = Join-Path $ToolPath "Cake.$CakeVersion/Cake.exe"
if (!(Test-Path $CakePath)) {
Write-Host "Installing Cake..."
Invoke-Expression "&`"$NugetPath`" install Cake -Version $CakeVersion -OutputDirectory `"$ToolPath`"" | Out-Null;
if ($LASTEXITCODE -ne 0) {
Throw "An error occured while restoring Cake from NuGet."
}
}
###########################################################################
# RUN BUILD SCRIPT
###########################################################################
# Build the argument list.
$Arguments = @{
target=$Target;
configuration=$Configuration;
verbosity=$Verbosity;
dryrun=$WhatIf;
}.GetEnumerator() | %{"--{0}=`"{1}`"" -f $_.key, $_.value };
# Start Cake
Write-Host "Running build script..."
Invoke-Expression "& `"$CakePath`" `"build.cake`" $Arguments $ScriptArgs"
exit $LASTEXITCODE
</code></pre>
| 0debug
|
How to use node-config in typescript? : <p>After installing <code>node-config</code> and <code>@types/config</code>:</p>
<pre><code>yarn add config
yarn add --dev @types/config
</code></pre>
<p>And adding config as described in <a href="https://github.com/lorenwest/node-config" rel="noreferrer">lorenwest/node-config</a>:</p>
<pre><code>// default.ts
export default {
server: {
port: 4000,
},
logLevel: 'error',
};
</code></pre>
<p>When I am trying to use in my app:</p>
<pre><code>import config from 'config';
console.log(config.server);
</code></pre>
<p>I am getting the error:</p>
<pre><code>src/app.ts(19,53): error TS2339: Property 'server' does not exist on type 'IConfig'.
</code></pre>
| 0debug
|
static uint64_t ac97_read(void *opaque, target_phys_addr_t addr,
unsigned size)
{
MilkymistAC97State *s = opaque;
uint32_t r = 0;
addr >>= 2;
switch (addr) {
case R_AC97_CTRL:
case R_AC97_ADDR:
case R_AC97_DATAOUT:
case R_AC97_DATAIN:
case R_D_CTRL:
case R_D_ADDR:
case R_D_REMAINING:
case R_U_CTRL:
case R_U_ADDR:
case R_U_REMAINING:
r = s->regs[addr];
break;
default:
error_report("milkymist_ac97: read access to unknown register 0x"
TARGET_FMT_plx, addr << 2);
break;
}
trace_milkymist_ac97_memory_read(addr << 2, r);
return r;
}
| 1threat
|
How to print array elements inversely in a given range in c programming? : An array A of N real numbers and two integers K and L (1 ≤ K < L ≤ N) are given. Change the order of the array elements between AK and AL (including these elements) to inverse one.
| 0debug
|
SOAP message to webservice - HTTP response code: 403 for URL : <p>I try to send a <code>SOAP</code> message in an <code>XML</code> file to a webservice and than grab the binary output and decode it. Endpoint uses <code>HTTPS</code> protocol, so I used <code>TrustManager</code> in my code to avoid <code>PKIX</code> problems. You can see my code here:</p>
<pre><code>import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;
public class Main{
public static void sendSoapRequest() throws Exception {
String SOAPUrl = "URL HERE";
String xmlFile2Send = ".\\src\\request.xml";
String responseFileName = ".\\src\\response.xml";
String inputLine;
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
} };
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) { return true; }
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
// Create the connection with http
URL url = new URL(SOAPUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
FileInputStream fin = new FileInputStream(xmlFile2Send);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
copy(fin, bout);
fin.close();
byte[] b = bout.toByteArray();
StringBuffer buf=new StringBuffer();
String s=new String(b);
b=s.getBytes();
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction", "");
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();
// Read the response.
httpConn.connect();
System.out.println("http connection status :"+ httpConn.getResponseMessage());
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
FileOutputStream fos=new FileOutputStream(responseFileName);
copy(httpConn.getInputStream(),fos);
in.close();
}
public static void copy(InputStream in, OutputStream out) throws IOException {
synchronized (in) {
synchronized (out) {
byte[] buffer = new byte[256];
while (true) {
int bytesRead = in.read(buffer);
if (bytesRead == -1)
break;
out.write(buffer, 0, bytesRead);
}
}
}
}
public static void main(String args[]) throws Exception {
sendSoapRequest();
}
}
</code></pre>
<p>I get following error code, when I execute this.</p>
<blockquote>
<p>Exception in thread "main" java.io.IOException: Server returned HTTP
response code: 403 for URL</p>
</blockquote>
| 0debug
|
How do I derive the type for this function: : <p>I'm trying to get better at playing "type tetris". I have the functions:</p>
<pre><code>(=<<) :: Monad m => (a -> m b) -> m a -> m b
zip :: [a] -> [b] -> [(a, b)]
</code></pre>
<p>And GHCi tells me:</p>
<pre><code>(zip =<<) :: ([b] -> [a]) -> [b] -> [(a, b)]
</code></pre>
<p>I'm having a hard time figuring out how to arrive at that final signature from the first two. My intuition (for lack of a better word) is saying that the first argument of <code>=<<</code> namely <code>a -> mb</code> is somehow reconciled against the signature of <code>zip</code>, and then it should all fall out from that. But I can't understand how to make that leap. Can it be broken down in to a series of easy to follow steps?</p>
| 0debug
|
i want to send {"emailId":"IDtxt.text","password":"passtxt.text"} this string as whole string in alamofire request how could i do that? : code :
let str :String = "{"emailId":"\(id)","password":"\(pass)"}"
Alamofire.request(.GET, "http://constructionapp.dev04.vijaywebsolutions.com/proroffingservice.asmx?op=wsUserLogin", parameters: ["json":str])
.responseJSON{response in
self.arrresult = JSON(response.result.value!)}
| 0debug
|
Cannot use new with expression typescript : <pre><code>interface Window {
AudioContext: AudioContext;
webkitAudioContext: Function
}
let contextClass = window.AudioContext || window.webkitAudioContext;
let context: AudioContext = new contextClass();
</code></pre>
<p>The last line is giving me this error,</p>
<blockquote>
<p>Cannot use 'new' with an expression whose type lacks a call or
construct signature</p>
</blockquote>
<p>How can I resolve this?</p>
| 0debug
|
How do I write it in MySQLi? : Im quite new to PHP and MySQl and I try to learn how to change a code from PDO to MySQLi. Its about a remember me function with a securitytoken and identifier for a login system that I found in the web.
I would like to learn and understand how I can change the code from PDO to MySQLi. I know in MySQLi there is a statement create and prepare, also I have to bind parameters and execute. But in this case, I dont know how to start anyway. Thanks for any help with this.
$pdo = new PDO('mysql:host=localhost;dbname=dbname', 'root', '');
if(!isset($_SESSION['id']) && isset($_COOKIE['identifier']) &&
isset($_COOKIE['securitytoken'])) {
$identifier = $_COOKIE['identifier'];
$securitytoken = $_COOKIE['securitytoken'];
$statement = $pdo->prepare("SELECT * FROM securitytokens WHERE identifier = ?");
$result = $statement->execute(array($identifier));
$securitytoken_row = $statement->fetch();
if(sha1($securitytoken) !== $securitytoken_row['securitytoken']) {
die('Maybe a stolen securitytoken.');
} else {
//Token was correct
//Set an new token
$neuer_securitytoken = random_string();
$insert = $pdo->prepare("UPDATE securitytokens SET securitytoken = :securitytoken WHERE identifier = :identifier");
$insert->execute(array('securitytoken' => sha1($neuer_securitytoken), 'identifier' => $identifier));
setcookie("identifier",$identifier,time()+(3600*24*365)); //1 Year valid
setcookie("securitytoken",$neuer_securitytoken,time()+(3600*24*365)); //1 Year valid
//Loggin the user
$_SESSION['id'] = $securitytoken_row['id'];
}
}
| 0debug
|
static int get_char(GDBState *s)
{
uint8_t ch;
int ret;
for(;;) {
ret = qemu_recv(s->fd, &ch, 1, 0);
if (ret < 0) {
if (errno == ECONNRESET)
s->fd = -1;
if (errno != EINTR && errno != EAGAIN)
return -1;
} else if (ret == 0) {
close(s->fd);
s->fd = -1;
return -1;
} else {
break;
}
}
return ch;
}
| 1threat
|
Adding to an ArrayList of a class object? : <pre><code>public static ArrayList<Lecturer> lecturers = new ArrayList<Lecturer>();
lecturers.add(Lecturer);
public Lecturer (String name, String id, String address, String email, String office, String phone_number, String research, Module mod){
super(name, id, address, email, office, phone_number);
this.research = research;
this.mod = mod;
}
</code></pre>
<p>Hi all,
I have created a class and a constructor called Lecturer which stores details about Lecturers. I have also created an ArrayList of the type Lecturer which stores objects of lecturers. However, when I try to add to the list I keep getting the error " expected". I know there is something wrong with the "add(Lecturer)" part but I can't seem to figure out what else to write instead. Any help would be appreciated, thank you.</p>
| 0debug
|
Pandas Dataframe row selection combined condition index- and column values : <p>I want to select rows from a dataframe based on values in the index combined with values in a specific column:</p>
<pre><code>df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [0, 20, 30], [40, 20, 30]],
index=[4, 5, 6, 7], columns=['A', 'B', 'C'])
A B C
4 0 2 3
5 0 4 1
6 0 20 30
7 40 20 30
</code></pre>
<p>with</p>
<pre><code>df.loc[df['A'] == 0, 'C'] = 99
</code></pre>
<p>i can select all rows with column A = 0 and replace the value in column C with 99, but how can i select all rows with column A = 0 and the index < 6 (i want to combine selection on the index with selection on the column)?</p>
| 0debug
|
static int spapr_tce_table_realize(DeviceState *dev)
{
sPAPRTCETable *tcet = SPAPR_TCE_TABLE(dev);
if (kvm_enabled()) {
tcet->table = kvmppc_create_spapr_tce(tcet->liobn,
tcet->nb_table <<
tcet->page_shift,
&tcet->fd,
tcet->vfio_accel);
}
if (!tcet->table) {
size_t table_size = tcet->nb_table * sizeof(uint64_t);
tcet->table = g_malloc0(table_size);
}
trace_spapr_iommu_new_table(tcet->liobn, tcet, tcet->table, tcet->fd);
memory_region_init_iommu(&tcet->iommu, OBJECT(dev), &spapr_iommu_ops,
"iommu-spapr",
(uint64_t)tcet->nb_table << tcet->page_shift);
QLIST_INSERT_HEAD(&spapr_tce_tables, tcet, list);
vmstate_register(DEVICE(tcet), tcet->liobn, &vmstate_spapr_tce_table,
tcet);
return 0;
}
| 1threat
|
bool virtio_scsi_handle_event_vq(VirtIOSCSI *s, VirtQueue *vq)
{
virtio_scsi_acquire(s);
if (s->events_dropped) {
virtio_scsi_push_event(s, NULL, VIRTIO_SCSI_T_NO_EVENT, 0);
virtio_scsi_release(s);
return true;
}
virtio_scsi_release(s);
return false;
}
| 1threat
|
Why has the TypeScript API changed after compiling to JavaScript? : I consider that `const greet = require('./greet');` is equivelant to `import greet from './greet';`.
So these two files should work together:
1. `greet.ts`:
```
export default ({ name, age }) => `Name: ${name}, Age: ${age}`;
```
2. `test.js`:
```
const greet = require("./greet");
greet({ name: 'Smith', age: 21 });
```
But after compiling, `greet.ts` turns out to be:
"use strict";
exports.__esModule = true;
exports["default"] = (function (_a) {
var name = _a.name, age = _a.age;
return "Name: " + name + ", Age: " + age;
});
instead of:
module.exports = (function (_a) {
var name = _a.name, age = _a.age;
return "Name: " + name + ", Age: " + age;
});
Why is this?
| 0debug
|
How to make an asp.net website where we can login using MS ID and Password? : <p>I have created a website which is to be used internally in my company. Log-in Id and password to be used should be the same (Microsoft)MS ID/Password employees use to log-in their computer. How to put this functionality in the website ?</p>
| 0debug
|
static void usb_xhci_realize(struct PCIDevice *dev, Error **errp)
{
int i, ret;
Error *err = NULL;
XHCIState *xhci = XHCI(dev);
dev->config[PCI_CLASS_PROG] = 0x30;
dev->config[PCI_INTERRUPT_PIN] = 0x01;
dev->config[PCI_CACHE_LINE_SIZE] = 0x10;
dev->config[0x60] = 0x30;
if (strcmp(object_get_typename(OBJECT(dev)), TYPE_NEC_XHCI) == 0) {
xhci->nec_quirks = true;
}
if (xhci->numintrs > MAXINTRS) {
xhci->numintrs = MAXINTRS;
}
while (xhci->numintrs & (xhci->numintrs - 1)) {
xhci->numintrs++;
}
if (xhci->numintrs < 1) {
xhci->numintrs = 1;
}
if (xhci->numslots > MAXSLOTS) {
xhci->numslots = MAXSLOTS;
}
if (xhci->numslots < 1) {
xhci->numslots = 1;
}
if (xhci_get_flag(xhci, XHCI_FLAG_ENABLE_STREAMS)) {
xhci->max_pstreams_mask = 7;
} else {
xhci->max_pstreams_mask = 0;
}
if (xhci->msi != ON_OFF_AUTO_OFF) {
ret = msi_init(dev, 0x70, xhci->numintrs, true, false, &err);
assert(!ret || ret == -ENOTSUP);
if (ret && xhci->msi == ON_OFF_AUTO_ON) {
error_append_hint(&err, "You have to use msi=auto (default) or "
"msi=off with this machine type.\n");
error_propagate(errp, err);
return;
}
assert(!err || xhci->msi == ON_OFF_AUTO_AUTO);
error_free(err);
}
usb_xhci_init(xhci);
xhci->mfwrap_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, xhci_mfwrap_timer, xhci);
memory_region_init(&xhci->mem, OBJECT(xhci), "xhci", LEN_REGS);
memory_region_init_io(&xhci->mem_cap, OBJECT(xhci), &xhci_cap_ops, xhci,
"capabilities", LEN_CAP);
memory_region_init_io(&xhci->mem_oper, OBJECT(xhci), &xhci_oper_ops, xhci,
"operational", 0x400);
memory_region_init_io(&xhci->mem_runtime, OBJECT(xhci), &xhci_runtime_ops, xhci,
"runtime", LEN_RUNTIME);
memory_region_init_io(&xhci->mem_doorbell, OBJECT(xhci), &xhci_doorbell_ops, xhci,
"doorbell", LEN_DOORBELL);
memory_region_add_subregion(&xhci->mem, 0, &xhci->mem_cap);
memory_region_add_subregion(&xhci->mem, OFF_OPER, &xhci->mem_oper);
memory_region_add_subregion(&xhci->mem, OFF_RUNTIME, &xhci->mem_runtime);
memory_region_add_subregion(&xhci->mem, OFF_DOORBELL, &xhci->mem_doorbell);
for (i = 0; i < xhci->numports; i++) {
XHCIPort *port = &xhci->ports[i];
uint32_t offset = OFF_OPER + 0x400 + 0x10 * i;
port->xhci = xhci;
memory_region_init_io(&port->mem, OBJECT(xhci), &xhci_port_ops, port,
port->name, 0x10);
memory_region_add_subregion(&xhci->mem, offset, &port->mem);
}
pci_register_bar(dev, 0,
PCI_BASE_ADDRESS_SPACE_MEMORY|PCI_BASE_ADDRESS_MEM_TYPE_64,
&xhci->mem);
if (pci_bus_is_express(dev->bus) ||
xhci_get_flag(xhci, XHCI_FLAG_FORCE_PCIE_ENDCAP)) {
ret = pcie_endpoint_cap_init(dev, 0xa0);
assert(ret > 0);
}
if (xhci->msix != ON_OFF_AUTO_OFF) {
msix_init(dev, xhci->numintrs,
&xhci->mem, 0, OFF_MSIX_TABLE,
&xhci->mem, 0, OFF_MSIX_PBA,
0x90, NULL);
}
}
| 1threat
|
How to create a Worker with parameters for in WorkManager for Android? : <p>Android architecture has a new components <a href="https://developer.android.com/topic/libraries/architecture/workmanager/" rel="noreferrer">WorkManager</a>.</p>
<p>From the <a href="https://developer.android.com/topic/libraries/architecture/workmanager/basics" rel="noreferrer">example</a>,</p>
<pre><code>class CompressWorker(context : Context, params : WorkerParameters)
: Worker(context, params) {
override fun doWork(): Result {
// Do the work here--in this case, compress the stored images.
// In this example no parameters are passed; the task is
// assumed to be "compress the whole library."
myCompress()
// Indicate success or failure with your return value:
return Result.SUCCESS
// (Returning RETRY tells WorkManager to try this task again
// later; FAILURE says not to try again.)
}
}
val compressionWork = OneTimeWorkRequestBuilder<CompressWorker>().build()
</code></pre>
<p>How can I create a <code>Worker</code> that accept parameters in constructor or <code>doWork</code>?</p>
| 0debug
|
string constructor taking two char* into another std::string works in c++14 but not c++17 : <p>The following program attempts to construct a second string using the first string and a pointer into the middle of the first string:</p>
<pre><code>#include <string>
int main() {
std::string src = "hello world";
const char* end = &src[5];
std::string dest(src.data(), end);
}
</code></pre>
<p>In C++14 and earlier this works. But <a href="https://wandbox.org/permlink/fQIbQ2PdJ55AUk5F" rel="noreferrer">in C++17 the call fails</a>:</p>
<pre><code>error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(char*, const char*&)’
std::string dest(src.data(), end);
[... full output omitted ...]
</code></pre>
<p>What changed to make this fail?</p>
| 0debug
|
void gen_intermediate_code(CPUState *cs, struct TranslationBlock *tb)
{
CPUSH4State *env = cs->env_ptr;
DisasContext ctx;
target_ulong pc_start;
int num_insns;
int max_insns;
pc_start = tb->pc;
ctx.pc = pc_start;
ctx.tbflags = (uint32_t)tb->flags;
ctx.envflags = tb->flags & TB_FLAG_ENVFLAGS_MASK;
ctx.bstate = BS_NONE;
ctx.memidx = (ctx.tbflags & (1u << SR_MD)) == 0 ? 1 : 0;
ctx.delayed_pc = -1;
ctx.tb = tb;
ctx.singlestep_enabled = cs->singlestep_enabled;
ctx.features = env->features;
ctx.has_movcal = (ctx.tbflags & TB_FLAG_PENDING_MOVCA);
ctx.gbank = ((ctx.tbflags & (1 << SR_MD)) &&
(ctx.tbflags & (1 << SR_RB))) * 0x10;
ctx.fbank = ctx.tbflags & FPSCR_FR ? 0x10 : 0;
max_insns = tb->cflags & CF_COUNT_MASK;
if (max_insns == 0) {
max_insns = CF_COUNT_MASK;
}
max_insns = MIN(max_insns, TCG_MAX_INSNS);
num_insns = -(ctx.pc | TARGET_PAGE_MASK) / 2;
max_insns = MIN(max_insns, num_insns);
if (ctx.singlestep_enabled || singlestep) {
max_insns = 1;
}
gen_tb_start(tb);
num_insns = 0;
#ifdef CONFIG_USER_ONLY
if (ctx.tbflags & GUSA_MASK) {
num_insns = decode_gusa(&ctx, env, &max_insns);
}
#endif
while (ctx.bstate == BS_NONE
&& num_insns < max_insns
&& !tcg_op_buf_full()) {
tcg_gen_insn_start(ctx.pc, ctx.envflags);
num_insns++;
if (unlikely(cpu_breakpoint_test(cs, ctx.pc, BP_ANY))) {
gen_save_cpu_state(&ctx, true);
gen_helper_debug(cpu_env);
ctx.bstate = BS_EXCP;
ctx.pc += 2;
break;
}
if (num_insns == max_insns && (tb->cflags & CF_LAST_IO)) {
gen_io_start();
}
ctx.opcode = cpu_lduw_code(env, ctx.pc);
decode_opc(&ctx);
ctx.pc += 2;
}
if (tb->cflags & CF_LAST_IO) {
gen_io_end();
}
if (ctx.tbflags & GUSA_EXCLUSIVE) {
ctx.envflags &= ~GUSA_MASK;
}
if (cs->singlestep_enabled) {
gen_save_cpu_state(&ctx, true);
gen_helper_debug(cpu_env);
} else {
switch (ctx.bstate) {
case BS_STOP:
gen_save_cpu_state(&ctx, true);
tcg_gen_exit_tb(0);
break;
case BS_NONE:
gen_save_cpu_state(&ctx, false);
gen_goto_tb(&ctx, 0, ctx.pc);
break;
case BS_EXCP:
case BS_BRANCH:
default:
break;
}
}
gen_tb_end(tb, num_insns);
tb->size = ctx.pc - pc_start;
tb->icount = num_insns;
#ifdef DEBUG_DISAS
if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)
&& qemu_log_in_addr_range(pc_start)) {
qemu_log_lock();
qemu_log("IN:\n");
log_target_disas(cs, pc_start, ctx.pc - pc_start, 0);
qemu_log("\n");
qemu_log_unlock();
}
#endif
}
| 1threat
|
def is_sublist(l, s):
sub_set = False
if s == []:
sub_set = True
elif s == l:
sub_set = True
elif len(s) > len(l):
sub_set = False
else:
for i in range(len(l)):
if l[i] == s[0]:
n = 1
while (n < len(s)) and (l[i+n] == s[n]):
n += 1
if n == len(s):
sub_set = True
return sub_set
| 0debug
|
Javascript change image onclick (specific patern) : So i'm new to javascript and i got this assignment:
"Find a figure with the number 1 and name it "one.jpg" on a page. Change the figure (figure 2) to "two.jpg" when it is clicked. Change after another click to "three.jpg" then back to "one.jpg"
howver i cannot seem to find a solution for this. all examples i found use buttons, anybody help?!
thank you.
| 0debug
|
void qemu_clock_notify(QEMUClockType type)
{
QEMUTimerList *timer_list;
QEMUClock *clock = qemu_clock_ptr(type);
QLIST_FOREACH(timer_list, &clock->timerlists, list) {
timerlist_notify(timer_list);
}
}
| 1threat
|
static int asf_read_seek(AVFormatContext *s, int stream_index,
int64_t pts, int flags)
{
ASFContext *asf = s->priv_data;
AVStream *st = s->streams[stream_index];
int64_t pos;
int index;
if (s->packet_size <= 0)
return -1;
if (s->pb) {
int ret = avio_seek_time(s->pb, stream_index, pts, flags);
if (ret >= 0)
asf_reset_header(s);
if (ret != AVERROR(ENOSYS))
return ret;
}
if (!asf->index_read)
asf_build_simple_index(s, stream_index);
if ((asf->index_read && st->index_entries)) {
index = av_index_search_timestamp(st, pts, flags);
if (index >= 0) {
pos = st->index_entries[index].pos;
av_log(s, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos);
avio_seek(s->pb, pos, SEEK_SET);
asf_reset_header(s);
return 0;
}
}
if (ff_seek_frame_binary(s, stream_index, pts, flags) < 0)
return -1;
asf_reset_header(s);
return 0;
}
| 1threat
|
Who to access at properties of a file using js : <p>Could any one help me with the steps to getting the properties of a file like name path size and more using JavaScript</p>
| 0debug
|
static void network_to_caps(RDMACapabilities *cap)
{
cap->version = ntohl(cap->version);
cap->flags = ntohl(cap->flags);
}
| 1threat
|
static int musicpal_lcd_init(SysBusDevice *dev)
{
musicpal_lcd_state *s = FROM_SYSBUS(musicpal_lcd_state, dev);
s->brightness = 7;
memory_region_init_io(&s->iomem, &musicpal_lcd_ops, s,
"musicpal-lcd", MP_LCD_SIZE);
sysbus_init_mmio(dev, &s->iomem);
s->con = graphic_console_init(lcd_refresh, lcd_invalidate,
NULL, NULL, s);
qemu_console_resize(s->con, 128*3, 64*3);
qdev_init_gpio_in(&dev->qdev, musicpal_lcd_gpio_brigthness_in, 3);
return 0;
}
| 1threat
|
static int initFilter(int16_t **outFilter, int16_t **filterPos, int *outFilterSize, int xInc,
int srcW, int dstW, int filterAlign, int one, int flags, int cpu_flags,
SwsVector *srcFilter, SwsVector *dstFilter, double param[2], int is_horizontal)
{
int i;
int filterSize;
int filter2Size;
int minFilterSize;
int64_t *filter=NULL;
int64_t *filter2=NULL;
const int64_t fone= 1LL<<54;
int ret= -1;
emms_c();
FF_ALLOC_OR_GOTO(NULL, *filterPos, (dstW+3)*sizeof(int16_t), fail);
if (FFABS(xInc - 0x10000) <10) {
int i;
filterSize= 1;
FF_ALLOCZ_OR_GOTO(NULL, filter, dstW*sizeof(*filter)*filterSize, fail);
for (i=0; i<dstW; i++) {
filter[i*filterSize]= fone;
(*filterPos)[i]=i;
}
} else if (flags&SWS_POINT) {
int i;
int xDstInSrc;
filterSize= 1;
FF_ALLOC_OR_GOTO(NULL, filter, dstW*sizeof(*filter)*filterSize, fail);
xDstInSrc= xInc/2 - 0x8000;
for (i=0; i<dstW; i++) {
int xx= (xDstInSrc - ((filterSize-1)<<15) + (1<<15))>>16;
(*filterPos)[i]= xx;
filter[i]= fone;
xDstInSrc+= xInc;
}
} else if ((xInc <= (1<<16) && (flags&SWS_AREA)) || (flags&SWS_FAST_BILINEAR)) {
int i;
int xDstInSrc;
filterSize= 2;
FF_ALLOC_OR_GOTO(NULL, filter, dstW*sizeof(*filter)*filterSize, fail);
xDstInSrc= xInc/2 - 0x8000;
for (i=0; i<dstW; i++) {
int xx= (xDstInSrc - ((filterSize-1)<<15) + (1<<15))>>16;
int j;
(*filterPos)[i]= xx;
for (j=0; j<filterSize; j++) {
int64_t coeff= fone - FFABS((xx<<16) - xDstInSrc)*(fone>>16);
if (coeff<0) coeff=0;
filter[i*filterSize + j]= coeff;
xx++;
}
xDstInSrc+= xInc;
}
} else {
int xDstInSrc;
int sizeFactor;
if (flags&SWS_BICUBIC) sizeFactor= 4;
else if (flags&SWS_X) sizeFactor= 8;
else if (flags&SWS_AREA) sizeFactor= 1;
else if (flags&SWS_GAUSS) sizeFactor= 8;
else if (flags&SWS_LANCZOS) sizeFactor= param[0] != SWS_PARAM_DEFAULT ? ceil(2*param[0]) : 6;
else if (flags&SWS_SINC) sizeFactor= 20;
else if (flags&SWS_SPLINE) sizeFactor= 20;
else if (flags&SWS_BILINEAR) sizeFactor= 2;
else {
sizeFactor= 0;
assert(0);
}
if (xInc <= 1<<16) filterSize= 1 + sizeFactor;
else filterSize= 1 + (sizeFactor*srcW + dstW - 1)/ dstW;
if (filterSize > srcW-2) filterSize=srcW-2;
FF_ALLOC_OR_GOTO(NULL, filter, dstW*sizeof(*filter)*filterSize, fail);
xDstInSrc= xInc - 0x10000;
for (i=0; i<dstW; i++) {
int xx= (xDstInSrc - ((filterSize-2)<<16)) / (1<<17);
int j;
(*filterPos)[i]= xx;
for (j=0; j<filterSize; j++) {
int64_t d= ((int64_t)FFABS((xx<<17) - xDstInSrc))<<13;
double floatd;
int64_t coeff;
if (xInc > 1<<16)
d= d*dstW/srcW;
floatd= d * (1.0/(1<<30));
if (flags & SWS_BICUBIC) {
int64_t B= (param[0] != SWS_PARAM_DEFAULT ? param[0] : 0) * (1<<24);
int64_t C= (param[1] != SWS_PARAM_DEFAULT ? param[1] : 0.6) * (1<<24);
if (d >= 1LL<<31) {
coeff = 0.0;
} else {
int64_t dd = (d * d) >> 30;
int64_t ddd = (dd * d) >> 30;
if (d < 1LL<<30)
coeff = (12*(1<<24)-9*B-6*C)*ddd + (-18*(1<<24)+12*B+6*C)*dd + (6*(1<<24)-2*B)*(1<<30);
else
coeff = (-B-6*C)*ddd + (6*B+30*C)*dd + (-12*B-48*C)*d + (8*B+24*C)*(1<<30);
}
coeff *= fone>>(30+24);
}
else if (flags & SWS_X) {
double A= param[0] != SWS_PARAM_DEFAULT ? param[0] : 1.0;
double c;
if (floatd<1.0)
c = cos(floatd*M_PI);
else
c=-1.0;
if (c<0.0) c= -pow(-c, A);
else c= pow( c, A);
coeff= (c*0.5 + 0.5)*fone;
} else if (flags & SWS_AREA) {
int64_t d2= d - (1<<29);
if (d2*xInc < -(1LL<<(29+16))) coeff= 1.0 * (1LL<<(30+16));
else if (d2*xInc < (1LL<<(29+16))) coeff= -d2*xInc + (1LL<<(29+16));
else coeff=0.0;
coeff *= fone>>(30+16);
} else if (flags & SWS_GAUSS) {
double p= param[0] != SWS_PARAM_DEFAULT ? param[0] : 3.0;
coeff = (pow(2.0, - p*floatd*floatd))*fone;
} else if (flags & SWS_SINC) {
coeff = (d ? sin(floatd*M_PI)/(floatd*M_PI) : 1.0)*fone;
} else if (flags & SWS_LANCZOS) {
double p= param[0] != SWS_PARAM_DEFAULT ? param[0] : 3.0;
coeff = (d ? sin(floatd*M_PI)*sin(floatd*M_PI/p)/(floatd*floatd*M_PI*M_PI/p) : 1.0)*fone;
if (floatd>p) coeff=0;
} else if (flags & SWS_BILINEAR) {
coeff= (1<<30) - d;
if (coeff<0) coeff=0;
coeff *= fone >> 30;
} else if (flags & SWS_SPLINE) {
double p=-2.196152422706632;
coeff = getSplineCoeff(1.0, 0.0, p, -p-1.0, floatd) * fone;
} else {
coeff= 0.0;
assert(0);
}
filter[i*filterSize + j]= coeff;
xx++;
}
xDstInSrc+= 2*xInc;
}
}
assert(filterSize>0);
filter2Size= filterSize;
if (srcFilter) filter2Size+= srcFilter->length - 1;
if (dstFilter) filter2Size+= dstFilter->length - 1;
assert(filter2Size>0);
FF_ALLOCZ_OR_GOTO(NULL, filter2, filter2Size*dstW*sizeof(*filter2), fail);
for (i=0; i<dstW; i++) {
int j, k;
if(srcFilter) {
for (k=0; k<srcFilter->length; k++) {
for (j=0; j<filterSize; j++)
filter2[i*filter2Size + k + j] += srcFilter->coeff[k]*filter[i*filterSize + j];
}
} else {
for (j=0; j<filterSize; j++)
filter2[i*filter2Size + j]= filter[i*filterSize + j];
}
(*filterPos)[i]+= (filterSize-1)/2 - (filter2Size-1)/2;
}
av_freep(&filter);
minFilterSize= 0;
for (i=dstW-1; i>=0; i--) {
int min= filter2Size;
int j;
int64_t cutOff=0.0;
for (j=0; j<filter2Size; j++) {
int k;
cutOff += FFABS(filter2[i*filter2Size]);
if (cutOff > SWS_MAX_REDUCE_CUTOFF*fone) break;
if (i<dstW-1 && (*filterPos)[i] >= (*filterPos)[i+1]) break;
for (k=1; k<filter2Size; k++)
filter2[i*filter2Size + k - 1]= filter2[i*filter2Size + k];
filter2[i*filter2Size + k - 1]= 0;
(*filterPos)[i]++;
}
cutOff=0;
for (j=filter2Size-1; j>0; j--) {
cutOff += FFABS(filter2[i*filter2Size + j]);
if (cutOff > SWS_MAX_REDUCE_CUTOFF*fone) break;
min--;
}
if (min>minFilterSize) minFilterSize= min;
}
if (HAVE_ALTIVEC && cpu_flags & AV_CPU_FLAG_ALTIVEC) {
if (minFilterSize < 5)
filterAlign = 4;
if (minFilterSize < 3)
filterAlign = 1;
}
if (HAVE_MMX && cpu_flags & AV_CPU_FLAG_MMX) {
if (minFilterSize == 1 && filterAlign == 2)
filterAlign= 1;
}
assert(minFilterSize > 0);
filterSize= (minFilterSize +(filterAlign-1)) & (~(filterAlign-1));
assert(filterSize > 0);
filter= av_malloc(filterSize*dstW*sizeof(*filter));
if (filterSize >= MAX_FILTER_SIZE*16/((flags&SWS_ACCURATE_RND) ? APCK_SIZE : 16) || !filter)
goto fail;
*outFilterSize= filterSize;
if (flags&SWS_PRINT_INFO)
av_log(NULL, AV_LOG_VERBOSE, "SwScaler: reducing / aligning filtersize %d -> %d\n", filter2Size, filterSize);
for (i=0; i<dstW; i++) {
int j;
for (j=0; j<filterSize; j++) {
if (j>=filter2Size) filter[i*filterSize + j]= 0;
else filter[i*filterSize + j]= filter2[i*filter2Size + j];
if((flags & SWS_BITEXACT) && j>=minFilterSize)
filter[i*filterSize + j]= 0;
}
}
if (is_horizontal) {
for (i = 0; i < dstW; i++) {
int j;
if ((*filterPos)[i] < 0) {
to compensate for filterPos
for (j = 1; j < filterSize; j++) {
int left = FFMAX(j + (*filterPos)[i], 0);
filter[i * filterSize + left] += filter[i * filterSize + j];
filter[i * filterSize + j ] = 0;
}
(*filterPos)[i] = 0;
}
if ((*filterPos)[i] + filterSize > srcW) {
int shift = (*filterPos)[i] + filterSize - srcW;
for (j = filterSize - 2; j >= 0; j--) {
int right = FFMIN(j + shift, filterSize - 1);
filter[i * filterSize + right] += filter[i * filterSize + j];
filter[i * filterSize + j ] = 0;
}
(*filterPos)[i] = srcW - filterSize;
}
}
}
FF_ALLOCZ_OR_GOTO(NULL, *outFilter, *outFilterSize*(dstW+3)*sizeof(int16_t), fail);
for (i=0; i<dstW; i++) {
int j;
int64_t error=0;
int64_t sum=0;
for (j=0; j<filterSize; j++) {
sum+= filter[i*filterSize + j];
}
sum= (sum + one/2)/ one;
for (j=0; j<*outFilterSize; j++) {
int64_t v= filter[i*filterSize + j] + error;
int intV= ROUNDED_DIV(v, sum);
(*outFilter)[i*(*outFilterSize) + j]= intV;
error= v - intV*sum;
}
}
(*filterPos)[dstW+0] =
(*filterPos)[dstW+1] =
(*filterPos)[dstW+2] = (*filterPos)[dstW-1];
for (i=0; i<*outFilterSize; i++) {
int k= (dstW - 1) * (*outFilterSize) + i;
(*outFilter)[k + 1 * (*outFilterSize)] =
(*outFilter)[k + 2 * (*outFilterSize)] =
(*outFilter)[k + 3 * (*outFilterSize)] = (*outFilter)[k];
}
ret=0;
fail:
av_free(filter);
av_free(filter2);
return ret;
}
| 1threat
|
How std::random_device generate non-deterministic random numbers? : <p>Why std::random_device generate non-deterministic random numbers? What is the seed in this generator? It's not a time, so what?</p>
| 0debug
|
static int adts_write_header(AVFormatContext *s)
{
ADTSContext *adts = s->priv_data;
AVCodecContext *avc = s->streams[0]->codec;
if(avc->extradata_size > 0)
decode_extradata(adts, avc->extradata, avc->extradata_size);
return 0;
}
| 1threat
|
rand() function doesn't works properly : <p>I have a problem with rand() function
I want to build a program that shows the number of each face of dice when you throw it 6000 times</p>
<p>I wrote this code </p>
<pre><code>#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
#include <cstdlib>
#include <ctime>
int main()
{
int face ;
int frequency1 =0;
int frequency2 =0;
int frequency3 =0;
int frequency4 =0;
int frequency5 =0;
int frequency6 =0;
for(int counter =1;counter <=6000;counter++){
face = 1+rand()%6;
switch(face){
case 1:
++frequency1;
break;
case 2:
++frequency1;
break;
case 3:
++frequency1;
break;
case 4:
++frequency1;
break;
case 5:
++frequency1;
break;
case 6:
++frequency1;
break;
default:
cout<<"program should never get here!!! ";
break;
}}
cout<<"the number of face 1 is : "<<frequency1<<endl;
cout<<"the number of face 2 is : "<<frequency2<<endl;
cout<<"the number of face 3 is : "<<frequency3<<endl;
cout<<"the number of face 4 is : "<<frequency4<<endl;
cout<<"the number of face 5 is : " <<frequency5<<endl;
cout<<"the number of face 6 is : " <<frequency6<<endl;
return 0;
}
</code></pre>
<p>Every time that i run this code it shows the same thing</p>
<pre><code>the number of face 1 is : 6000
the number of face 2 is : 0
the number of face 3 is : 0
the number of face 4 is : 0
the number of face 5 is : 0
the number of face 6 is : 0
</code></pre>
| 0debug
|
Restrict some JS to work on specific websites : <p>This is more of a conceptual question. I have a JS that I need to run when user is accessing only specific website(s). Is there any approach to make sure that my particular JS is invoked from some specific website(s)?</p>
<p>Thank you!</p>
| 0debug
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.