problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
ff_vorbis_comment(AVFormatContext * as, AVDictionary **m, const uint8_t *buf, int size)
{
const uint8_t *p = buf;
const uint8_t *end = buf + size;
unsigned n, j;
int s;
if (size < 8)
return -1;
s = bytestream_get_le32(&p);
if (end - p - 4 < s || s < 0)
return -1;
p += s;
n = bytestream_get_le32(&p);
while (end - p >= 4 && n > 0) {
const char *t, *v;
int tl, vl;
s = bytestream_get_le32(&p);
if (end - p < s || s < 0)
break;
t = p;
p += s;
n--;
v = memchr(t, '=', s);
if (!v)
continue;
tl = v - t;
vl = s - tl - 1;
v++;
if (tl && vl) {
char *tt, *ct;
tt = av_malloc(tl + 1);
ct = av_malloc(vl + 1);
if (!tt || !ct) {
av_freep(&tt);
av_log(as, AV_LOG_WARNING, "out-of-memory error. skipping VorbisComment tag.\n");
continue;
}
for (j = 0; j < tl; j++)
tt[j] = av_toupper(t[j]);
tt[tl] = 0;
memcpy(ct, v, vl);
ct[vl] = 0;
if (!strcmp(tt, "METADATA_BLOCK_PICTURE")) {
int ret;
char *pict = av_malloc(vl);
if (!pict) {
av_log(as, AV_LOG_WARNING, "out-of-memory error. Skipping cover art block.\n");
continue;
}
if ((ret = av_base64_decode(pict, ct, vl)) > 0)
ret = ff_flac_parse_picture(as, pict, ret);
av_freep(&pict);
if (ret < 0) {
av_log(as, AV_LOG_WARNING, "Failed to parse cover art block.\n");
continue;
}
} else if (!ogm_chapter(as, tt, ct))
av_dict_set(m, tt, ct,
AV_DICT_DONT_STRDUP_KEY |
AV_DICT_DONT_STRDUP_VAL);
}
}
if (p != end)
av_log(as, AV_LOG_INFO, "%ti bytes of comment header remain\n", end-p);
if (n > 0)
av_log(as, AV_LOG_INFO,
"truncated comment header, %i comments not found\n", n);
ff_metadata_conv(m, NULL, ff_vorbiscomment_metadata_conv);
return 0;
} | 1threat |
Linux Bash, what does this mean: awk 'OFS="\t" {$1=$1}1' /filepath : What does following Linux Bash code do:
awk 'OFS="\t" {$1=$1}1' /filepath | 0debug |
Regex to get all kind of contacts in web-scraping : Pattern cp =Pattern.compile("\\s*(?:\\+*(\\d{1,3})?[-. (]*(\\d{1,6}))[-. )]*?[-. ]*(\\d{1,3})?[-. (]*(\\d{1,3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x\\d{1,6}+)?\\s*");
Getting this kind of formats
- 123-123-1234
- 91 12 12345678
- 123.123.1234
- (123) 345-1234
- 1-800-423-1234
- (123) 123 1234
- +1 123 123 1234
- +123-12-123-1234
- +353-(0)-1-123-1234
### I'm expecting to scrap the numbers in this format 11-11-12345678.<br>
In some cases this regex is getting the Zip number also( When Contact number is followed by the zip number )
###Address:
Main Road<br>
Opp. White Field<br>
Delhi - 501120 <br>
91-12-12345678
>Above pattern is getting like this " 501120 91-12-12345678 ".
Help me out in fixing these 2 issues..Thanks in advance.. :) | 0debug |
How do I display contents of my mongodb database to my front end? : <p>Basically I need to retrieve user input from my html. Use that input to search my mongoDB database via mongoose. Then retrieve and display that information to the front end. I have no idea about how to go about doing this.</p>
| 0debug |
Regex How to match ONLY File name prefix and extension ignoring the numbers in the middle in Ruby? : <p>I've been trying to match only specific prefix and it's extension in a filename but with no luck.
Example:</p>
<p>BX-ST123456.mxf ==> I need to match only BX-ST and .mxf</p>
<p>BX-SR123456.mxf ==> this shouldn't be a match</p>
<p>BXL-ST123456.mxf ==> this shouldn't be a match</p>
<p>so basically the match should happen only if it finds the string of BX-ST and .mxf without restricting the length of numbers in the middle (ignore them) they could be 0-9 in any random.</p>
<p>Example:</p>
<p>BX-ST0.mxf ==> should be a match</p>
<p>BX-ST01.mxf ==> should also be a match and so on.</p>
<p>appreciate your help everyone</p>
| 0debug |
static void vmxnet3_pci_realize(PCIDevice *pci_dev, Error **errp)
{
DeviceState *dev = DEVICE(pci_dev);
VMXNET3State *s = VMXNET3(pci_dev);
VMW_CBPRN("Starting init...");
memory_region_init_io(&s->bar0, OBJECT(s), &b0_ops, s,
"vmxnet3-b0", VMXNET3_PT_REG_SIZE);
pci_register_bar(pci_dev, VMXNET3_BAR0_IDX,
PCI_BASE_ADDRESS_SPACE_MEMORY, &s->bar0);
memory_region_init_io(&s->bar1, OBJECT(s), &b1_ops, s,
"vmxnet3-b1", VMXNET3_VD_REG_SIZE);
pci_register_bar(pci_dev, VMXNET3_BAR1_IDX,
PCI_BASE_ADDRESS_SPACE_MEMORY, &s->bar1);
memory_region_init(&s->msix_bar, OBJECT(s), "vmxnet3-msix-bar",
VMXNET3_MSIX_BAR_SIZE);
pci_register_bar(pci_dev, VMXNET3_MSIX_BAR_IDX,
PCI_BASE_ADDRESS_SPACE_MEMORY, &s->msix_bar);
vmxnet3_reset_interrupt_states(s);
pci_dev->config[PCI_INTERRUPT_PIN] = 0x01;
if (!vmxnet3_init_msix(s)) {
VMW_WRPRN("Failed to initialize MSI-X, configuration is inconsistent.");
}
if (!vmxnet3_init_msi(s)) {
VMW_WRPRN("Failed to initialize MSI, configuration is inconsistent.");
}
vmxnet3_net_init(s);
if (pci_is_express(pci_dev)) {
if (pci_bus_is_express(pci_dev->bus)) {
pcie_endpoint_cap_init(pci_dev, VMXNET3_EXP_EP_OFFSET);
}
pcie_dev_ser_num_init(pci_dev, VMXNET3_DSN_OFFSET,
vmxnet3_device_serial_num(s));
}
register_savevm(dev, "vmxnet3-msix", -1, 1,
vmxnet3_msix_save, vmxnet3_msix_load, s);
}
| 1threat |
python scrabble score calculation : <p><a href="https://i.stack.imgur.com/WoHAH.png" rel="nofollow noreferrer">I am a beginner to python and I'm trying to make a simple scrabble score calculation program. May I know how to get the letter score from the letterScore function and add it to the scrabbleScore function? Thanks a lot for your help! Please have a look on the screenshot for the program I have tried~</a></p>
| 0debug |
static av_cold int wmavoice_decode_init(AVCodecContext *ctx)
{
int n, flags, pitch_range, lsp16_flag;
WMAVoiceContext *s = ctx->priv_data;
if (ctx->extradata_size != 46) {
av_log(ctx, AV_LOG_ERROR,
"Invalid extradata size %d (should be 46)\n",
ctx->extradata_size);
flags = AV_RL32(ctx->extradata + 18);
s->spillover_bitsize = 3 + av_ceil_log2(ctx->block_align);
s->do_apf = flags & 0x1;
if (s->do_apf) {
ff_rdft_init(&s->rdft, 7, DFT_R2C);
ff_rdft_init(&s->irdft, 7, IDFT_C2R);
ff_dct_init(&s->dct, 6, DCT_I);
ff_dct_init(&s->dst, 6, DST_I);
ff_sine_window_init(s->cos, 256);
memcpy(&s->sin[255], s->cos, 256 * sizeof(s->cos[0]));
for (n = 0; n < 255; n++) {
s->sin[n] = -s->sin[510 - n];
s->cos[510 - n] = s->cos[n];
s->denoise_strength = (flags >> 2) & 0xF;
if (s->denoise_strength >= 12) {
av_log(ctx, AV_LOG_ERROR,
"Invalid denoise filter strength %d (max=11)\n",
s->denoise_strength);
s->denoise_tilt_corr = !!(flags & 0x40);
s->dc_level = (flags >> 7) & 0xF;
s->lsp_q_mode = !!(flags & 0x2000);
s->lsp_def_mode = !!(flags & 0x4000);
lsp16_flag = flags & 0x1000;
if (lsp16_flag) {
s->lsps = 16;
s->frame_lsp_bitsize = 34;
s->sframe_lsp_bitsize = 60;
} else {
s->lsps = 10;
s->frame_lsp_bitsize = 24;
s->sframe_lsp_bitsize = 48;
for (n = 0; n < s->lsps; n++)
s->prev_lsps[n] = M_PI * (n + 1.0) / (s->lsps + 1.0);
init_get_bits(&s->gb, ctx->extradata + 22, (ctx->extradata_size - 22) << 3);
if (decode_vbmtree(&s->gb, s->vbm_tree) < 0) {
av_log(ctx, AV_LOG_ERROR, "Invalid VBM tree; broken extradata?\n");
s->min_pitch_val = ((ctx->sample_rate << 8) / 400 + 50) >> 8;
s->max_pitch_val = ((ctx->sample_rate << 8) * 37 / 2000 + 50) >> 8;
pitch_range = s->max_pitch_val - s->min_pitch_val;
if (pitch_range <= 0) {
av_log(ctx, AV_LOG_ERROR, "Invalid pitch range; broken extradata?\n");
s->pitch_nbits = av_ceil_log2(pitch_range);
s->last_pitch_val = 40;
s->last_acb_type = ACB_TYPE_NONE;
s->history_nsamples = s->max_pitch_val + 8;
if (s->min_pitch_val < 1 || s->history_nsamples > MAX_SIGNAL_HISTORY) {
int min_sr = ((((1 << 8) - 50) * 400) + 0xFF) >> 8,
max_sr = ((((MAX_SIGNAL_HISTORY - 8) << 8) + 205) * 2000 / 37) >> 8;
av_log(ctx, AV_LOG_ERROR,
"Unsupported samplerate %d (min=%d, max=%d)\n",
ctx->sample_rate, min_sr, max_sr);
s->block_conv_table[0] = s->min_pitch_val;
s->block_conv_table[1] = (pitch_range * 25) >> 6;
s->block_conv_table[2] = (pitch_range * 44) >> 6;
s->block_conv_table[3] = s->max_pitch_val - 1;
s->block_delta_pitch_hrange = (pitch_range >> 3) & ~0xF;
s->block_delta_pitch_nbits = 1 + av_ceil_log2(s->block_delta_pitch_hrange);
s->block_pitch_range = s->block_conv_table[2] +
s->block_conv_table[3] + 1 +
2 * (s->block_conv_table[1] - 2 * s->min_pitch_val);
s->block_pitch_nbits = av_ceil_log2(s->block_pitch_range);
ctx->sample_fmt = AV_SAMPLE_FMT_FLT;
return 0;
| 1threat |
PHP rename files conatain special charecters "/" and " " : How to rename file with name conatain "/" in PHP
example : "A / B"
$filename= "A / B";
rename("1.html", $filename.".html");
doesn't work !!! | 0debug |
Live regular expression highlighting : <p>I am attempting to use JavaScript to highlight regular expression matches in real time. Similar to sites such as <a href="http://regexr.com/" rel="nofollow">http://regexr.com/</a></p>
<pre><code><p id="haystack"> Sample text Sample Text Sample Text Sample Text </p>
<form>
<input id="needle" onkeyup="highlight('haystack')" onkeydown="highlight('haystack')" type="text" placeholder="Enter Pattern" autofocus>
</form>
function highlight(e){
var pattern = document.getElementById('needle');
var consoleText = document.getElementById('haystack').innerHTML;
consoleText = consoleText.replace(pattern.value,"replaced");
document.getElementById('haystack').innerHTML = consoleText;
</code></pre>
<p>I'm very new to JavaScript. How can I achieve the desired effect?</p>
| 0debug |
static void decode_colskip(uint8_t* plane, int width, int height, int stride, VC9Context *v){
int x, y;
GetBitContext *gb = &v->s.gb;
for (x=0; x<width; x++){
if (!get_bits(gb, 1))
for (y=0; y<height; y++)
plane[y*stride] = 0;
else
for (y=0; y<height; y++)
plane[y*stride] = get_bits(gb, 1);
plane ++;
}
}
| 1threat |
how to develope private website for a company by renting server : i want to develop a web application for some company it is home rent system and the customer data need to be stored in a server and i want to make it a website but any one can not see and use it other than the company the problem i faced is if the company had a server it will be easy since a website in intranet is not visible on the internet but they have no server and we want to rent server from some web hosting company and access the site by only the company if you understsand what i want to say please share me what shall i do? | 0debug |
void qemu_file_skip(QEMUFile *f, int size)
{
if (f->buf_index + size <= f->buf_size) {
f->buf_index += size;
}
}
| 1threat |
Jest expect.any() not working as expected : <p>So when testing one of my <strong>reducers</strong> in a Preact(not much different to React while testing with JEST) based project, I got bumped into this issue:</p>
<p>Following output comes up when running jest test - </p>
<pre><code>● should setup
expect(received).toEqual(expected)
Expected value to equal:
{"ID": Any<String>, "active": true, "data": Any<Array>}
Received:
{"ID": "BysnEuMlm", "active": true, "data": [{"ID": "Hy7wMAz1lm", "code": "dat.fle", "label": "CRES/datum14.cdata", "name": "File", "status": "READY", "value": {"format": "cdata", "name": "datum14.cdata", "path": "CRES"}}, {"ID": "rkB7RMkeX", "code": "prp.kcv", "label": "3 folds", "name": "k-Fold Cross-Validation", "status": "READY", "value": "3"}, {"ID": "ByCmRfygQ", "code": "ats", "label": undefined, "name": " Best First + Cfs Subset Eval", "status": "READY", "value": {"evaluator": {"name": "CfsSubsetEval"}, "search": {"name": "BestFirst", "options": ["-D", "1", "-N", "5"]}, "use": true}}, {"ID": "HkmVAM1l7", "code": "lrn", "label": undefined, "name": "Naive Bayes", "status": "READY", "value": {"label": "Naive Bayes", "name": "bayes.NaiveBayes", "use": true}}], "output": {"format": "pipeline", "name": "jestReact.cpipe", "path": "/home/rupav/opensource/candis/CRES"}}
Difference:
- Expected
+ Received
Object {
- "ID": Any<String>,
+ "ID": "BysnEuMlm",
"active": true,
- "data": Any<Array>,
+ "data": Array [
+ Object {
+ "ID": "Hy7wMAz1lm",
+ "code": "dat.fle",
+ "label": "CRES/datum14.cdata",
+ "name": "File",
+ "status": "READY",
+ "value": Object {
+ "format": "cdata",
+ "name": "datum14.cdata",
+ "path": "CRES",
+ },
+ },
+ Object {
+ "ID": "rkB7RMkeX",
+ "code": "prp.kcv",
+ "label": "3 folds",
+ "name": "k-Fold Cross-Validation",
+ "status": "READY",
+ "value": "3",
+ },
+ Object {
+ "ID": "ByCmRfygQ",
+ "code": "ats",
+ "label": undefined,
+ "name": " Best First + Cfs Subset Eval",
+ "status": "READY",
+ "value": Object {
+ "evaluator": Object {
+ "name": "CfsSubsetEval",
+ },
+ "search": Object {
+ "name": "BestFirst",
+ "options": Array [
+ "-D",
+ "1",
+ "-N",
+ "5",
+ ],
+ },
+ "use": true,
+ },
+ },
+ Object {
+ "ID": "HkmVAM1l7",
+ "code": "lrn",
+ "label": undefined,
+ "name": "Naive Bayes",
+ "status": "READY",
+ "value": Object {
+ "label": "Naive Bayes",
+ "name": "bayes.NaiveBayes",
+ "use": true,
+ },
+ },
+ ],
+ "output": Object {
+ "format": "pipeline",
+ "name": "jestReact.cpipe",
+ "path": "/home/rupav/opensource/candis/CRES",
+ },
}
</code></pre>
<p>Following is the test case:</p>
<pre><code>test('should setup ', () => {
const state = documentProcessor(
undefined,
{
type: ActionType.Asynchronous.READ_SUCCESS,
payload: dokuments.active
})
// expect(state.active.ID).toEqual(expect.any(String)) - Test case passes iff I run this test with this command only.
expect(state.active).toEqual({
data: expect.any(Array),
active: true,
ID: expect.any(String),
})
})
</code></pre>
<p>Since state gets changed while calling that reducer, I needed to use <code>expect.any</code> function, but as per the output, although types are same, test is not getting passed.
Rather in expected its showing up <code>Any<String></code>.</p>
| 0debug |
C Floating Point Division Result Rounded to Zero : <p>Why does this expression give me an output of zero?</p>
<pre><code>float x = ((1000)/(24 * 60 * 60));
</code></pre>
<p>Breaking this into two parts, gives the correct result:</p>
<pre><code>float x = (1000);
x /= (24 * 60 * 60);
</code></pre>
| 0debug |
static int bdrv_can_snapshot(BlockDriverState *bs)
{
return (bs &&
!bdrv_is_removable(bs) &&
!bdrv_is_read_only(bs));
}
| 1threat |
How to get first file extension in string using PHP? : <p>I want to get first file extension in string using php.</p>
<p>now i use this code.</p>
<pre><code><?php
$string = "aaa.jpgbbb.pngccc.jpg";
if( strpos( $string, $needle ) !== false ) {
list($string) = explode('.png',$string);
echo $string.".jpg";
}
?>
</code></pre>
<p>My code only check file extension in string. but can not get first file extension. How can i do ?</p>
<p>.
.</p>
<p>For this string first file extension is <code>jpg</code>.</p>
<pre><code>$string = "aaa.jpgbbb.pngccc.jpg";
</code></pre>
<p>.
.</p>
<p>For this string first file extension is <code>gif</code>.</p>
<pre><code>$string = "aaa.gifbbb.pngccc.jpg";
</code></pre>
<p>.
.</p>
<p>For this string first file extension is <code>png</code>.</p>
<pre><code>$string = "aaa.pngbbb.pngccc.jpg";
</code></pre>
| 0debug |
How to reuse block of HTML in template of component? : <p>I have some Angular components with the same HTML structure</p>
<pre><code><div class='something'>
<div ...>
<custom HTML code for Component>
</div>
</div>
</code></pre>
<p>Now, how can I reuse code to something like</p>
<pre><code><popup-template>
<custom HTML code for Component>
</popup-template>
</code></pre>
| 0debug |
How to create my own delay function in C : <p>I'm developing an OS and don't have access to the standard library. Therefore, I don't have access to <code>time.h</code>.</p>
<p>I'm using the following function to create a time delay.</p>
<pre><code>void delay() {
int c = 1 , d = 1 ;
for ( c = 1; c <= 100000; c++) {
for ( d = 1; d <= 100000; d ++) {
asm("nop");
}
}
}
</code></pre>
<p>This waits around twenty seconds; however, I'd like the function to take in an integer and wait for that many seconds. What will I need to do to make this possible?</p>
| 0debug |
static void filter_mb( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize) {
MpegEncContext * const s = &h->s;
const int mb_xy= mb_x + mb_y*s->mb_stride;
const int mb_type = s->current_picture.mb_type[mb_xy];
const int mvy_limit = IS_INTERLACED(mb_type) ? 2 : 4;
int first_vertical_edge_done = 0;
int dir;
if(!FRAME_MBAFF){
int qp_thresh = 15 - h->slice_alpha_c0_offset - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1]);
int qp = s->current_picture.qscale_table[mb_xy];
if(qp <= qp_thresh
&& (mb_x == 0 || ((qp + s->current_picture.qscale_table[mb_xy-1] + 1)>>1) <= qp_thresh)
&& (mb_y == 0 || ((qp + s->current_picture.qscale_table[h->top_mb_xy] + 1)>>1) <= qp_thresh)){
return;
}
}
if (FRAME_MBAFF
&& h->slice_table[mb_xy-1] != 255
&& (IS_INTERLACED(mb_type) != IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]))
&& (h->deblocking_filter!=2 || h->slice_table[mb_xy-1] == h->slice_table[mb_xy])) {
const int pair_xy = mb_x + (mb_y&~1)*s->mb_stride;
const int left_mb_xy[2] = { pair_xy-1, pair_xy-1+s->mb_stride };
int16_t bS[8];
int qp[2];
int bqp[2];
int rqp[2];
int mb_qp, mbn0_qp, mbn1_qp;
int i;
first_vertical_edge_done = 1;
if( IS_INTRA(mb_type) )
bS[0] = bS[1] = bS[2] = bS[3] = bS[4] = bS[5] = bS[6] = bS[7] = 4;
else {
for( i = 0; i < 8; i++ ) {
int mbn_xy = MB_FIELD ? left_mb_xy[i>>2] : left_mb_xy[i&1];
if( IS_INTRA( s->current_picture.mb_type[mbn_xy] ) )
bS[i] = 4;
else if( h->non_zero_count_cache[12+8*(i>>1)] != 0 ||
h->non_zero_count[mbn_xy][MB_FIELD ? i&3 : (i>>2)+(mb_y&1)*2] )
bS[i] = 2;
else
bS[i] = 1;
}
}
mb_qp = s->current_picture.qscale_table[mb_xy];
mbn0_qp = s->current_picture.qscale_table[left_mb_xy[0]];
mbn1_qp = s->current_picture.qscale_table[left_mb_xy[1]];
qp[0] = ( mb_qp + mbn0_qp + 1 ) >> 1;
bqp[0] = ( get_chroma_qp( h, 0, mb_qp ) +
get_chroma_qp( h, 0, mbn0_qp ) + 1 ) >> 1;
rqp[0] = ( get_chroma_qp( h, 1, mb_qp ) +
get_chroma_qp( h, 1, mbn0_qp ) + 1 ) >> 1;
qp[1] = ( mb_qp + mbn1_qp + 1 ) >> 1;
bqp[1] = ( get_chroma_qp( h, 0, mb_qp ) +
get_chroma_qp( h, 0, mbn1_qp ) + 1 ) >> 1;
rqp[1] = ( get_chroma_qp( h, 1, mb_qp ) +
get_chroma_qp( h, 1, mbn1_qp ) + 1 ) >> 1;
tprintf(s->avctx, "filter mb:%d/%d MBAFF, QPy:%d/%d, QPb:%d/%d QPr:%d/%d ls:%d uvls:%d", mb_x, mb_y, qp[0], qp[1], bqp[0], bqp[1], rqp[0], rqp[1], linesize, uvlinesize);
{ int i; for (i = 0; i < 8; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
filter_mb_mbaff_edgev ( h, &img_y [0], linesize, bS, qp );
filter_mb_mbaff_edgecv( h, &img_cb[0], uvlinesize, bS, bqp );
filter_mb_mbaff_edgecv( h, &img_cr[0], uvlinesize, bS, rqp );
}
for( dir = 0; dir < 2; dir++ )
{
int edge;
const int mbm_xy = dir == 0 ? mb_xy -1 : h->top_mb_xy;
const int mbm_type = s->current_picture.mb_type[mbm_xy];
int start = h->slice_table[mbm_xy] == 255 ? 1 : 0;
const int edges = (mb_type & (MB_TYPE_16x16|MB_TYPE_SKIP))
== (MB_TYPE_16x16|MB_TYPE_SKIP) ? 1 : 4;
const int mask_edge = (mb_type & (MB_TYPE_16x16 | (MB_TYPE_16x8 << dir))) ? 3 :
(mb_type & (MB_TYPE_8x16 >> dir)) ? 1 : 0;
const int mask_par0 = mb_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir));
if (first_vertical_edge_done) {
start = 1;
first_vertical_edge_done = 0;
}
if (h->deblocking_filter==2 && h->slice_table[mbm_xy] != h->slice_table[mb_xy])
start = 1;
if (FRAME_MBAFF && (dir == 1) && ((mb_y&1) == 0) && start == 0
&& !IS_INTERLACED(mb_type)
&& IS_INTERLACED(mbm_type)
) {
static const int nnz_idx[4] = {4,5,6,3};
unsigned int tmp_linesize = 2 * linesize;
unsigned int tmp_uvlinesize = 2 * uvlinesize;
int mbn_xy = mb_xy - 2 * s->mb_stride;
int qp;
int i, j;
int16_t bS[4];
for(j=0; j<2; j++, mbn_xy += s->mb_stride){
if( IS_INTRA(mb_type) ||
IS_INTRA(s->current_picture.mb_type[mbn_xy]) ) {
bS[0] = bS[1] = bS[2] = bS[3] = 3;
} else {
const uint8_t *mbn_nnz = h->non_zero_count[mbn_xy];
for( i = 0; i < 4; i++ ) {
if( h->non_zero_count_cache[scan8[0]+i] != 0 ||
mbn_nnz[nnz_idx[i]] != 0 )
bS[i] = 2;
else
bS[i] = 1;
}
}
Do not use s->qscale as luma quantizer because it has not the same
value in IPCM macroblocks.
qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;
tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, tmp_linesize, tmp_uvlinesize);
{ int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
filter_mb_edgeh( h, &img_y[j*linesize], tmp_linesize, bS, qp );
filter_mb_edgech( h, &img_cb[j*uvlinesize], tmp_uvlinesize, bS,
( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
filter_mb_edgech( h, &img_cr[j*uvlinesize], tmp_uvlinesize, bS,
( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
}
start = 1;
}
for( edge = start; edge < edges; edge++ ) {
const int mbn_xy = edge > 0 ? mb_xy : mbm_xy;
const int mbn_type = s->current_picture.mb_type[mbn_xy];
int16_t bS[4];
int qp;
if( (edge&1) && IS_8x8DCT(mb_type) )
continue;
if( IS_INTRA(mb_type) ||
IS_INTRA(mbn_type) ) {
int value;
if (edge == 0) {
if ( (!IS_INTERLACED(mb_type) && !IS_INTERLACED(mbm_type))
|| ((FRAME_MBAFF || (s->picture_structure != PICT_FRAME)) && (dir == 0))
) {
value = 4;
} else {
value = 3;
}
} else {
value = 3;
}
bS[0] = bS[1] = bS[2] = bS[3] = value;
} else {
int i, l;
int mv_done;
if( edge & mask_edge ) {
bS[0] = bS[1] = bS[2] = bS[3] = 0;
mv_done = 1;
}
else if( FRAME_MBAFF && IS_INTERLACED(mb_type ^ mbn_type)) {
bS[0] = bS[1] = bS[2] = bS[3] = 1;
mv_done = 1;
}
else if( mask_par0 && (edge || (mbn_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir)))) ) {
int b_idx= 8 + 4 + edge * (dir ? 8:1);
int bn_idx= b_idx - (dir ? 8:1);
int v = 0;
int xn= h->slice_type_nos == FF_B_TYPE && h->ref2frm[0][h->ref_cache[0][b_idx]+2] != h->ref2frm[0][h->ref_cache[0][bn_idx]+2];
for( l = 0; !v && l < 1 + (h->slice_type_nos == FF_B_TYPE); l++ ) {
int ln= l^xn;
v |= h->ref2frm[l][h->ref_cache[l][b_idx]+2] != h->ref2frm[ln][h->ref_cache[ln][bn_idx]+2] ||
FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[ln][bn_idx][0] ) >= 4 ||
FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[ln][bn_idx][1] ) >= mvy_limit;
}
bS[0] = bS[1] = bS[2] = bS[3] = v;
mv_done = 1;
}
else
mv_done = 0;
for( i = 0; i < 4; i++ ) {
int x = dir == 0 ? edge : i;
int y = dir == 0 ? i : edge;
int b_idx= 8 + 4 + x + 8*y;
int bn_idx= b_idx - (dir ? 8:1);
if( h->non_zero_count_cache[b_idx] != 0 ||
h->non_zero_count_cache[bn_idx] != 0 ) {
bS[i] = 2;
}
else if(!mv_done)
{
int xn= h->slice_type_nos == FF_B_TYPE && h->ref2frm[0][h->ref_cache[0][b_idx]+2] != h->ref2frm[0][h->ref_cache[0][bn_idx]+2];
bS[i] = 0;
for( l = 0; l < 1 + (h->slice_type_nos == FF_B_TYPE); l++ ) {
int ln= l^xn;
if( h->ref2frm[l][h->ref_cache[l][b_idx]+2] != h->ref2frm[ln][h->ref_cache[ln][bn_idx]+2] ||
FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[ln][bn_idx][0] ) >= 4 ||
FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[ln][bn_idx][1] ) >= mvy_limit ) {
bS[i] = 1;
break;
}
}
}
}
if(bS[0]+bS[1]+bS[2]+bS[3] == 0)
continue;
}
Do not use s->qscale as luma quantizer because it has not the same
value in IPCM macroblocks.
qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;
tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d, QPc:%d, QPcn:%d\n", mb_x, mb_y, dir, edge, qp, h->chroma_qp, s->current_picture.qscale_table[mbn_xy]);
tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, linesize, uvlinesize);
{ int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
if( dir == 0 ) {
filter_mb_edgev( h, &img_y[4*edge], linesize, bS, qp );
if( (edge&1) == 0 ) {
filter_mb_edgecv( h, &img_cb[2*edge], uvlinesize, bS,
( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
filter_mb_edgecv( h, &img_cr[2*edge], uvlinesize, bS,
( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
}
} else {
filter_mb_edgeh( h, &img_y[4*edge*linesize], linesize, bS, qp );
if( (edge&1) == 0 ) {
filter_mb_edgech( h, &img_cb[2*edge*uvlinesize], uvlinesize, bS,
( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
filter_mb_edgech( h, &img_cr[2*edge*uvlinesize], uvlinesize, bS,
( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
}
}
}
}
}
| 1threat |
How to check time interval for presence of 31st of January of any year : Trying to make 30 days in 31 days months.
I made code, but it checks only current date, when I use (from:, to:) it counts difference, but not checking the time interval.
let componentsForStatement = calendar.dateComponents([.day, .month], from: currentDateDay)
if ((componentsForStatement.month == 01) || (componentsForStatement.month == 03) || (componentsForStatement.month == 05) || (componentsForStatement.month == 07) || (componentsForStatement.month == 08) || (componentsForStatement.month == 10) || (componentsForStatement.month == 12)) && componentsForStatement.day == 31 {
daysPassed -= 1} | 0debug |
SQLite: Geeting value 0 from a select when insert works correct : I have a Table `Notes (_Id, Title, Body, Category)` and a Table `Categories (_Id, Name)`, referencing Category to Categories._Id.
Whit this method I create a Note in my SQLite Database.
/**
* Create a new note using the title and body provided, and associated to
* the category with row id provided. If the note is successfully created
* return the new rowId for that note, otherwise return a -1 to indicate failure.
*
* @param title the title of the note
* @param body the body of the note
* @param category the category associated to the note
* @return rowId or -1 if failed
*/
public long createNote(String title, String body, String category) {
if (title == null || title.equals("") || body == null) {
return -1;
}
else {
ContentValues initialValues = new ContentValues();
initialValues.put(NOTE_KEY_TITLE, title);
initialValues.put(NOTE_KEY_BODY, body);
// If it has associated a category
if (!category.equals("No Category")) {
Cursor idCategory = fetchCategory(category);
long catId = idCategory.getLong(idCategory.getColumnIndex("_id"));
initialValues.put(NOTE_KEY_CAT, catId);
// Else, it has no category
} else {
initialValues.put(NOTE_KEY_CAT, (Byte) null);
}
return mDb.insert(DATABASE_NOTE_TABLE, null, initialValues);
}
}
And whit this another I get all the notes of my database.
/**
* Return a Cursor over the list of all notes in the database
*
* @param mode - if TITLE, it returns the list ordered by the title of the notes.
* - if CATEGORY, it returns the list ordered by the category of the notes.
* - it returns null in another case.
* @param category - category of the notes to return (No Category if none)
* @return Cursor over all notes
*/
public Cursor fetchAllNotes(String mode, String category) {
//// Order
String order;
// Mode is Title
if (mode.equals("TITLE")) {
order = NOTE_KEY_TITLE;
// Mode is Categories
} else if (mode.equals("CATEGORY")) {
order = CAT_KEY_NAME;
// A forbidden mode
} else {
return null;
}
// No category filter if it is No Category
String cat;
if (category.equals("No Category")) {
cat = "";
} else {
cat = " WHERE " + CAT_KEY_NAME + "='" + category + "'";
} // Left outer because there are notes without category
String query = "SELECT * FROM " + DATABASE_NOTE_TABLE + " LEFT OUTER JOIN " + DATABASE_CAT_TABLE +
" C ON " + NOTE_KEY_CAT + "=C." + CAT_KEY_ROWID + cat + " ORDER BY " + order;
return mDb.rawQuery(query, null);
}
When I insert a new Note, `createNote()` returns me the correct rowId. When I realize a `fetchAllNotes()` operation, two things happens: when a Note has a category, it returns the correct note with its proper attributes. When another Note has not Category (value `No Category`), the note with the desired attributes is returned, but not its identifier (a 0 value is returned as _id).
Any idea of what is happening? | 0debug |
Access router instance from my service : <p>I create a auth service (<code>src/services/auth.js</code>), with just functions and properties ..</p>
<pre><code>export default {
login() { ... }
...
}
</code></pre>
<p>Inside <code>login</code> function, I need to redirect user </p>
<pre><code>router.go(redirect)
</code></pre>
<p><strong>How can I retrieve router instance</strong>?</p>
<hr>
<h3>Context</h3>
<p>In my <code>src/main.js</code> file, i create a router ..</p>
<pre><code>import VueRouter from 'vue-router'
Vue.use(VueRouter)
import route from './routes'
const router = new VueRouter({
history: false,
linkActiveClass: 'active'
})
route(router)
const App = Vue.extend(require('./App.vue'))
</code></pre>
<p>In my <code>src/routers.js</code> is just map routes</p>
<pre><code>export default function configRouter (router) {
router.map({ .. })
}
</code></pre>
| 0debug |
HFP/HSP profile in linux : <p>I have Ubuntu 16.04 and already installed BlueZ 5.37, PulseAudio 10.0, and ofono 1.20 (clone from github). </p>
<p>And I need to use phone like modem for transmitting my phone calls to computer. I paired my telephone with PC, made device trust and connect (all actions are successfully). I think problem with ofono, because I can play music (which use the A2DP) but if i want use hends free or headset profile - I have no sound on PC. </p>
<p>In pacmd (PulseAudio console tool) list-cards I see my bluetooth device, but Headset Audio Gateway HFP/HSP is not avalible. Also I tested it on different devices and computers. </p>
<p>Thank you in advice.</p>
| 0debug |
Adding url into <a href=""> with Emmet : <p>Has Emmet a syntax for adding <code>URL</code> into <code><a href=""></code> tag?</p>
<p>E.g.:</p>
<p>Syntax:</p>
<pre><code>a:www.google.com
</code></pre>
<p>Result:</p>
<pre><code><a href="www.google.com"></a>
</code></pre>
| 0debug |
How can I put an icon inside a TextInput in React Native? : <p>I am thinking of having something like this <a href="https://android-arsenal.com/details/1/3941" rel="noreferrer">https://android-arsenal.com/details/1/3941</a> where you have icon that you press to show password as plaintext, not as dots. However, I was unable to find any custom component that would help me.</p>
<p>I don't want to put too much time on such a minor feature, so I'm asking without having attempted anything yet: Is there a custom component I've missed? If not, is there a simple way to add children to TextInput? Or should I just have TextInput and Touchable side by side?</p>
| 0debug |
How do I access the input from UI Text View in Swift Xcode : I have linked my uitextview and I have looked all around and cannot seem to be able to access the information my user inputs. This probably is a dumb question but I am Kinda new to swift so any advice would be awesome. Thank again | 0debug |
Check how many times a file has been changed : <p>Git traced all the files changed and updated,</p>
<p>is it possible to check how many times a file have been changed?</p>
<p>or one more step sort files by times they were modified?</p>
| 0debug |
static void handle_msr(DisasContext *s, uint32_t insn, unsigned int op0,
unsigned int op1, unsigned int op2,
unsigned int crn, unsigned int crm, unsigned int rt)
{
unsupported_encoding(s, insn);
}
| 1threat |
static int rm_write_header(AVFormatContext *s)
{
RMMuxContext *rm = s->priv_data;
StreamInfo *stream;
int n;
AVCodecContext *codec;
for(n=0;n<s->nb_streams;n++) {
s->streams[n]->id = n;
codec = s->streams[n]->codec;
stream = &rm->streams[n];
memset(stream, 0, sizeof(StreamInfo));
stream->num = n;
stream->bit_rate = codec->bit_rate;
stream->enc = codec;
switch(codec->codec_type) {
case AVMEDIA_TYPE_AUDIO:
rm->audio_stream = stream;
stream->frame_rate = (float)codec->sample_rate / (float)codec->frame_size;
stream->packet_max_size = 1024;
stream->nb_packets = 0;
stream->total_frames = stream->nb_packets;
break;
case AVMEDIA_TYPE_VIDEO:
rm->video_stream = stream;
stream->frame_rate = (float)codec->time_base.den / (float)codec->time_base.num;
stream->packet_max_size = 4096;
stream->nb_packets = 0;
stream->total_frames = stream->nb_packets;
break;
default:
return -1;
if (rv10_write_header(s, 0, 0))
return AVERROR_INVALIDDATA;
avio_flush(s->pb);
return 0; | 1threat |
Cauchy Distribution Secant Method C++ RCPP : I am quite new to C++ and RCPP integration. I am required to create a program using C++ with R integration to find the MLE/root of a Cauchy Distribution.
Below is my code thus far.
#include <Rcpp.h>
#include <math.h>
#include <iostream>
#include <cstdlib>
using namespace std;
using namespace Rcpp;
// [[Rcpp::export]]
double Cauchy(double x, double y); //Declare Function
double Cauchy(double x,double y) //Define Function
{
return 1/(M_PI*(1+(pow(x-y,2)))); //write the equation whose roots are
to be determined x=chosen y=theta
}
using namespace std;
// [[Rcpp::export]]
int Secant (NumericVector x){
NumericVector xvector(x) ; //Input of x vector
double eplison= 0.001; //Threshold
double a= xvector[3]; //Select starting point
double b= xvector[4];//Select end point
double c= 0.0; //initial value for c
double Theta= 10.6; //median value for theta estimate
int noofIter= 0; //Iterations
double error = 0.0;
if (std::abs(Cauchy(a, Theta)<(std::abs(Cauchy(a, Theta))))){
do{
a=b;
b=c;
error= (b-(Cauchy(b, Theta)))*((a-b)/(Cauchy(a, Theta)-Cauchy(b, Theta)));
error= Cauchy(c,Theta);
//return number of iterations
noofIter++;
for (int i = 0; i < noofIter; i += 1) {
cout << "The Value is " << c << endl;
cout << "The Value is " << a << endl;
cout << "The Value is " << b << endl;
cout << "The Value is " << Theta << endl;
}
}while (std::abs(error)>eplison);
}
cout<<"\nThe root of the equation is occurs at "<<c<<endl; //print the
root
cout << "The number of iterations is " << noofIter;
return 0;
}``
With a few ammendments, the program either goes into a never ending loop or returns a value which is infinitely small.
My understanding of this mathematics is limited. Therefore any help or correction in that would be greatly appreciated.
The X vector that we have been given as an output is
x <- c( 11.262307 , 10.281078 , 10.287090 , 12.734039 ,
11.731881 , 8.861998 , 12.246509 , 11.244818 ,
9.696278 , 11.557572 , 11.112531 , 10.550190 ,
9.018438 , 10.704774 , 9.515617 , 10.003247 ,
10.278352 , 9.709630 , 10.963905 , 17.314814)
Using previous R code we know that the MLE/Root for this distribution occurs at 10.5935 approx
Thanks! | 0debug |
static int cavs_decode_frame(AVCodecContext * avctx,void *data, int *data_size,
uint8_t * buf, int buf_size) {
AVSContext *h = avctx->priv_data;
MpegEncContext *s = &h->s;
int input_size;
const uint8_t *buf_end;
const uint8_t *buf_ptr;
AVFrame *picture = data;
uint32_t stc;
s->avctx = avctx;
if (buf_size == 0) {
if(!s->low_delay && h->DPB[0].data[0]) {
*data_size = sizeof(AVPicture);
*picture = *(AVFrame *) &h->DPB[0];
}
return 0;
}
buf_ptr = buf;
buf_end = buf + buf_size;
for(;;) {
buf_ptr = ff_find_start_code(buf_ptr,buf_end, &stc);
if(stc & 0xFFFFFE00)
return FFMAX(0, buf_ptr - buf - s->parse_context.last_index);
input_size = (buf_end - buf_ptr)*8;
switch(stc) {
case CAVS_START_CODE:
init_get_bits(&s->gb, buf_ptr, input_size);
decode_seq_header(h);
break;
case PIC_I_START_CODE:
if(!h->got_keyframe) {
if(h->DPB[0].data[0])
avctx->release_buffer(avctx, (AVFrame *)&h->DPB[0]);
if(h->DPB[1].data[0])
avctx->release_buffer(avctx, (AVFrame *)&h->DPB[1]);
h->got_keyframe = 1;
}
case PIC_PB_START_CODE:
*data_size = 0;
if(!h->got_keyframe)
break;
init_get_bits(&s->gb, buf_ptr, input_size);
h->stc = stc;
if(decode_pic(h))
break;
*data_size = sizeof(AVPicture);
if(h->pic_type != FF_B_TYPE) {
if(h->DPB[1].data[0]) {
*picture = *(AVFrame *) &h->DPB[1];
} else {
*data_size = 0;
}
} else
*picture = *(AVFrame *) &h->picture;
break;
case EXT_START_CODE:
break;
case USER_START_CODE:
break;
default:
if (stc >= SLICE_MIN_START_CODE &&
stc <= SLICE_MAX_START_CODE) {
init_get_bits(&s->gb, buf_ptr, input_size);
decode_slice_header(h, &s->gb);
}
break;
}
}
}
| 1threat |
int r4k_map_address (CPUMIPSState *env, hwaddr *physical, int *prot,
target_ulong address, int rw, int access_type)
{
uint8_t ASID = env->CP0_EntryHi & 0xFF;
int i;
for (i = 0; i < env->tlb->tlb_in_use; i++) {
r4k_tlb_t *tlb = &env->tlb->mmu.r4k.tlb[i];
target_ulong mask = tlb->PageMask | ~(TARGET_PAGE_MASK << 1);
target_ulong tag = address & ~mask;
target_ulong VPN = tlb->VPN & ~mask;
#if defined(TARGET_MIPS64)
tag &= env->SEGMask;
#endif
if ((tlb->G == 1 || tlb->ASID == ASID) && VPN == tag) {
int n = !!(address & mask & ~(mask >> 1));
if (!(n ? tlb->V1 : tlb->V0)) {
return TLBRET_INVALID;
}
if (rw == MMU_INST_FETCH && (n ? tlb->XI1 : tlb->XI0)) {
return TLBRET_XI;
}
if (rw == MMU_DATA_LOAD && (n ? tlb->RI1 : tlb->RI0)) {
return TLBRET_RI;
}
if (rw != MMU_DATA_STORE || (n ? tlb->D1 : tlb->D0)) {
*physical = tlb->PFN[n] | (address & (mask >> 1));
*prot = PAGE_READ;
if (n ? tlb->D1 : tlb->D0)
*prot |= PAGE_WRITE;
return TLBRET_MATCH;
}
return TLBRET_DIRTY;
}
}
return TLBRET_NOMATCH;
}
| 1threat |
Why does A resolve true, but B does not? : <p>Why does A resolve true, but B does not?</p>
<pre><code>Bosses = {
'A' : 5,
'B' : [5,6]
}
for key, value in Bosses.iteritems():
if value == 5:
print "Yes for " + key
else:
print "No for " + key
</code></pre>
| 0debug |
FetchFailedException or MetadataFetchFailedException when processing big data set : <p>When I run the parsing code with 1 GB dataset it completes without any error. But, when I attempt 25 gb of data at a time I get below errors. I'm trying to understand how can I avoid below failures. Happy to hear any suggestions or ideas.</p>
<p>Differnt errors,</p>
<pre><code>org.apache.spark.shuffle.MetadataFetchFailedException: Missing an output location for shuffle 0
org.apache.spark.shuffle.FetchFailedException: Failed to connect to ip-xxxxxxxx
org.apache.spark.shuffle.FetchFailedException: Error in opening FileSegmentManagedBuffer{file=/mnt/yarn/nm/usercache/xxxx/appcache/application_1450751731124_8446/blockmgr-8a7b17b8-f4c3-45e7-aea8-8b0a7481be55/08/shuffle_0_224_0.data, offset=12329181, length=2104094}
</code></pre>
<p>Cluster Details:</p>
<blockquote>
<p>Yarn: 8 Nodes<br>
Total cores: 64<br>
Memory: 500 GB<br>
Spark Version: 1.5 </p>
</blockquote>
<p>Spark submit statement:</p>
<pre><code>spark-submit --master yarn-cluster \
--conf spark.dynamicAllocation.enabled=true \
--conf spark.shuffle.service.enabled=true \
--executor-memory 4g \
--driver-memory 16g \
--num-executors 50 \
--deploy-mode cluster \
--executor-cores 1 \
--class my.parser \
myparser.jar \
-input xxx \
-output xxxx \
</code></pre>
<p>One of stack trace:</p>
<pre><code>at org.apache.spark.MapOutputTracker$$anonfun$org$apache$spark$MapOutputTracker$$convertMapStatuses$2.apply(MapOutputTracker.scala:460)
at org.apache.spark.MapOutputTracker$$anonfun$org$apache$spark$MapOutputTracker$$convertMapStatuses$2.apply(MapOutputTracker.scala:456)
at scala.collection.TraversableLike$WithFilter$$anonfun$foreach$1.apply(TraversableLike.scala:772)
at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:108)
at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:771)
at org.apache.spark.MapOutputTracker$.org$apache$spark$MapOutputTracker$$convertMapStatuses(MapOutputTracker.scala:456)
at org.apache.spark.MapOutputTracker.getMapSizesByExecutorId(MapOutputTracker.scala:183)
at org.apache.spark.shuffle.hash.HashShuffleReader.read(HashShuffleReader.scala:47)
at org.apache.spark.rdd.ShuffledRDD.compute(ShuffledRDD.scala:90)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:297)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:264)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:297)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:264)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
at org.apache.spark.scheduler.Task.run(Task.scala:88)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
| 0debug |
How to deploy simultaneously several critical bugs with gitflow process as soon as possible? : So we use the gitflow process for a safe and sound CID
(https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow)
But something's wrong..
Lets say we have 10 critical bugs on prod - they must be fixed asap.
So 10 bugs are assigned to 10 devs.
Dev 1 creates a hotfix 0.0.1, commits the fix to it, fix gets uploaded to staging env and handovered to QA for verifing.
In that time dev 2 wants to create hotfix 0.0.2 for his bug, but he cant as gitflow forbids creating new hotfix if one exists already.
So he either have to wait for closing hotfix/0.0.1 or commit to the same hotfix.
Of course the normal choice is to commit to that hotfix/0.0.1, because his bug is critical and cant wait fix for bug 1
So does every other 10 devs with their 10 critical bugs.
QA verifies bug 1 and confirm for deployment.
But hotfix can't be closed and deployed, because the other 9 bugs are not tested or just not working
So to be closed, every bug in that hotfix must be working and confirmed.
In our case this takes time, a lot of time - 1,2 weeks, luckily
- as more and more things needs to be fixed asap on production.
So devs commit to that branch more and more, getting the first bugs to be put on hold even more.
So eventually, after all those bugs are fixed and confirmed it is time to finally close the hotfix and deploy those critical bugs on prod...with quite of a big time delay.
But there is also another big problem - THE MERGE with dev branch, where other devs do their work (like minor bugfixings for next release). A horrible, several-hours lasting merge.
So we obviosly do something wrong...what could be a solution for this?
For our hotfixes to be on time and to not have terrible merges to dev
One solution we were thinking, is to put a limit in the hotfix for the number of bugs which it should contain
- for example 5 bugs max, other bugs must wait until those are fixed
This, though, means that only lead-dev should commit to hotfix, as he must ensure the limit (it is hard to control otherwise)
But this way bugs are still put on hold and fast-deployment is not achieved
What would be the normal procedure? Please share your ideas. | 0debug |
Failed to execute 'createElement' on 'Document': The result must not have children : <p>I've been using custom elements v1 for a while now via a <a href="https://github.com/WebReflection/document-register-element" rel="noreferrer">polyfill</a>. Chrome 54 (the first version with a native v1 implementation) started throwing errors when initializing my elements:</p>
<blockquote>
<p>DOMException: Failed to execute 'createElement' on 'Document': The result must not have children</p>
</blockquote>
<p>The offending line is a simple:</p>
<pre><code>let el = document.createElement('my-custom-element');
</code></pre>
| 0debug |
static int frame_start(MpegEncContext *s)
{
int ret;
if (s->pict_type != AV_PICTURE_TYPE_B && s->last_picture_ptr &&
s->last_picture_ptr != s->next_picture_ptr &&
s->last_picture_ptr->f.buf[0]) {
ff_mpeg_unref_picture(s, s->last_picture_ptr);
}
s->current_picture_ptr->f.pict_type = s->pict_type;
s->current_picture_ptr->f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;
ff_mpeg_unref_picture(s, &s->current_picture);
if ((ret = ff_mpeg_ref_picture(s, &s->current_picture,
s->current_picture_ptr)) < 0)
return ret;
if (s->pict_type != AV_PICTURE_TYPE_B) {
s->last_picture_ptr = s->next_picture_ptr;
if (!s->droppable)
s->next_picture_ptr = s->current_picture_ptr;
}
if (s->last_picture_ptr) {
ff_mpeg_unref_picture(s, &s->last_picture);
if (s->last_picture_ptr->f.buf[0] &&
(ret = ff_mpeg_ref_picture(s, &s->last_picture,
s->last_picture_ptr)) < 0)
return ret;
}
if (s->next_picture_ptr) {
ff_mpeg_unref_picture(s, &s->next_picture);
if (s->next_picture_ptr->f.buf[0] &&
(ret = ff_mpeg_ref_picture(s, &s->next_picture,
s->next_picture_ptr)) < 0)
return ret;
}
if (s->picture_structure!= PICT_FRAME) {
int i;
for (i = 0; i < 4; i++) {
if (s->picture_structure == PICT_BOTTOM_FIELD) {
s->current_picture.f.data[i] +=
s->current_picture.f.linesize[i];
}
s->current_picture.f.linesize[i] *= 2;
s->last_picture.f.linesize[i] *= 2;
s->next_picture.f.linesize[i] *= 2;
}
}
if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
s->dct_unquantize_intra = s->dct_unquantize_mpeg2_intra;
s->dct_unquantize_inter = s->dct_unquantize_mpeg2_inter;
} else if (s->out_format == FMT_H263 || s->out_format == FMT_H261) {
s->dct_unquantize_intra = s->dct_unquantize_h263_intra;
s->dct_unquantize_inter = s->dct_unquantize_h263_inter;
} else {
s->dct_unquantize_intra = s->dct_unquantize_mpeg1_intra;
s->dct_unquantize_inter = s->dct_unquantize_mpeg1_inter;
}
if (s->dct_error_sum) {
assert(s->avctx->noise_reduction && s->encoding);
update_noise_reduction(s);
}
return 0;
}
| 1threat |
Installed and Activate plugin – but nothing different and no amp pages detected : I have just installed and activated the plugin. All good no issues. I cleared cache and checked my site on a mobile device to see how it now displays and there is no difference.Is there more I need to do after activating the plugin. All replies will be most appreciated. | 0debug |
Marshalling LocalDate using JAXB : <p>I'm building a series of linked classes whose instances I want to be able to marshall to XML so I can save them to a file and read them in again later.</p>
<p>At present I'm using the following code as a test case:</p>
<pre><code>import javax.xml.bind.annotation.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.time.LocalDate;
public class LocalDateExample
{
@XmlRootElement
private static class WrapperTest {
public LocalDate startDate;
}
public static void main(String[] args) throws JAXBException
{
WrapperTest wt = new WrapperTest();
LocalDate ld = LocalDate.of(2016, 3, 1);
wt.startDate = ld;
marshall(wt);
}
public static void marshall(Object jaxbObject) throws JAXBException
{
JAXBContext context = JAXBContext.newInstance(jaxbObject.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(jaxbObject, System.out);
}
}
</code></pre>
<p>The XML output is:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<wrapperTest>
<startDate/>
</wrapperTest>
</code></pre>
<p>Is there a reason why the <code>startDate</code> element is empty? I would like it to contain the string representation of the date (i.e. <code>toString()</code>). Do I need to write some code of my own in order to do this?</p>
<p>The output of <code>java -version</code> is:</p>
<pre><code>openjdk version "1.8.0_66-internal"
OpenJDK Runtime Environment (build 1.8.0_66-internal-b17)
OpenJDK 64-Bit Server VM (build 25.66-b17, mixed mode)
</code></pre>
| 0debug |
error in calling function in if condition : i have a very basic question in C++. I m calling the login() function in if condition and its giving me the error at time of compilation.
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
void login();
int main()
{
string login;
int passcode;
cout << "login ";
cin >> login;
cout << "passcode ";
cin >> passcode;
if(login == "admin" && passcode == 123)
{
login();
}
else
{
cout << "It's not the Correct Passcode ";
}
return 0;
system("pause");
} // main()
void login()
{
cout << "You've successfully Logged into the Software ";
return ;
}
| 0debug |
Download data from a jupyter server : <p>I'm using ipython notebook by connecting to a server
I don't know how to download a thing (data frame, .csv file,... for example) programatically to my local computer. Because I can't specific declare the path like C://user//... It will be downloaded to their machine not mine</p>
| 0debug |
static int smacker_decode_tree(GetBitContext *gb, HuffContext *hc, uint32_t prefix, int length)
{
if(!get_bits1(gb)){
if(hc->current >= 256){
av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n");
if(length){
hc->bits[hc->current] = prefix;
hc->lengths[hc->current] = length;
} else {
hc->bits[hc->current] = 0;
hc->lengths[hc->current] = 0;
hc->values[hc->current] = get_bits(gb, 8);
hc->current++;
if(hc->maxlength < length)
hc->maxlength = length;
return 0;
} else {
int r;
length++;
r = smacker_decode_tree(gb, hc, prefix, length);
if(r)
return r;
return smacker_decode_tree(gb, hc, prefix | (1 << (length - 1)), length);
| 1threat |
Uncaught TypeError: this.is is not a function : <p>I am getting error on <code>this.is</code>. is there any alternatives?</p>
<pre><code> function UpdateTotalPrice() {
$('input[type=checkbox]').each(function () {
var id = this.id;
if (id.indexOf("chkSelected") > -1) {
if (this.checked && this.is(':disabled')==false) {
// alert(id);
getPrice(this);
}
}
});
}
</code></pre>
| 0debug |
static void qmp_serialize(void *native_in, void **datap,
VisitorFunc visit, Error **errp)
{
QmpSerializeData *d = g_malloc0(sizeof(*d));
d->qov = qmp_output_visitor_new(&d->obj);
visit(d->qov, &native_in, errp);
*datap = d;
}
| 1threat |
Suppress warning for both pycharm and pylint : <p>I use PyCharm to write code and I also have CI server configured to run PyLint on every PR. The problem is PyCharm and PyLint use different comments for warning suppression:</p>
<pre><code># noinspection PyMethodMayBeStatic
# pylint: disable=no-self-use
</code></pre>
<p>I don't like having two comments for both PyCharm and PyLint. Is there a way to configure PyLint to understand PyCharm comments or to configure PyCharm to understand PyLint comments?</p>
| 0debug |
Swift: RSA encrypt file or text : I use swift 3.
I encrypt message and save it to file. If when I decrypt file the same time of encrypt file, decrypt successful but if other time decrypt function return nil.
I use this class for encrypt and decrypt.
class Crypt{
// MARK: Public
// MARK: Internal
var publicKey, privateKey: SecKey?
var publicKeyData, privateKeyData: Data?
var statusCode: OSStatus?
let publicKeyAttr: [NSObject: NSObject] = [
kSecAttrIsPermanent:true as NSObject,
kSecAttrApplicationTag:"com.aparnik.ios.books.public".data(using: String.Encoding.utf8)! as NSObject,
kSecClass: kSecClassKey, // added this value
kSecReturnData: kCFBooleanTrue] // added this value
let privateKeyAttr: [NSObject: NSObject] = [
kSecAttrIsPermanent:true as NSObject,
kSecAttrApplicationTag:"com.aparnik.ios.books.private".data(using: String.Encoding.utf8)! as NSObject,
kSecClass: kSecClassKey, // added this value
kSecReturnData: kCFBooleanTrue] // added this value
// MARK: Private
// MARK: Initializer
init() {
self.generateRSAKey()
}
// MARK: Function
fileprivate func generateRSAKey() {
var keyPairAttr = [NSObject: NSObject]()
keyPairAttr[kSecAttrKeyType] = kSecAttrKeyTypeRSA
keyPairAttr[kSecAttrKeySizeInBits] = 1024 as NSObject
keyPairAttr[kSecPublicKeyAttrs] = publicKeyAttr as NSObject
keyPairAttr[kSecPrivateKeyAttrs] = privateKeyAttr as NSObject
statusCode = SecKeyGeneratePair(keyPairAttr as CFDictionary, &publicKey, &privateKey)
if statusCode == noErr && self.publicKey != nil && self.privateKey != nil {
print("Key pair generated OK")
var resultPublicKey: AnyObject?
var resultPrivateKey: AnyObject?
let statusPublicKey = SecItemCopyMatching(publicKeyAttr as CFDictionary, &resultPublicKey)
let statusPrivateKey = SecItemCopyMatching(privateKeyAttr as CFDictionary, &resultPrivateKey)
if statusPublicKey == noErr {
if let publicKeyData = resultPublicKey as? Data {
self.publicKeyData = publicKeyData
// let publicKeyXor = xor(publicKeyData)
//print("Public Key: \((publicKeyData.base64EncodedString()))")
//print("Public Key xor: \(publicKeyXor.base64EncodedString())")
}
}
if statusPrivateKey == noErr {
if let privateKey = resultPrivateKey as? Data {
self.privateKeyData = privateKey
//print("Private Key: \((privateKey.base64EncodedString()))"
}
}
} else {
//print("Error generating key pair: \(String(describing: statusCode))")
}
}
func xor() -> Data{
var publicKeyXor: Data = Data()
if (self.publicKeyData != nil) {
//print("Public Key: \((publicKeyData.base64EncodedString()))")
//print("Public Key xor: \(publicKeyXor.base64EncodedString())")
publicKeyXor = self.publicKeyData!
let base: Int = 53
let length: Int = 40
let magic: Int = 95
for i in 0..<length{
let index = i + base
publicKeyXor[index] = self.publicKeyData![magic] ^ self.publicKeyData![index]
}
}
return publicKeyXor
}
// decrypt
func decryptWithRSAKey(_ encryptedData: Data, padding: SecPadding = .PKCS1, rsaKeyRef: SecKey? = nil) -> Data? {
let rsaKeyRef = rsaKeyRef ?? self.privateKey!
let blockSize = SecKeyGetBlockSize(rsaKeyRef)
let dataSize = encryptedData.count / MemoryLayout<UInt8>.size
var encryptedDataAsArray = [UInt8](repeating: 0, count: dataSize)
(encryptedData as NSData).getBytes(&encryptedDataAsArray, length: dataSize)
var decryptedData = [UInt8](repeating: 0, count: 0)
var idx = 0
while (idx < encryptedDataAsArray.count ) {
var idxEnd = idx + blockSize
if ( idxEnd > encryptedDataAsArray.count ) {
idxEnd = encryptedDataAsArray.count
}
var chunkData = [UInt8](repeating: 0, count: blockSize)
for i in idx..<idxEnd {
chunkData[i-idx] = encryptedDataAsArray[i]
}
var decryptedDataBuffer = [UInt8](repeating: 0, count: blockSize)
var decryptedDataLength = blockSize
let status = SecKeyDecrypt(rsaKeyRef, padding, chunkData, idxEnd-idx, &decryptedDataBuffer, &decryptedDataLength)
if ( status != noErr ) {
return nil
}
let finalData = removePadding(decryptedDataBuffer)
decryptedData += finalData
idx += blockSize
}
return Data(bytes: UnsafePointer<UInt8>(decryptedData), count: decryptedData.count)
}
// remove padding
func removePadding(_ data: [UInt8]) -> [UInt8] {
var idxFirstZero = -1
var idxNextZero = data.count
for i in 0..<data.count {
if ( data[i] == 0 ) {
if ( idxFirstZero < 0 ) {
idxFirstZero = i
} else {
idxNextZero = i
break
}
}
}
if ( idxNextZero-idxFirstZero-1 == 0 ) {
idxNextZero = idxFirstZero
idxFirstZero = -1
}
var newData = [UInt8](repeating: 0, count: idxNextZero-idxFirstZero-1)
for i in idxFirstZero+1..<idxNextZero {
newData[i-idxFirstZero-1] = data[i]
}
return newData
}
// encrypt
func encryptWithRSAKey(_ data: Data, padding: SecPadding = .PKCS1, rsaKeyRef: SecKey? = nil) -> Data? {
let rsaKeyRef = rsaKeyRef ?? self.publicKey!
let blockSize = SecKeyGetBlockSize(rsaKeyRef)
let dataSize = data.count / MemoryLayout<UInt8>.size
let maxChunkSize = padding==SecPadding.OAEP ? (blockSize - 42) : (blockSize - 11)
var dataAsArray = [UInt8](repeating: 0, count: dataSize)
(data as NSData).getBytes(&dataAsArray, length: dataSize)
var encryptedData = [UInt8](repeating: 0, count: 0)
var idx = 0
while (idx < dataAsArray.count ) {
var idxEnd = idx + maxChunkSize
if ( idxEnd > dataAsArray.count ) {
idxEnd = dataAsArray.count
}
var chunkData = [UInt8](repeating: 0, count: maxChunkSize)
for i in idx..<idxEnd {
chunkData[i-idx] = dataAsArray[i]
}
var encryptedDataBuffer = [UInt8](repeating: 0, count: blockSize)
var encryptedDataLength = blockSize
let status = SecKeyEncrypt(rsaKeyRef, padding, chunkData, idxEnd-idx, &encryptedDataBuffer, &encryptedDataLength)
if ( status != noErr ) {
NSLog("Error while encrypting: %i", status)
return nil
}
encryptedData += encryptedDataBuffer
idx += maxChunkSize
}
return Data(bytes: UnsafePointer<UInt8>(encryptedData), count: encryptedData.count)
}
}
save this message to file:
let message = "This is my message. asdfl;jas f;lkajsdf la;skfj asd;lkfj sa;dlkfjsad ;lkfj dsal;kfj daslk;fjds flkjas dfjkdfgjkhdfs gjklsdf lkgjhdfs klgj dfskljg fdslkjg dsfjklg dfskjlg dfskljg fdskljg fdskjlgn dfsjlknv sflkdjnv ldksfjnv dfsjnvdkfjsghlfsjkdgh fdskljgh dsfkljgh dfslkjghdljkfs sdfkljsadf dsaf;lkasdjf sad;lfjk as;ldkfjas d;flkjasd flk;asdf lkjha sdflhjka sdklgha fkljgh fsdkljg alkjfh aslkjdf asldkjfh asdljkfasdlkjfhas ldfh ash aslkj asdlkj aslkjchads lkjchadslkfjhsadlkfjhsad flkjasdh flkjashdf lkjadhsf lkjasdhf lkjashdf lkjasdhf lkadsjfhadslkfjhiuwlhoewiqufhopweif asjkbdsa kjfasdlkfja sdljkfhs alkjfh adsjkfhas ldfkjhas ldkfjhajlsfh alsjdfhadlsfhlasjdkfjhsad fljkls "
let encryptData: Data? = self.crypt.encryptWithRSAKey(message.data(using: .utf8)!)
let fileName = "file.enc"
let dir = try? FileManager.default.url(for: .documentDirectory,
in: .userDomainMask, appropriateFor: nil, create: false)
if let fileURL = dir?.appendingPathComponent(fileName).appendingPathExtension("dgk") {
// Write to the file Test
do {
// try encry.write(to: fileURL, atomically: true, encoding: .utf8)
try encryptData?.write(to: fileURL)
} catch {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
}
if I decrypt file at this time decrypt is success. but when I close the program and open it and decrypt file, decrypt method has been failed.
if let fileURL = dir?.appendingPathComponent(fileName).appendingPathExtension("dgk") {
var encryptDataFromFile: Data?
do {
encryptDataFromFile = try Data(contentsOf: fileURL)
if let decryptData: Data = self.crypt.decryptWithRSAKey(encryptDataFromFile!){
let decryptString: String = String(data: decryptData, encoding: .utf8)!
print(decryptString)
}
exit(0)
} catch {
print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
} | 0debug |
Inheritance student, undergrad and gradstudent code : For a class project I was asked to create three codes. First the student class containing 3 Parameters. Name(String), TestScores( int array), Grade(String). An Empty Constructor- sets the Name and Grade to empty Strings. The TestScores Array will be created with 3 zeros. Another Constructor(String n, int[] tests, String g)- This will set the name, testScores, and grade. Three methods getName()- Returns the Name, getGrade()- Returns the Grade, setGrade()- Sets the Grade, and getTestAverage()- returns the average of the test scores. The method computeGrade()-If the average is greater than or equal to 65, the grade is a "Pass". Otherwise it is a "Fail". The second class is called UnderGrad- This class is a subclass of Student. We had to create an Empty Constructor and another Constructor(String n, int[] tests, String g).We were instructed to override the computeGrade() method so that an UnderGrad() student must get a 70 or higher to pass. The third class is the GradStudent- is a subclass of Student. We have to create 1 instance variable- int MyGradID. An empty Constructor Remember to call super and set the ID to 0. And another constructor(String n, int[] tests, String g, int id)- Remember to call the super constructor and set ID. We had to write the method getId()-returns the ID number. Again we needed to override the computeGrade() method-If if the average is greater than or equal to 65, the grade is a "Pass". Otherwise it is a "Fail". If the test average is higher than 90, the grade should be "Pass with distinction".
I have great difficulty with this task. I attached the GradStudent code. can you find the errors please. I don't fully understand how to override the superclass private instance variables.
public class GradStudent extends Student
{
private int MyGradID;
public void GradStudent()
{
super();
MyGradID= 0;
}
public void GradStudent(String n, int[]tests,String g, int id)
{
super(n,tests,g);
MyGradId = id;
}
public int getId()
{
return MyGradId;
}
public void computeGrade()
{
if(testScores.getTestAverage>=65)
{
super.setGrade("Pass");
}
else if (testScores.getTestAverage>90)
{
grade = "Pass with distinction";
}
} | 0debug |
static int ram_save_setup(QEMUFile *f, void *opaque)
{
RAMBlock *block;
int64_t ram_pages = last_ram_offset() >> TARGET_PAGE_BITS;
migration_bitmap = bitmap_new(ram_pages);
bitmap_set(migration_bitmap, 0, ram_pages);
migration_dirty_pages = ram_pages;
mig_throttle_on = false;
dirty_rate_high_cnt = 0;
if (migrate_use_xbzrle()) {
qemu_mutex_lock_iothread();
XBZRLE.cache = cache_init(migrate_xbzrle_cache_size() /
TARGET_PAGE_SIZE,
TARGET_PAGE_SIZE);
if (!XBZRLE.cache) {
qemu_mutex_unlock_iothread();
DPRINTF("Error creating cache\n");
return -1;
}
qemu_mutex_init(&XBZRLE.lock);
qemu_mutex_unlock_iothread();
XBZRLE.encoded_buf = g_try_malloc0(TARGET_PAGE_SIZE);
if (!XBZRLE.encoded_buf) {
DPRINTF("Error allocating encoded_buf\n");
return -1;
}
XBZRLE.current_buf = g_try_malloc(TARGET_PAGE_SIZE);
if (!XBZRLE.current_buf) {
DPRINTF("Error allocating current_buf\n");
g_free(XBZRLE.encoded_buf);
XBZRLE.encoded_buf = NULL;
return -1;
}
acct_clear();
}
qemu_mutex_lock_iothread();
qemu_mutex_lock_ramlist();
bytes_transferred = 0;
reset_ram_globals();
memory_global_dirty_log_start();
migration_bitmap_sync();
qemu_mutex_unlock_iothread();
qemu_put_be64(f, ram_bytes_total() | RAM_SAVE_FLAG_MEM_SIZE);
QTAILQ_FOREACH(block, &ram_list.blocks, next) {
qemu_put_byte(f, strlen(block->idstr));
qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));
qemu_put_be64(f, block->length);
}
qemu_mutex_unlock_ramlist();
ram_control_before_iterate(f, RAM_CONTROL_SETUP);
ram_control_after_iterate(f, RAM_CONTROL_SETUP);
qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
return 0;
}
| 1threat |
How to get the longest text in Html document using Jquery or javascript : Could someone help on the my issue.
I am having an HTML document like below,
<div id="customdiv">
<p>AAAAAA AAAAA AAAAA AAAAA AAAAA AAAA</p>
<p>AAAAAA</p>
<p>AAAAAA</p>
</div>
I need output like:
Largest value is:AAAAAA AAAAA AAAAA AAAAA AAAAA AAAA
Length:37 | 0debug |
Extract name of a file without its extension using php : <p>I upload a file say 'example.csv'...How do I store 'example' inside a variable using php so as to create a table in the database having the table name as 'example'?</p>
| 0debug |
How to get container id of a docker service : <p>I want to get a container ID of docker service.
Is there any command available for this ?</p>
<p>I tried </p>
<pre><code>docker service ps MyService
</code></pre>
<p>but this one only gives the service ID, I am interested in the container id in which the service is running</p>
| 0debug |
C++ Overload the subscript operator to call a function based on the type assigned : I have an object that has functions like "addString" and "addInteger". These functions add data to a JSON string. At the end, the JSON string can be obtained and sent out. How can this be made easier by overloading subscript operators to do the following?
jsonBuilder builder();
builder[ "string_value" ] = "Hello";
builder[ "int_value" ] = 5;
builder[ "another_string" ] = "Thank you"; | 0debug |
static av_cold int flashsv_encode_init(AVCodecContext *avctx)
{
FlashSVContext *s = avctx->priv_data;
s->avctx = avctx;
if (avctx->width > 4095 || avctx->height > 4095) {
av_log(avctx, AV_LOG_ERROR,
"Input dimensions too large, input must be max 4096x4096 !\n");
return AVERROR_INVALIDDATA;
}
memset(&s->zstream, 0, sizeof(z_stream));
s->last_key_frame = 0;
s->image_width = avctx->width;
s->image_height = avctx->height;
s->tmpblock = av_mallocz(3 * 256 * 256);
s->encbuffer = av_mallocz(s->image_width * s->image_height * 3);
if (!s->tmpblock || !s->encbuffer) {
av_log(avctx, AV_LOG_ERROR, "Memory allocation failed.\n");
return AVERROR(ENOMEM);
}
avctx->coded_frame = av_frame_alloc();
if (!avctx->coded_frame) {
flashsv_encode_end(avctx);
return AVERROR(ENOMEM);
}
return 0;
}
| 1threat |
my program is working corectly but I get a warning : guys.
I have allocated memory for a double pointer and I have populated it with some values.(1)
After that I created a function that populates the ints with 0
Than I have made a pointer to that function and crated another function that uses that pointer as an argument
I ran the program and it was working
But the problem was that I was getting a warning
"passing argument 1 of 'cheama_transforma0' makes pointer from integer without a cast"
This is my code:
#include <stdio.h>
#include <stdlib.h>
void printeaza_pointer(int **cacat){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
printf("%d\n",cacat[i][j]);
}
putchar('\n');
}
}
int transforma_in0(int **cacat){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
cacat[i][j] = 0;
}
}
return 0;
}
void cheama_transforma0(int (*p)(int **pointer)){
}
int main()
{
int (*p)(int **cacat);
int **pointer_d = (int **)malloc(sizeof(int*)*3);
for(int i = 0; i < 3; i++){
pointer_d[i] = (int *)malloc(sizeof(int)*3);
}
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
pointer_d[i][j] = 1;
}
}
p = transforma_in0;
printeaza_pointer(pointer_d);
cheama_transforma0(p(pointer_d));
printeaza_pointer(pointer_d);
return 0;
}
| 0debug |
db.execute('SELECT * FROM products WHERE product_id = ' + product_input) | 1threat |
xcode Resolve "Safe Area Layout" errors : <p><a href="https://i.stack.imgur.com/9r1EX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9r1EX.png" alt="Illegal Configuration - Safe Area Layout Guide before iOS 9.0"></a></p>
<p>What is the correct way to stop this error?</p>
<p>For now I'm merely unchecking "Use Safe Area Layout Guides" which allows me to compile the app without error.</p>
| 0debug |
How to run an existing stopped container and get inside the bash? : <p>I am a newbie to Docker, and I know that in order to run a container I can use the following command:</p>
<pre><code>docker run -it --name custom-container-name --hostname custom-hostname image-name bash
</code></pre>
<p>The previous command creates a container named <code>custom-container-name</code> which hostname is <code>custom-hostname</code>, and it uses the image <code>image-name</code>. I know that the <code>-it</code> flag gives me access to the <code>bash</code>. (please correct me if I am wrong)</p>
<p>Now, I have stopped this container, but I want use it again, so <strong>what is the command I should use to open this container again with its bash</strong>, as when I run the <code>docker run ...</code> command the first time it was created.</p>
| 0debug |
window.location.href = 'http://attack.com?user=' + user_input; | 1threat |
How is the Travis CI Github integration actually working? : <p>I am really only interested in how Github can display the Badge status of the passing / failed build. I has to access Travis somehow?</p>
| 0debug |
Is there a way to record the value of an index when a listener is being created, so that that same value is used when the listener function is called? : <p>When an event listener function is called, the value of the index is no longer the same value as when the listener was created</p>
<p>I'm creating all the markers and their listeners through iteration. however when 'infowindow.open(map, marker[i]);' is called after the iteration, 'i' has a different value and opens a different marker's infowindow. How can I make this point to the marker being clicked?</p>
<pre><code>google.maps.event.addListener(marker[i], 'click', function(){
infowindow.open(map, marker[i]);
}
</code></pre>
<p>I can see why this is happening but I'm not sure how to get around it. 'infowindow.open(map, marker[i]);' is not called until the marker is clicked, and by that stage i has a different value.</p>
| 0debug |
Parse XML File with PowerShell and if a value is found, copy file to a new location : <p>I have an application that outputs XML files during the life of an event in the software. I need to parse the XML files and once certain text are matched, move the file to another folder</p>
<p>The file name format of each XML file is: Event Owner (MEMS), Year (2020) and serial number (00012345). The software will write same file multiple time throughout the event so I need to look for specific items before taking any action.
I would prefer to do this in PowerShell if at all possible.</p>
<p>I need to find</p>
<pre><code> `<EventUnits>
<Unit>
<UnitCode>xxxxxxx></UnitCode>
</EventUnits>`
</code></pre>
<p>and </p>
<pre><code><EventDetails>
<EventCompletedTime>YYYY-MM-DD HH:MM:SS</EventCompletedTime>
</EventDetails>
</code></pre>
<p>Once UnitCode equals one of 4 unit codes and EventCompleted has a valid date and time, the file is moved to a different folder.</p>
| 0debug |
Is it possible to install Oracle 11g server version on windows 7 non server : I want to install oracle 11g server class on my windows 7 ( NON SERVER OS).
If it is possible then what step to follow client-server installation.
plz help. | 0debug |
int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
{
int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
if (bs->dirty_bitmap != NULL &&
(sector << BDRV_SECTOR_BITS) <= bdrv_getlength(bs)) {
return bs->dirty_bitmap[chunk];
} else {
return 0;
}
}
| 1threat |
static void isa_ne2000_cleanup(NetClientState *nc)
{
NE2000State *s = qemu_get_nic_opaque(nc);
s->nic = NULL;
}
| 1threat |
Change color of google map : I have ambeded my map in a website , Now I want to change color of google map to `dark` , as given in google maps. I am trying to do this but dont know where to given style I have to apply
my code of init map is .I think I have to change in this
_initMap: function() {
var self= this, options = this.options,
centerPosition = new google.maps.LatLng(options.latitude, options.longitude);
/**
* map
* @type {google.maps.Map}
*/
this.map = new google.maps.Map(this.element[0], {
zoom: parseFloat(options.zoom_level),
center: centerPosition,
minZoom: options.minZoom,
maxZoom: options.maxZoom
});
this.storePopupTmpl = mageTemplate($(options.storePopupTemplate).html());
/**
* infor windopw
* @type {google.maps.InfoWindow}
*/
this.infowindow = new google.maps.InfoWindow({
//maxWidth: 250,
//disableAutoPan: true,
maxWidth: 450,
minWidth: 350,
});
| 0debug |
static void vm_change_state_handler(void *opaque, int running,
RunState state)
{
GICv3ITSState *s = (GICv3ITSState *)opaque;
Error *err = NULL;
int ret;
if (running) {
return;
}
ret = kvm_device_access(s->dev_fd, KVM_DEV_ARM_VGIC_GRP_CTRL,
KVM_DEV_ARM_ITS_SAVE_TABLES, NULL, true, &err);
if (err) {
error_report_err(err);
}
if (ret < 0 && ret != -EFAULT) {
abort();
}
}
| 1threat |
I'm looking for help to display a part on my database according to my previous choices in the select buttons : <p>i study the web developpement and i'm actually stuck with a problem.</p>
<p>I have two select buttons in which my database is displayed, the concern being that I would like the second select button to display only the results based on the first one. A bit like if the first button select would have inside "Numbers" and "Letters" and the second in consequences would have inside "1" "2" "3" if in the first select button we choose "Numbers" and "a" "b" "c" if we choose "Letters". I currently only have the full display of my entire database in the second and it does not do the sorting. </p>
<p>I tried a lot of thing but not realy working this is why i come here to have some help or tips.</p>
<p>I'm currently working with symfony 3.4 and on ubuntu.</p>
<p>Here is the code for my first select button:</p>
<pre><code><select id="sel1" class="formDevis" >
<option> Cliquez pour choisir </option>
{% for categorie in categories %}
<option>{{ categorie.nomCategories }}
</option>
{% endfor %}
</select>
</code></pre>
<p>Then this is the code for the second select button:</p>
<pre><code><select id="prod1" class="formDevis">
<option> Cliquez pour choisir </option>
<option>Non spécifié</option>
{% for produit in produits %}
<option>{{ produit.nomProduits }}
</option>
{% endfor %}
</select>
</code></pre>
<p>And finaly here is the code i use in my controller:</p>
<pre><code>/**
* Lists all devis entities.
*
* @Route("/", name="admin_devis_index")
* @Method("GET")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$devis = $em->getRepository('DevisBundle:Devis')->findAll();
$produits = $em->getRepository('DevisBundle:Produits')->findAll();
$categories = $em->getRepository('DevisBundle:Categories')->findAll();
return $this->render('categories/devis.html.twig', array(
'produits' => $produits,
'devis' => $devis,
'categories' => $categories
));
}
</code></pre>
<p>I tried to have on the second button select the display of my database according to the first button select but I managed to have the complete display.</p>
| 0debug |
Bootstrap Datatables: Change cell color based on values : <p>I am getting json data from server and trying to display the datatable.</p>
<p>Code :</p>
<pre><code> var siteName = $("#stateType").val();
$(".jqueryDataTable").DataTable({
"sPaginationType" : "full_numbers",
"bProcessing" : false,
"bServerSide" : false,
"bJQueryUI" : true,
"bDestroy" : true,
"sAjaxSource" : "searchState",
"sServerMethod" : "POST",
"fnServerParams" : function(aoData) {
aoData.push({
"name" : "stateType",
"value" : siteName
});
},
"aoColumns" : [ {
"mData" : "stitcher"
}, {
"mData" : "state"
}, {
"mData" : "load"
}, {
"mData" : "sessionsActive"
}, {
"mData" : "sessionsPaused"
}, {
"mData" : "csmVersion"
}, {
"mData" : "serviceID"
} ]
});
</code></pre>
<p>I am able to display the data. but the requirement is I need to change the color of the state cell based on value?</p>
| 0debug |
What will be the output of this program and how? : <pre><code>#include<stdio.h>
#define ABS(a,b) \
do { \
(a>0) ? b = a : (b = -a); \
return b; \
}while(0) \
int main()
{
int a = -2, b;
ABS(a,b);
printf("a=%d b=%d\n", a, b);
}
</code></pre>
<p>I can't able to understand the output of this. Please explain. Thanks</p>
| 0debug |
how can i navigate to the next page in a for loop without failing the loop?i m trying to download all the pdfs : This is my code , I'm trying to download all the Pdf's from the webpage <https://iaeme.com/ijmet/index.asp> . The page has different links , inside each link there are multiple downloads and more pages , i m trying to navigate the next page and continue the loop . pls help !
package flow;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.NoSuchElementException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tools.ant.taskdefs.Java;
import org.apache.tools.ant.types.FileList.FileName;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Navigation;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.w3c.dom.Text;
import jxl.common.Assert;
//kindly ignore the imports
public class excel {
public static void main(String[] args) throws IOException, Exception {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\User_2\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver d=new ChromeDriver();
d.manage().window().maximize();
d.get("https://iaeme.com/ijmet/index.asp");
java.util.List<WebElement> catvalues=d.findElements(By.className("issue"));
for(int i=0;i<=catvalues.size();i++){
catvalues.get(i).click();
java.util.List<WebElement>
downcount=d.findElements(By.linkText("Download"));
System.out.println(downcount.size());
for(int k=1;k<=downcount.size();k++){
downcount.get(k).click();
Thread.sleep(5000);
}
d.navigate().back();
catvalues = d.findElements(By.className("issue"));
}
}
}
I tried different moethods which failed , kindly help
| 0debug |
Can't install pytorch with pip on Windows : <p>I'm trying to install Pytorch with Windows and I'm using the commands of the official site
<a href="https://pytorch.org/get-started/locally/" rel="noreferrer">https://pytorch.org/get-started/locally/</a></p>
<pre><code>pip3 install torch==1.2.0 torchvision==0.4.0 -f https://download.pytorch.org/whl/torch_stable.html
</code></pre>
<p>This is the command if I choose Windows, Cuda 10.0, and Python 3.7
But if I run this I get the error message:</p>
<pre><code>ERROR: Could not find a version that satisfies the requirement torch==1.2.0 (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2)
ERROR: No matching distribution found for torch==1.2.0
</code></pre>
<p>So why does this happen?
My pip is version 19.2 and I am in a newly installed python 3.7 environment</p>
| 0debug |
Is this std::ref behaviour logical? : <p>Consider this code:</p>
<pre><code>#include <iostream>
#include <functional>
int xx = 7;
template<class T>
void f1(T arg)
{
arg += xx;
}
template<class T>
void f2(T arg)
{
arg = xx;
}
int main()
{
int j;
j=100;
f1(std::ref(j));
std::cout << j << std::endl;
j=100;
f2(std::ref(j));
std::cout << j << std::endl;
}
</code></pre>
<p>When executed, this code outputs</p>
<pre><code>107
100
</code></pre>
<p>I would have expected the second value to be 7 rather than 100.</p>
<p>What am I missing?</p>
| 0debug |
static void pc_init_isa(MachineState *machine)
{
pci_enabled = false;
has_acpi_build = false;
smbios_defaults = false;
gigabyte_align = false;
smbios_legacy_mode = true;
has_reserved_memory = false;
option_rom_has_mr = true;
rom_file_has_mr = false;
if (!machine->cpu_model) {
machine->cpu_model = "486";
}
x86_cpu_change_kvm_default("kvm-pv-eoi", NULL);
enable_compat_apic_id_mode();
pc_init1(machine, TYPE_I440FX_PCI_HOST_BRIDGE, TYPE_I440FX_PCI_DEVICE);
}
| 1threat |
Please anyone tell me how to put this php myql query in proper way : <p>I have written the query below but there is no errors and no records are updated
please can anyone correct it.</p>
<pre><code>$db->query("INSERT INTO members (username, password, email)
VALUES ('$username', '$password', '$email')");
</code></pre>
| 0debug |
static void test_qemu_strtoull_hex(void)
{
const char *str = "0123";
char f = 'X';
const char *endptr = &f;
uint64_t res = 999;
int err;
err = qemu_strtoull(str, &endptr, 16, &res);
g_assert_cmpint(err, ==, 0);
g_assert_cmpint(res, ==, 0x123);
g_assert(endptr == str + strlen(str));
str = "0x123";
endptr = &f;
res = 999;
err = qemu_strtoull(str, &endptr, 0, &res);
g_assert_cmpint(err, ==, 0);
g_assert_cmpint(res, ==, 0x123);
g_assert(endptr == str + strlen(str));
}
| 1threat |
angular bootstrap dropdown to open on left : <p>I have used angular bootstrap dropdown successfully <a href="https://angular-ui.github.io/bootstrap/">link</a>.
But the problem it that the dropdown opens on the right side.
How can i make it to open on left?
Here is the markup and js i used from the given link.</p>
<p>Markup:</p>
<pre><code><div ng-controller="DropdownCtrl">
<!-- Single button with keyboard nav -->
<div class="btn-group" uib-dropdown keyboard-nav>
<button id="simple-btn-keyboard-nav" type="button" class="btn btn-primary" uib-dropdown-toggle>
Dropdown with keyboard navigation <span class="caret"></span>
</button>
<ul uib-dropdown-menu role="menu" aria-labelledby="simple-btn-keyboard-nav">
<li role="menuitem"><a href="#">Action</a></li>
<li role="menuitem"><a href="#">Another action</a></li>
<li role="menuitem"><a href="#">Something else here</a></li>
<li class="divider"></li>
<li role="menuitem"><a href="#">Separated link</a></li>
</ul>
</div>
</div>
</code></pre>
<p>js:</p>
<pre><code>angular.module('ui.bootstrap.demo').controller('DropdownCtrl', function ($scope, $log) {
$scope.items = [
'The first choice!',
'And another choice for you.',
'but wait! A third!'
];
$scope.status = {
isopen: false
};
$scope.toggled = function(open) {
$log.log('Dropdown is now: ', open);
};
$scope.toggleDropdown = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.status.isopen = !$scope.status.isopen;
};
$scope.appendToEl = angular.element(document.querySelector('#dropdown-long-content'));
});
</code></pre>
<p>please help</p>
| 0debug |
Is it bad to have 100+ classes in one element : <p>I am making some website and I thought if I make css for everything as each class it can be easier to change after something like extended bootstrap...</p>
<p>So I would have <code>font-size.css, text_colors.css etc</code></p>
<pre><code>.1px{font-size: 1px;} .2px{font-size: 2px;}....
.red{color: red;} .B4040{color: #B40404;}....
</code></pre>
<p>And then when I make div:</p>
<pre><code><div class="2px B40404 something_else"></div>
</code></pre>
| 0debug |
Having some trouble with a while loop in bash script : I'm trying to get the variables setup properly in my script. Basically the x and y variables should increment by 5 after each iteration of the loop. The a value should increment by one, and the loop should iterate $numResults amount of times.
The numResults variable is working fine and the loop does try to iterate that number of times. I'm encountering 4 sets of errors since that's the number stored in that variable. For my other variables, when I replace them with real numbers, then the program runs fine but just not with the variables in place.
#!/bin/bash
# An application that for each course with more than 50 students enrolled generates
# an advisory report to warn of over-enrollment. It generates a text file from a user-defined
# template which uses the following variables:
#
# • [[dept_code]]
# • [[dept_name]]
# • [[course_name]]
# • [[course_start]]
# • [[course_end]]
# • [[credit_hours]]
# • [[num_students]]
# • [[course_num]] (the course number as specified in the filename of the .crs file)
# • [[date]]
#
# Create a new user-specified subdirectory for files mkdir -p "$4"
numResults=`grep -rE --include \*.crs -e "^[5][1-9]$" -e "^[6-9][0-9]$" -e "^[1-9][0-9][0-9]$" ./data | gawk '{n++} END { print n }'`
let i=0; x=1 y=5 a=1 while [[ $i<="$numResults" ]] do
# Gets the course code and number to use as the output file name && stores course_num to the output file temporarily for retrieval file=`grep -rE --include \*.crs -e "^[5][1-9]$" -e "^[6-9][0-9]$" -e "^[1-9][0-9][0-9]$" "$1" | sed -E 's/.*([A-Z]{3})([0-9]{4})\.*crs:[0-9][0-9]/\1\2/g' | gawk 'NR==$a { print; echo "" }'` course=`echo $file | sed 's/[A-Z]//g'` (cat "$2"; echo ""; echo "$course";) > "$4/$file"
# Locate all files in the data directory with the .crs extension that also contain a line with
# only a string "51" - "999" and grabs the contents of that file and stores them to the new
# output file temporarily for retrieval grep -hrEB 4 --include \*.crs -e "^[5][1-9]$" -e "^[6-9][0-9]$" -e "^[1-9][0-9][0-9]$" "$1" | gawk 'NR==$x,NR==$y{print}' >> "$4"/$file
# Create variables to hold the dept and course info varCNum=`gawk -v n=6 '{saved[FNR % n] = $0} ENDFILE {if (FNR >= n) print saved[(FNR + 1) % n]}' "$4"/$file`
varDC=`gawk -v n=5 '{saved[FNR % n] = $1} ENDFILE {if (FNR >= n) print saved[(FNR + 1) % n]}' "$4"/$file` varDN=`gawk -v n=5 '{saved[FNR % n] = $0} ENDFILE {if (FNR >= n) print saved[(FNR + 1) % n]}' "$4"/$file | gawk '{for(i=2;i<=NF;i++){printf "%s", $i};}'`
varCN=`gawk -v n=4 '{saved[FNR % n] = $0} ENDFILE {if (FNR >= n) print saved[(FNR + 1) % n]}' "$4"/$file` varCS=`gawk -v n=3 '{saved[FNR % n] = $2} ENDFILE {if (FNR >= n) print saved[(FNR + 1) % n]}' "$4"/$file` varCE=`gawk -v n=3 '{saved[FNR % n] = $3} ENDFILE {if (FNR >= n) print saved[(FNR + 1) % n]}' "$4"/$file` varCH=`gawk
-v n=2 '{saved[FNR % n] = $0} ENDFILE {if (FNR >= n) print saved[(FNR + 1) % n]}' "$4"/$file`
varNS=`gawk -v n=1 '{saved[FNR % n] = $0} ENDFILE {if (FNR >= n) print saved[(FNR + 1) % n]}' "$4"/$file`
# Substitute the variables into the output file && and clean up sed -E "s/\[\[ dept_code \]\]/$varDC/g; s/\[\[ dept_name \]\]/$varDN/g; s@\[\[ course_name \]\]@$varCN@g; s@\[\[ course_start \]\]@$varCS@g; s@\[\[ course_end \]\]@$varCE@g; s@\[\[ credit_hours \]\]@$varCH@g; s@\[\[ num_students \]\]@$varNS@g; s@\[\[ course_num \]\]@$varCNum@g; s@\[\[ date \]\]@$varDate@g;" "$4"/$file | sed -e :a -e '$d;N;2,6ba' -e 'P;D'
let i+=1 let x+=5 let y+=5 let a+=1
done
I'm passing in the following arguments to my script:
$ ./data assign4.template 12/16/2021 ./output
Which gives the following error message "./assign4.sh: line 31: ./output/: Is a directory
./assign4.sh: line 37: ./output/: Is a directory
gawk: warning: command line argument `./output/' is a directory: skipped" | 0debug |
void helper_ocbi(CPUSH4State *env, uint32_t address)
{
memory_content **current = &(env->movcal_backup);
while (*current)
{
uint32_t a = (*current)->address;
if ((a & ~0x1F) == (address & ~0x1F))
{
memory_content *next = (*current)->next;
cpu_stl_data(env, a, (*current)->value);
if (next == NULL)
{
env->movcal_backup_tail = current;
}
free (*current);
*current = next;
break;
}
}
}
| 1threat |
static int cow_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVCowState *s = bs->opaque;
struct cow_header_v2 cow_header;
int bitmap_size;
int64_t size;
int ret;
ret = bdrv_pread(bs->file, 0, &cow_header, sizeof(cow_header));
if (ret < 0) {
goto fail;
}
if (be32_to_cpu(cow_header.magic) != COW_MAGIC) {
error_setg(errp, "Image not in COW format");
ret = -EINVAL;
goto fail;
}
if (be32_to_cpu(cow_header.version) != COW_VERSION) {
char version[64];
snprintf(version, sizeof(version),
"COW version %" PRIu32, cow_header.version);
error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
bs->device_name, "cow", version);
ret = -ENOTSUP;
goto fail;
}
size = be64_to_cpu(cow_header.size);
bs->total_sectors = size / 512;
pstrcpy(bs->backing_file, sizeof(bs->backing_file),
cow_header.backing_file);
bitmap_size = ((bs->total_sectors + 7) >> 3) + sizeof(cow_header);
s->cow_sectors_offset = (bitmap_size + 511) & ~511;
qemu_co_mutex_init(&s->lock);
return 0;
fail:
return ret;
}
| 1threat |
Why does the count variable has to be defined outside the curly brackets of the for loop? (Refer to the codes) : Please read till the end, so that you will understand the problem completely.
As you can see in the two below codes, I get different results when I use the count variable outside the for loop curly brackets. Can someone please tell me why?
As you can see the first result only prints three i values.
So my question is why the count variable can not be defined in the curly brackets of the for loop as I have done in the first code. Please help. Thank you.
public class Main {
public static void main(String[] args) {
int count = 0;
for (int i=0; i<5; i++) {
System.out.println(i);
count++;
if (count == 3) {
break;
}
}
}
}
public class Main {
public static void main(String[] args) {
for (int i=0; i<5; i++) {
int count = 0;
System.out.println(i);
count++;
if (count == 3) {
break;
}
}
}
} | 0debug |
Split a Javascript class (ES6) over multiple files? : <p>I have a Javascript class (in ES6) that is getting quite long. To organize it better I'd like to split it over 2 or 3 different files. How can I do that?</p>
<p>Currently it looks like this in a single file:</p>
<pre><code>class foo extends bar {
constructor(a, b) {} // Put in file 1
methodA(a, b) {} // Put in file 1
methodB(a, b) {} // Put in file 2
methodC(a, b) {} // Put in file 2
}
</code></pre>
<p>Thanks!</p>
| 0debug |
If statement help (noob) : <p>I was trying to grab the first character from user entry, and determine it to be a vowel or not. I am very new, and have been struggling with this for a while. I am trying to add all vowels to the variable 'vowel', and not only will that obviously not work, but I feel like I am going the long way. Any help at all is vastly appreciated as I am very new to this.</p>
<pre><code>entry = scanner.nextLine();
letters = entry.substring(0,1);
holder = entry.substring(1);
vowels = "A";
if (entry.substring(0,1).equals(vowels)) {
pigLatinVowel = entry + "way";
System.out.println(pigLatinVowel);
}
</code></pre>
| 0debug |
Why memoization instead of memoRization? : <p>I am curious why the term "memoization" was coined instead of "memorization" historically? Did someone just forget the letter "r" and it was too late to change it? Or, if it is on purpose, what's the reasoning? Is there some story behind it?</p>
| 0debug |
static av_cold int cinvideo_decode_end(AVCodecContext *avctx)
{
CinVideoContext *cin = avctx->priv_data;
int i;
if (cin->frame.data[0])
avctx->release_buffer(avctx, &cin->frame);
for (i = 0; i < 3; ++i)
av_free(cin->bitmap_table[i]);
return 0;
}
| 1threat |
static int usb_bt_handle_data(USBDevice *dev, USBPacket *p)
{
struct USBBtState *s = (struct USBBtState *) dev->opaque;
int ret = 0;
if (!s->config)
goto fail;
switch (p->pid) {
case USB_TOKEN_IN:
switch (p->devep & 0xf) {
case USB_EVT_EP:
ret = usb_bt_fifo_dequeue(&s->evt, p);
break;
case USB_ACL_EP:
ret = usb_bt_fifo_dequeue(&s->acl, p);
break;
case USB_SCO_EP:
ret = usb_bt_fifo_dequeue(&s->sco, p);
break;
default:
goto fail;
}
break;
case USB_TOKEN_OUT:
switch (p->devep & 0xf) {
case USB_ACL_EP:
usb_bt_fifo_out_enqueue(s, &s->outacl, s->hci->acl_send,
usb_bt_hci_acl_complete, p);
break;
case USB_SCO_EP:
usb_bt_fifo_out_enqueue(s, &s->outsco, s->hci->sco_send,
usb_bt_hci_sco_complete, p);
break;
default:
goto fail;
}
break;
default:
fail:
ret = USB_RET_STALL;
break;
}
return ret;
}
| 1threat |
int av_buffersrc_add_frame(AVFilterContext *ctx, AVFrame *frame)
{
BufferSourceContext *s = ctx->priv;
AVFrame *copy;
int ret;
if (!frame) {
s->eof = 1;
return 0;
} else if (s->eof)
return AVERROR(EINVAL);
switch (ctx->outputs[0]->type) {
case AVMEDIA_TYPE_VIDEO:
CHECK_VIDEO_PARAM_CHANGE(ctx, s, frame->width, frame->height,
frame->format);
break;
case AVMEDIA_TYPE_AUDIO:
CHECK_AUDIO_PARAM_CHANGE(ctx, s, frame->sample_rate, frame->channel_layout,
frame->format);
break;
default:
return AVERROR(EINVAL);
}
if (!av_fifo_space(s->fifo) &&
(ret = av_fifo_realloc2(s->fifo, av_fifo_size(s->fifo) +
sizeof(copy))) < 0)
return ret;
if (!(copy = av_frame_alloc()))
return AVERROR(ENOMEM);
av_frame_move_ref(copy, frame);
if ((ret = av_fifo_generic_write(s->fifo, ©, sizeof(copy), NULL)) < 0) {
av_frame_move_ref(frame, copy);
av_frame_free(©);
return ret;
}
return 0;
}
| 1threat |
How to detect Windows 10 light/dark mode in Win32 application? : <p>A bit of context: <a href="https://sciter.com" rel="noreferrer">Sciter</a> (pure win32 application) is already capable to render UWP alike UIs:</p>
<p>in dark mode:
<a href="https://i.stack.imgur.com/mXJ6w.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/mXJ6w.jpg" alt="in dark mode"></a></p>
<p>in light mode:
<a href="https://i.stack.imgur.com/wNJi6.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/wNJi6.jpg" alt="in light mode"></a></p>
<p>Windows 10.1803 introduces Dark/Light switch in Settings applet <a href="https://www.digitaltrends.com/computing/how-to-enable-dark-mode-in-windows-10/" rel="noreferrer">as seen here for example</a>.</p>
<p>Question: how do I determine current type of that "app mode" in Win32 application? </p>
| 0debug |
Is Facebook's Graph API using GraphQL? : <p>They said Facebook used GraphLQ since 2012. Is Facebook's Graph API using GraphQL? If not, is there any public Facebook's API using GraphQL?</p>
<p>Do we need versioning for our APIs if we use GraphQL server?</p>
| 0debug |
appending from a list of strings : i would like to do a stopword removal.
I have a list which consists of about 15`000 strings. those strings are little texts. my code is the following:
h=[]
for w in clean.split():
if w not in cachedStopWords:
h.append(w)
if w in cachedStopWords:
h.append(" ")
print(h)
I understand that the .split() is necessary so that not every whole string is being compared to the list of stopwords. But it does not seem to work bc it cannot split lists. (Without any kind of splitting h = clean, bc nothing matches obviously.)
Does anyone have an idea how else i could split the different strings in the list while still perserving the different cases? | 0debug |
why I am not getting results from my uncompressing? : <p>I am using a Dragonfly BSD system and I need to uncompress a folder for configuration purpose. I could not find results, the compressed file was still there without the uncompressed folder I should find. To test if the problem was something more specific I tried the same tar -xf but later also adding <em>v (verbose)</em> option with an ordinary text file but what I found was the <strong>tar</strong> showing me the uncompressed file when on the verbose, meanwhile I couldn't find it (by ls command) neither open it.</p>
<p><a href="https://i.stack.imgur.com/F9KAM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F9KAM.jpg" alt="enter image description here"></a></p>
| 0debug |
How will I pass ranges instead of iterator-pairs in C++20? : <p>I've heard that C++20 will support acting on ranges, not just begin+end iterator pairs. Does that mean that, in C++20, I'll be able to write:</p>
<pre><code>std::vector<int> vec = get_vector_from_somewhere();
std::sort(vec);
std::vector<float> halves;
halves.reserve(vec.size());
std::transform(
vec, std::back_inserter(halves),
[](int x) { return x * 0.5; }
);
</code></pre>
<p>?</p>
| 0debug |
Content URI passed in EXTRA_STREAM appears to "To:" email field : <p>I am creating a file in the cache directory that I'd like to share with others (via Gmail / WhatsApp etc). I am able to do this using FileProvider, and it works OK for WhatsApp. When choosing to share on Gmail the photo is correctly attached, but the Uri that I pass via Intent.EXTRA_STREAM also ends up being parsed by Gmail as an address in the "To:" field of the newly composed email, along with the address(es) that I pass via Intent.EXTRA_EMAIL.</p>
<p>So the user is required to delete the bogus (Uri) email address before sending. Any idea how to prevent this from happening?</p>
<pre><code>Uri contentUri = FileProvider.getUriForFile(getActivity(), "com.mypackage.fileprovider", cacheFile);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setDataAndType(contentUri, "image/jpeg");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {"some_address@gmail.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Photo");
intent.putExtra(Intent.EXTRA_TEXT, "Check out this photo");
intent.putExtra(Intent.EXTRA_STREAM, contentUri);
if(intent.resolveActivity(getActivity().getPackageManager()) != null)
{
startActivity(Intent.createChooser(intent, getString(R.string.share_file)));
}
</code></pre>
| 0debug |
void qapi_copy_SocketAddress(SocketAddress **p_dest,
SocketAddress *src)
{
QmpOutputVisitor *qov;
Visitor *ov, *iv;
QObject *obj;
*p_dest = NULL;
qov = qmp_output_visitor_new();
ov = qmp_output_get_visitor(qov);
visit_type_SocketAddress(ov, NULL, &src, &error_abort);
obj = qmp_output_get_qobject(qov);
visit_free(ov);
if (!obj) {
return;
}
iv = qmp_input_visitor_new(obj, true);
visit_type_SocketAddress(iv, NULL, p_dest, &error_abort);
visit_free(iv);
qobject_decref(obj);
}
| 1threat |
npm WARN deprecated npmconf@2.1.2: this package has been reintegrated into npm and is now out of date with respect to npm : <p>I am installing node.js on a CentOS 7 server, and am getting the following error when I try to install yeoman: </p>
<pre><code>npm WARN deprecated npmconf@2.1.2: this package has been
reintegrated into npm and is now out of date with respect to npm
</code></pre>
<p>The install of yeoman seems to otherwise work correctly. Is there something that I can do to avoid this warning? What are the implications of leaving it unhandled? </p>
<p>Here is the rest of the first part of the terminal output from the yeoman install: </p>
<pre><code>[root@localhost ~]# npm install -g yo
npm WARN deprecated npmconf@2.1.2: this package has been reintegrated into npm and is now out of date with respect to npm
/usr/bin/yo -> /usr/lib/node_modules/yo/lib/cli.js
> yo@1.6.0 postinstall /usr/lib/node_modules/yo
> yodoctor
Yeoman Doctor
Running sanity checks on your system
✔ Global configuration file is valid
✔ NODE_PATH matches the npm root
✔ Node.js version
✔ No .bowerrc file in home directory
✔ No .yo-rc.json file in home directory
✔ npm version
Everything looks all right!
/usr/lib
.... many lines of directory structure follow
</code></pre>
| 0debug |
Chaining RxJS Observables from http data in Angular2 with TypeScript : <p>I'm currently trying to teach myself Angular2 and TypeScript after happily working with AngularJS 1.* for the last 4 years! I have to admit I am hating it but I am sure my eureka moment is just around the corner... anyway, I have written a service in my dummy app that will fetch http data from a phoney backend I wrote that serves JSON.</p>
<pre><code>import {Injectable} from 'angular2/core';
import {Http, Headers, Response} from 'angular2/http';
import {Observable} from 'rxjs';
@Injectable()
export class UserData {
constructor(public http: Http) {
}
getUserStatus(): any {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.get('/restservice/userstatus', {headers: headers})
.map((data: any) => data.json())
.catch(this.handleError);
}
getUserInfo(): any {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.get('/restservice/profile/info', {headers: headers})
.map((data: any) => data.json())
.catch(this.handleError);
}
getUserPhotos(myId): any {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.get(`restservice/profile/pictures/overview/${ myId }`, {headers: headers})
.map((data: any) => data.json())
.catch(this.handleError);
}
private handleError(error: Response) {
// just logging to the console for now...
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
</code></pre>
<p>Now in a Component I wish to run (or chain) both <code>getUserInfo()</code> and <code>getUserPhotos(myId)</code> methods. In AngularJS this was easy as in my controller I would do something like this to avoid the "Pyramid of doom"...</p>
<pre><code>// Good old AngularJS 1.*
UserData.getUserInfo().then(function(resp) {
return UserData.getUserPhotos(resp.UserId);
}).then(function (resp) {
// do more stuff...
});
</code></pre>
<p>Now I have tried doing something similar in my component (replacing <code>.then</code> for <code>.subscribe</code>) however my error console going crazy! </p>
<pre><code>@Component({
selector: 'profile',
template: require('app/components/profile/profile.html'),
providers: [],
directives: [],
pipes: []
})
export class Profile implements OnInit {
userPhotos: any;
userInfo: any;
// UserData is my service
constructor(private userData: UserData) {
}
ngOnInit() {
// I need to pass my own ID here...
this.userData.getUserPhotos('123456') // ToDo: Get this from parent or UserData Service
.subscribe(
(data) => {
this.userPhotos = data;
}
).getUserInfo().subscribe(
(data) => {
this.userInfo = data;
});
}
}
</code></pre>
<p>I'm obviously doing something wrong... how would I best with Observables and RxJS? Sorry if I am asking stupid questions... but thanks for the help in advance! I have also noticed the repeated code in my functions when declaring my http headers...</p>
| 0debug |
Ember - How to get route model inside route action : <p>Is it possible to access route model inside route action?</p>
<p>I am passing multiple objects inside a route model to template,</p>
<pre><code> model: function() {
return {
employeeList : this.store.findAll("employee"),
employee : Ember.Object.create()
}
}
</code></pre>
<p>From the route action I am want to modify the route model.employee. I tried the following, but I am not getting the object.</p>
<pre><code>actions:{
editAction : function(id) {
var emp = this.get("model");
console.log(emp.employee);
}
}
</code></pre>
<p>Can anyone give a solution to get and modify model object(employee)?</p>
| 0debug |
hello.sorry i cant assign char "X" in part of String?can you help me? : i cant assign a specific char like "X" in part of my input string.
for example i want to assign a default char with substring method in specific range of my input string. how can i assign a specific char in specific range of my
input string
can you help me?
thx | 0debug |
How to fix the Snackbar height and position? : <p>On <strong>Android Support Library 24.1.1</strong>, the Snackbar was working fine:</p>
<p><a href="https://i.stack.imgur.com/oIsUO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/oIsUO.png" alt="before"></a></p>
<p>Then starting on <strong>Android Support Library 24.2.0</strong> onwards, the Snackbar started to behave like this:</p>
<p><a href="https://i.stack.imgur.com/d6Kr3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/d6Kr3.png" alt="after"></a></p>
<p>On the library <a href="https://developer.android.com/topic/libraries/support-library/rev-archive.html#rev24-2-0" rel="noreferrer">revision history</a>, there is the following statement:</p>
<blockquote>
<p>Behavior changes: Snackbar now draws behind the navigation bar if the status bar is translucent.</p>
</blockquote>
<p>But the thing is that my app is full screen and it doesn't have the navigation bar or the status bar. How can I fix it?</p>
| 0debug |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.