problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
Vuforia basic app sample for android : <p>I want to know if anyone has an idea where to find basic android samples for vuforia sdk because provided samples are too big for me to fully understand it.</p>
| 0debug
|
static void rv34_gen_vlc(const uint8_t *bits, int size, VLC *vlc, const uint8_t *insyms,
const int num)
{
int i;
int counts[17] = {0}, codes[17];
uint16_t cw[size], syms[size];
uint8_t bits2[size];
int maxbits = 0, realsize = 0;
for(i = 0; i < size; i++){
if(bits[i]){
bits2[realsize] = bits[i];
syms[realsize] = insyms ? insyms[i] : i;
realsize++;
maxbits = FFMAX(maxbits, bits[i]);
counts[bits[i]]++;
}
}
codes[0] = 0;
for(i = 0; i < 16; i++)
codes[i+1] = (codes[i] + counts[i]) << 1;
for(i = 0; i < realsize; i++)
cw[i] = codes[bits2[i]]++;
vlc->table = &table_data[table_offs[num]];
vlc->table_allocated = table_offs[num + 1] - table_offs[num];
init_vlc_sparse(vlc, FFMIN(maxbits, 9), realsize,
bits2, 1, 1,
cw, 2, 2,
syms, 2, 2, INIT_VLC_USE_NEW_STATIC);
}
| 1threat
|
giving wrong day in php : displaying Thursday but Wednesday output,please fix it.........
thanks in advance
<?php
date_default_timezone_set('Asia/Kolkata');
$date = '2017/06/07';
$weekday = date('l', strtotime($date));
echo $weekday; //
?>
| 0debug
|
int bdrv_check(BlockDriverState *bs)
{
if (bs->drv->bdrv_check == NULL) {
return -ENOTSUP;
}
return bs->drv->bdrv_check(bs);
}
| 1threat
|
I have a method which returns Pane and On that pane are some button and ProgressBar everything work perfectly : But the problem is that when whenever I start a new Download It opens a new Pane on the same Position but I want to every new Download shoul be add in a new line.How can i achieve this?
[Here is CODELink][1]
[Here is the ImageLink][2]
[1]: https://drive.google.com/open?id=1lgaSNnvyzXKjl-b86dTiEkjsqGF1oer_
[2]: https://i.stack.imgur.com/cgitx.png
| 0debug
|
Why disable dropout during validation and testing? : <p>I've seen in multiple places that you should disable dropout during validation and testing stages and only keep it during the training phase. Is there a reason why that should happen? I haven't been able to find a good reason for that and was just wondering.</p>
<p>One reason I'm asking is because I trained a model with dropout, and the results turned out well - about 80% accuracy. Then, I went on to validate the model but forgot to set the prob to 1 and the model's accuracy went down to about 70%. Is it supposed to be that drastic? And is it as simple as setting the prob to 1 in each dropout layer?</p>
<p>Thanks in advance!</p>
| 0debug
|
Rails 6 webpacker cannot find module for installed module : <p>in my Rails 6 project, i added jQuery pushMenu with </p>
<blockquote>
<p>yarn add push-menu </p>
</blockquote>
<p>from <a href="https://www.npmjs.com/package/push-menu" rel="noreferrer">https://www.npmjs.com/package/push-menu</a>
Now i can see this in node-modules folder, as push-menu. however, when i try to import or include from packs, as:</p>
<pre><code>require("push-menu")
</code></pre>
<p>i get the following error:</p>
<pre><code>Uncaught Error: Cannot find module 'push-menu'
at webpackMissingModule (application.js:12)
at Module../app/javascript/packs/application.js (application.js:12)
at __webpack_require__ (bootstrap:19)
at bootstrap:83
at bootstrap:83
</code></pre>
<p>my package.json file looks like this</p>
<pre><code>//package.json file
{
"name": "example_setup",
"private": true,
"dependencies": {
"@rails/actioncable": "^6.0.0-alpha",
"@rails/activestorage": "^6.0.0-alpha",
"@rails/ujs": "^6.0.0-alpha",
"@rails/webpacker": "^4.0.7",
"jquery": "^3.4.1",
"push-menu": "^2.0.8",
"select2": "^4.0.7",
"turbolinks": "^5.2.0"
},
"version": "0.1.0",
"devDependencies": {
"webpack-dev-server": "^3.7.1"
}
}
</code></pre>
<p>What am i doing wrong here?</p>
| 0debug
|
how to make two level select option? : i need make two level select option if selected **bmw** how to show **bmwsubcategory** ?
if select **audi** how to remove **bmwsubcategory** from html and show **audisubcategory** ?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<select id="category">
<option class="bmwsubcategory" value="bmw">bmw</option>
<option class="audisubcategory" value="audi">audi</option>
<option class="fordsubcategory" value="ford">ford</option>
<option class="fiatsubcategory" value="fiat">fiat</option>
</select>
<select class="bmwsubcategory" name="bmw">
<option value="bmw 1">bmw 1</option>
<option value="bmw 2">bmw 2</option>
<option value="bmw 3">bmw 3</option>
<option value="bmw 4">bmw 4</option>
</select>
<select class="audisubcategory" name="audi">
<option value="audi 1">audi 1</option>
<option value="audi 2">audi 2</option>
<option value="audi 3">audi 3</option>
<option value="audi 4">audi 4</option>
</select>
<select class="fordsubcategory" name="ford">
<option value="ford 1">ford 1</option>
<option value="ford 2">ford 2</option>
<option value="ford 3">ford 3</option>
<option value="ford 4">ford 4</option>
</select>
<select class="fiatsubcategory" name="fiat">
<option value="fiat 1">fiat 1</option>
<option value="fiat 2">fiat 2</option>
<option value="fiat 3">fiat 3</option>
<option value="fiat 4">fiat 4</option>
</select>
<!-- end snippet -->
| 0debug
|
Add a prefix of +1 to a string : <p>How can I remove all non 10 digit numbers from a string, and add a +1 to the front of it if it doesn't exist yet?</p>
<p>Here's the regex code I have:</p>
<pre><code>phoneNumber.replace(/[^0-9.\,]/g, '');
phoneNumber = '+1' + phoneNumber;
</code></pre>
<p>but this won't work if <code>phoneNumber</code> already has <code>+1</code>. How can I make it that the regex first removes all non numerical, and adds a prefix of +1?</p>
| 0debug
|
static int read_decode_block(ALSDecContext *ctx, ALSBlockData *bd)
{
int ret;
ret = read_block(ctx, bd);
if (ret)
return ret;
ret = decode_block(ctx, bd);
return ret;
}
| 1threat
|
def recursive_list_sum(data_list):
total = 0
for element in data_list:
if type(element) == type([]):
total = total + recursive_list_sum(element)
else:
total = total + element
return total
| 0debug
|
static void chroma_4mv_motion(MpegEncContext *s,
uint8_t *dest_cb, uint8_t *dest_cr,
uint8_t **ref_picture,
op_pixels_func *pix_op,
int mx, int my)
{
int dxy, emu=0, src_x, src_y, offset;
uint8_t *ptr;
mx= ff_h263_round_chroma(mx);
my= ff_h263_round_chroma(my);
dxy = ((my & 1) << 1) | (mx & 1);
mx >>= 1;
my >>= 1;
src_x = s->mb_x * 8 + mx;
src_y = s->mb_y * 8 + my;
src_x = av_clip(src_x, -8, (s->width >> 1));
if (src_x == (s->width >> 1))
dxy &= ~1;
src_y = av_clip(src_y, -8, (s->height >> 1));
if (src_y == (s->height >> 1))
dxy &= ~2;
offset = src_y * s->uvlinesize + src_x;
ptr = ref_picture[1] + offset;
if(s->flags&CODEC_FLAG_EMU_EDGE){
if( (unsigned)src_x > FFMAX((s->h_edge_pos>>1) - (dxy &1) - 8, 0)
|| (unsigned)src_y > FFMAX((s->v_edge_pos>>1) - (dxy>>1) - 8, 0)){
s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize,
9, 9, src_x, src_y,
s->h_edge_pos>>1, s->v_edge_pos>>1);
ptr= s->edge_emu_buffer;
emu=1;
}
}
pix_op[dxy](dest_cb, ptr, s->uvlinesize, 8);
ptr = ref_picture[2] + offset;
if(emu){
s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize,
9, 9, src_x, src_y,
s->h_edge_pos>>1, s->v_edge_pos>>1);
ptr= s->edge_emu_buffer;
}
pix_op[dxy](dest_cr, ptr, s->uvlinesize, 8);
}
| 1threat
|
static void configure_alarms(char const *opt)
{
int i;
int cur = 0;
int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
char *arg;
char *name;
if (!strcmp(opt, "help")) {
show_available_alarms();
exit(0);
}
arg = strdup(opt);
name = strtok(arg, ",");
while (name) {
struct qemu_alarm_timer tmp;
for (i = 0; i < count; i++) {
if (!strcmp(alarm_timers[i].name, name))
break;
}
if (i == count) {
fprintf(stderr, "Unknown clock %s\n", name);
goto next;
}
if (i < cur)
goto next;
tmp = alarm_timers[i];
alarm_timers[i] = alarm_timers[cur];
alarm_timers[cur] = tmp;
cur++;
next:
name = strtok(NULL, ",");
}
free(arg);
if (cur) {
for (i = cur; i < count; i++)
alarm_timers[i].name = NULL;
}
show_available_alarms();
}
| 1threat
|
static int usb_hub_handle_data(USBDevice *dev, USBPacket *p)
{
USBHubState *s = (USBHubState *)dev;
int ret;
switch(p->pid) {
case USB_TOKEN_IN:
if (p->devep == 1) {
USBHubPort *port;
unsigned int status;
uint8_t buf[4];
int i, n;
n = (NUM_PORTS + 1 + 7) / 8;
if (p->iov.size == 1) {
n = 1;
} else if (n > p->iov.size) {
return USB_RET_BABBLE;
}
status = 0;
for(i = 0; i < NUM_PORTS; i++) {
port = &s->ports[i];
if (port->wPortChange)
status |= (1 << (i + 1));
}
if (status != 0) {
for(i = 0; i < n; i++) {
buf[i] = status >> (8 * i);
}
usb_packet_copy(p, buf, n);
ret = n;
} else {
ret = USB_RET_NAK;
}
} else {
goto fail;
}
break;
case USB_TOKEN_OUT:
default:
fail:
ret = USB_RET_STALL;
break;
}
return ret;
}
| 1threat
|
static void filter_mb_edgev( H264Context *h, uint8_t *pix, int stride, int bS[4], int qp ) {
int i, d;
const int index_a = clip( qp + h->slice_alpha_c0_offset, 0, 51 );
const int alpha = alpha_table[index_a];
const int beta = beta_table[clip( qp + h->slice_beta_offset, 0, 51 )];
for( i = 0; i < 4; i++ ) {
if( bS[i] == 0 ) {
pix += 4 * stride;
continue;
}
for( d = 0; d < 4; d++ ) {
const uint8_t p0 = pix[-1];
const uint8_t p1 = pix[-2];
const uint8_t p2 = pix[-3];
const uint8_t q0 = pix[0];
const uint8_t q1 = pix[1];
const uint8_t q2 = pix[2];
if( abs( p0 - q0 ) >= alpha ||
abs( p1 - p0 ) >= beta ||
abs( q1 - q0 ) >= beta ) {
pix += stride;
continue;
}
if( bS[i] < 4 ) {
const int tc0 = tc0_table[index_a][bS[i] - 1];
int tc = tc0;
int i_delta;
if( abs( p2 - p0 ) < beta ) {
pix[-2] = p1 + clip( ( p2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( p1 << 1 ) ) >> 1, -tc0, tc0 );
tc++;
}
if( abs( q2 - q0 ) < beta ) {
pix[1] = q1 + clip( ( q2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( q1 << 1 ) ) >> 1, -tc0, tc0 );
tc++;
}
i_delta = clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );
pix[-1] = clip( p0 + i_delta, 0, 255 );
pix[0] = clip( q0 - i_delta, 0, 255 );
}
else
{
const int c = abs( p0 - q0 ) < (( alpha >> 2 ) + 2 );
if( abs( p2 - p0 ) < beta && c )
{
const uint8_t p3 = pix[-4];
pix[-1] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
pix[-2] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
pix[-3] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
} else {
pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
}
if( abs( q2 - q0 ) < beta && c )
{
const uint8_t q3 = pix[3];
pix[0] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
pix[1] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
pix[2] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
} else {
pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
}
}
pix += stride;
}
}
}
| 1threat
|
infinite loop in the first function dont know how to fix : <p>Keep getting stuck in an infinite loop dont know where my logic went wrong</p>
<p>used while eof and dont know what else is missing, also break statement didnt do anything but print out my test statement once </p>
<pre><code>void readSetupData(string sfile, string efile, string afile, students
studArray[])
{
ifstream inS(sfile.c_str());
ifstream inA(afile.c_str());
ifstream inE(efile.c_str());
int numStudents = 0;
while (!inS.eof())
{
cout << "BEEP" << endl;
int id;
int examScore;
string name;
inS >> name >> studArray[numStudents].id >>
studArray[numStudents].name;
int examId;
inE >> id >> examId >> examScore;
int studentIndex = findStudent(id, studArray);
int examIndex = findExam(examId,
studArray[studentIndex].examArray);
studArray[studentIndex].examArray[examIndex].pointsScored
=
examScore;
int pointsAvail =
studArray[studentIndex].examArray[examIndex].pointsAvail;
studArray[studentIndex].examArray[examIndex].percentage =
(float)examScore / (float)pointsAvail;
}
while (!inA.eof())
{
int id;
int assignId;
int assignScore;
inA >> id >> assignId >> assignScore;
int studentIndex = findStudent(id, studArray);
int assignIndex = findAssignment(assignId,
studArray[studentIndex].assignArray);
studArray[studentIndex].assignArray[assignIndex].pointsScored
= assignScore;
}
}
</code></pre>
<p>the first void function is the problem and the test statement BEEP is repeated when compiled and ran with
./a.out student_info.txt exam_info assignment_info.txt exam_scores.txt assignment_scores grades.out </p>
| 0debug
|
for build calculate and make errors : <p>in my project for build calculate has error like this :</p>
<pre><code>void findView(){
btn_0=(Button)findViewById(R.id.btn_0);
btn_1=(Button)findViewById(R.id.btn_1);
</code></pre>
<p>and cannot resolve symbol for anythings have R ,what should i do ?</p>
| 0debug
|
retrieve data from a form and insert it in a database using adapters in worklight? : <p>i have an inscription form , and i don't know how to retrieve data from this form and send it to the database using adapter in worklight
i think that i should use jquery . val() to retrieve data and use it in a procedure to put it in the database , please some help :/
thanks !!</p>
<p>var procedure1Statement = WL.Server.createSQLStatement("select COLUMN1, COLUMN2 from TABLE1 where COLUMN3 = ?");
function procedure1(param) {
return WL.Server.invokeSQLStatement({
preparedStatement : procedure1Statement,
parameters : [param]
});
}</p>
| 0debug
|
void ff_mpeg_flush(AVCodecContext *avctx){
int i;
MpegEncContext *s = avctx->priv_data;
if(s==NULL || s->picture==NULL)
return;
for(i=0; i<MAX_PICTURE_COUNT; i++){
if(s->picture[i].data[0] && ( s->picture[i].type == FF_BUFFER_TYPE_INTERNAL
|| s->picture[i].type == FF_BUFFER_TYPE_USER))
avctx->release_buffer(avctx, (AVFrame*)&s->picture[i]);
}
s->current_picture_ptr = s->last_picture_ptr = s->next_picture_ptr = NULL;
s->mb_x= s->mb_y= 0;
s->parse_context.state= -1;
s->parse_context.frame_start_found= 0;
s->parse_context.overread= 0;
s->parse_context.overread_index= 0;
s->parse_context.index= 0;
s->parse_context.last_index= 0;
s->bitstream_buffer_size=0;
}
| 1threat
|
Is there way to determine why Azure App Service restarted? : <p>I have a bunch of websites running on a single instance of Azure App Service, and they're all set to Always On. They all suddenly restarted at the same time, causing everything to go slow for a few minutes as everything hit a cold request. </p>
<p>I would expect this if the service had moved me to a new host, but that didn't happen -- I'm still on the same hostname. </p>
<p>CPU and memory usage were normal at the time of the restart, and I didn't initiate any deployments or anything like that. I don't see an obvious reason for the restart.</p>
<p>Is there any logging anywhere that I can see to figure out <em>why</em> they all restarted? Or is this just a normal thing that App Service does from time to time?</p>
| 0debug
|
Using AWS services as backend to make an instagram(no videos initially) like app : <p>I am using AWS s3 to store images and ec2(t2.micro free tier) instance to save images url and user details.i have tested it and its working fine.</p>
<p>I want to rent servers and make the app live in play store now.
Im confused which ec2 instance i should go with ?</p>
<p>And will i need Load balancers and more than one ec2 instance for the initial phase of 2000-3000 users(for a month)?</p>
<p>Do i need to add any other service?</p>
<p>I am not an expert at managing servers because i have just learnt and yet to learn other AWS services.I want the servers to run well until the user number grows more than 3k.
Would be glad to get exact answers.</p>
| 0debug
|
How to use lotusscript button in web browser? : <p>I have a save button in my lotus notes. My save button will execute some process in lotusscript. I will explain what document related to my save process.</p>
<p>Now I have a document from main view with status "Active", I called it "current" document.</p>
<ol>
<li>First I create copy for all current document with status "Draft" and I called it as "Copy" document.</li>
<li>Second I create "Inspection" document for all copy documents with status "Incomplete" and use all data from copy document with "Computed for display". So my "Copy" is used for all editing while "Inspection" is a Report of document only. It means, changes made in copy documents, when click save, Report will also updated with latest information.</li>
</ol>
<p>So the process will start edit copy document and save it. Copy document status will change from "Draft" to "Active", and current document will change from "Active" to "Inactive". That means, Copy document will be new current document. Then, Inspection Report status will change to "Complete".</p>
<p>Below is my lotusscript button code:</p>
<pre><code>Set db = session.CurrentDatabase
Set uidoc = workspace.CurrentDocument
Set doc = uidoc.Document
'//Set lookup view for current document
keys(0) = doc.PTagNo(0)
keys(1) = "Lock"
Set view = db.GetView("TagNo")
'//Set lookup view for "Inspection" document
pckeys(0) = doc.PTagNo(0)
pckeys(1) = doc.PBatchNo(0)
pckeys(2) = "Incomplete"
Set pcview = db.GetView("BatchPCInspection")
answer% = Messagebox("Save PC Inspection?", 4,"Confirmation")
If Not answer% = 6 Then
Exit Sub
Else
'//Make changes for "Inspection" document
Set comdoc = pcview.GetDocumentByKey(pckeys, True)
If Not comdoc Is Nothing Then
If comdoc.AStatus(0) = "Incomplete" Then
comdoc.DocId=doc.UniversalID
comdoc.ATagNo = doc.PTagNo
comdoc.ADept= doc.PDept
comdoc.AUserName= doc.PUserName
comdoc.AStatus="Complete"
Call comdoc.Save(True, False)
End If
End If
'//Make changes for current document become Inactive
Set activeDoc = view.GetDocumentByKey(keys, True)
If Not activeDoc Is Nothing Then
If activeDoc.PStatus(0) = "Lock" Then
activeDoc.DocumetId = doc.UniversalID
activeDoc.PStatus = "Inactive"
Call activeDoc.Save(True, False)
End If
End If
'//Make changes for "Copy" document become Active
Call uidoc.FieldSetText("PStatus" , "Active")
Call uidoc.FieldSetText("SaveOptions" , "1")
Call uidoc.Save
Call uidoc.Close
End If
End Sub
</code></pre>
<p>So my question now, how can I convert this lotusscript code to javascript code? Because lotusscript will not run in web browser, so I surely need to convert this to javascript. Anyone know any documentation or way on how to convert this lotusscript button to javascript button. Any help will be appreciated! Thanks in advanced!</p>
| 0debug
|
static int alac_decode_frame(AVCodecContext *avctx,
void *outbuffer, int *outputsize,
uint8_t *inbuffer, int input_buffer_size)
{
ALACContext *alac = avctx->priv_data;
int channels;
int32_t outputsamples;
if (!inbuffer || !input_buffer_size)
return input_buffer_size;
if (!alac->context_initialized) {
if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
ALAC_EXTRADATA_SIZE);
return input_buffer_size;
}
alac_set_info(alac);
alac->context_initialized = 1;
}
outputsamples = alac->setinfo_max_samples_per_frame;
init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
channels = get_bits(&alac->gb, 3);
*outputsize = outputsamples * alac->bytespersample;
switch(channels) {
case 0: {
int hassize;
int isnotcompressed;
int readsamplesize;
int wasted_bytes;
int ricemodifier;
get_bits(&alac->gb, 4);
get_bits(&alac->gb, 12);
hassize = get_bits(&alac->gb, 1);
wasted_bytes = get_bits(&alac->gb, 2);
isnotcompressed = get_bits(&alac->gb, 1);
if (hassize) {
outputsamples = get_bits(&alac->gb, 32);
*outputsize = outputsamples * alac->bytespersample;
}
readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8);
if (!isnotcompressed) {
int16_t predictor_coef_table[32];
int predictor_coef_num;
int prediction_type;
int prediction_quantitization;
int i;
get_bits(&alac->gb, 8);
get_bits(&alac->gb, 8);
prediction_type = get_bits(&alac->gb, 4);
prediction_quantitization = get_bits(&alac->gb, 4);
ricemodifier = get_bits(&alac->gb, 3);
predictor_coef_num = get_bits(&alac->gb, 5);
for (i = 0; i < predictor_coef_num; i++) {
predictor_coef_table[i] = (int16_t)get_bits(&alac->gb, 16);
}
if (wasted_bytes) {
av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
}
bastardized_rice_decompress(alac,
alac->predicterror_buffer_a,
outputsamples,
readsamplesize,
alac->setinfo_rice_initialhistory,
alac->setinfo_rice_kmodifier,
ricemodifier * alac->setinfo_rice_historymult / 4,
(1 << alac->setinfo_rice_kmodifier) - 1);
if (prediction_type == 0) {
predictor_decompress_fir_adapt(alac->predicterror_buffer_a,
alac->outputsamples_buffer_a,
outputsamples,
readsamplesize,
predictor_coef_table,
predictor_coef_num,
prediction_quantitization);
} else {
av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type);
}
} else {
if (readsamplesize <= 16) {
int i;
for (i = 0; i < outputsamples; i++) {
int32_t audiobits = get_bits(&alac->gb, readsamplesize);
audiobits = SIGN_EXTENDED32(audiobits, readsamplesize);
alac->outputsamples_buffer_a[i] = audiobits;
}
} else {
int i;
for (i = 0; i < outputsamples; i++) {
int32_t audiobits;
audiobits = get_bits(&alac->gb, 16);
audiobits = audiobits << 16;
audiobits = audiobits >> (32 - readsamplesize);
audiobits |= get_bits(&alac->gb, readsamplesize - 16);
alac->outputsamples_buffer_a[i] = audiobits;
}
}
}
switch(alac->setinfo_sample_size) {
case 16: {
int i;
for (i = 0; i < outputsamples; i++) {
int16_t sample = alac->outputsamples_buffer_a[i];
((int16_t*)outbuffer)[i * alac->numchannels] = sample;
}
break;
}
case 20:
case 24:
case 32:
av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
break;
default:
break;
}
break;
}
case 1: {
int hassize;
int isnotcompressed;
int readsamplesize;
int wasted_bytes;
uint8_t interlacing_shift;
uint8_t interlacing_leftweight;
get_bits(&alac->gb, 4);
get_bits(&alac->gb, 12);
hassize = get_bits(&alac->gb, 1);
wasted_bytes = get_bits(&alac->gb, 2);
isnotcompressed = get_bits(&alac->gb, 1);
if (hassize) {
outputsamples = get_bits(&alac->gb, 32);
*outputsize = outputsamples * alac->bytespersample;
}
readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + 1;
if (!isnotcompressed) {
int16_t predictor_coef_table_a[32];
int predictor_coef_num_a;
int prediction_type_a;
int prediction_quantitization_a;
int ricemodifier_a;
int16_t predictor_coef_table_b[32];
int predictor_coef_num_b;
int prediction_type_b;
int prediction_quantitization_b;
int ricemodifier_b;
int i;
interlacing_shift = get_bits(&alac->gb, 8);
interlacing_leftweight = get_bits(&alac->gb, 8);
prediction_type_a = get_bits(&alac->gb, 4);
prediction_quantitization_a = get_bits(&alac->gb, 4);
ricemodifier_a = get_bits(&alac->gb, 3);
predictor_coef_num_a = get_bits(&alac->gb, 5);
for (i = 0; i < predictor_coef_num_a; i++) {
predictor_coef_table_a[i] = (int16_t)get_bits(&alac->gb, 16);
}
prediction_type_b = get_bits(&alac->gb, 4);
prediction_quantitization_b = get_bits(&alac->gb, 4);
ricemodifier_b = get_bits(&alac->gb, 3);
predictor_coef_num_b = get_bits(&alac->gb, 5);
for (i = 0; i < predictor_coef_num_b; i++) {
predictor_coef_table_b[i] = (int16_t)get_bits(&alac->gb, 16);
}
if (wasted_bytes) {
av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
}
bastardized_rice_decompress(alac,
alac->predicterror_buffer_a,
outputsamples,
readsamplesize,
alac->setinfo_rice_initialhistory,
alac->setinfo_rice_kmodifier,
ricemodifier_a * alac->setinfo_rice_historymult / 4,
(1 << alac->setinfo_rice_kmodifier) - 1);
if (prediction_type_a == 0) {
predictor_decompress_fir_adapt(alac->predicterror_buffer_a,
alac->outputsamples_buffer_a,
outputsamples,
readsamplesize,
predictor_coef_table_a,
predictor_coef_num_a,
prediction_quantitization_a);
} else {
av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type_a);
}
bastardized_rice_decompress(alac,
alac->predicterror_buffer_b,
outputsamples,
readsamplesize,
alac->setinfo_rice_initialhistory,
alac->setinfo_rice_kmodifier,
ricemodifier_b * alac->setinfo_rice_historymult / 4,
(1 << alac->setinfo_rice_kmodifier) - 1);
if (prediction_type_b == 0) {
predictor_decompress_fir_adapt(alac->predicterror_buffer_b,
alac->outputsamples_buffer_b,
outputsamples,
readsamplesize,
predictor_coef_table_b,
predictor_coef_num_b,
prediction_quantitization_b);
} else {
av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type_b);
}
} else {
if (alac->setinfo_sample_size <= 16) {
int i;
for (i = 0; i < outputsamples; i++) {
int32_t audiobits_a, audiobits_b;
audiobits_a = get_bits(&alac->gb, alac->setinfo_sample_size);
audiobits_b = get_bits(&alac->gb, alac->setinfo_sample_size);
audiobits_a = SIGN_EXTENDED32(audiobits_a, alac->setinfo_sample_size);
audiobits_b = SIGN_EXTENDED32(audiobits_b, alac->setinfo_sample_size);
alac->outputsamples_buffer_a[i] = audiobits_a;
alac->outputsamples_buffer_b[i] = audiobits_b;
}
} else {
int i;
for (i = 0; i < outputsamples; i++) {
int32_t audiobits_a, audiobits_b;
audiobits_a = get_bits(&alac->gb, 16);
audiobits_a = audiobits_a << 16;
audiobits_a = audiobits_a >> (32 - alac->setinfo_sample_size);
audiobits_a |= get_bits(&alac->gb, alac->setinfo_sample_size - 16);
audiobits_b = get_bits(&alac->gb, 16);
audiobits_b = audiobits_b << 16;
audiobits_b = audiobits_b >> (32 - alac->setinfo_sample_size);
audiobits_b |= get_bits(&alac->gb, alac->setinfo_sample_size - 16);
alac->outputsamples_buffer_a[i] = audiobits_a;
alac->outputsamples_buffer_b[i] = audiobits_b;
}
}
interlacing_shift = 0;
interlacing_leftweight = 0;
}
switch(alac->setinfo_sample_size) {
case 16: {
deinterlace_16(alac->outputsamples_buffer_a,
alac->outputsamples_buffer_b,
(int16_t*)outbuffer,
alac->numchannels,
outputsamples,
interlacing_shift,
interlacing_leftweight);
break;
}
case 20:
case 24:
case 32:
av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
break;
default:
break;
}
break;
}
}
return input_buffer_size;
}
| 1threat
|
Using R.NET.Community in .NET Core 2.0 Preview 1 : <p>For a while, I've been hoping to use <a href="https://www.nuget.org/packages/R.NET.Community/" rel="noreferrer">R.NET.Community</a> in a .NET Core app. Obviously though with the NuGet package not having been ported to .NET Core, that's been a non-starter. However, with the <a href="https://blogs.msdn.microsoft.com/dotnet/2017/05/10/announcing-net-core-2-0-preview-1/" rel="noreferrer">.NET Core 2.0 Preview 1 announcement</a> that you can reference .NET Framework libraries from .NET Core, I gave this another go:</p>
<pre><code>using RDotNet;
namespace RDotNetCore2
{
class Program
{
static void Main(string[] args)
{
REngine.SetEnvironmentVariables();
var engine = REngine.GetInstance();
}
}
}
</code></pre>
<p>Creating this as a .NET Core 2.0 app in the new Visual Studio 2017 Preview, this at least gets as far as compiling and running, but errors at the <code>GetInstance</code> call:</p>
<blockquote>
<p>Could not load file or assembly 'System.Security.Permissions, Version=0.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified.</p>
</blockquote>
<p>Is there anything I can do to fix this, or this just one of those bits which isn't supported in .NET Core (which I suspect may be likely due to the fact that CAS isn't supported on .NET Core)?</p>
| 0debug
|
std::ostringstream puts sign in wrong location? : <p>I am using std::ostringstream to format a double to a string with a specific format (using apostrophes as thousands separators). However, in some cases ostringstream gave me a different result from what I expected. </p>
<p>As far as I can tell, the expected output of the code below should be "+01"; instead it outputs "0+1". What am I doing wrong here, and how can I get the result I need?</p>
<pre><code>#include <iomanip>
#include <iostream>
#include <sstream>
int main()
{
std::ostringstream stream;
stream << std::showpos; // Always show sign
stream << std::setw(3); // Minimum 3 characters
stream << std::setfill( '0' ); // Zero-padded
stream << 1; // Expected output: "+01"
std::cout << stream.str(); // Output: "0+1"
return 0;
}
</code></pre>
<p><a href="https://ideone.com/BvHzrJ" rel="noreferrer">Code on ideone</a></p>
| 0debug
|
Can someone pls help me solve this issue : <p>Create a function fizzBuzz to return 'Fizz', 'Buzz', 'FizzBuzz', or the argument it receives, all depending on the argument of the function, a number that is divisible by, 3, 5, or both 3 and 5, respectively.</p>
<p>When the number is not divisible by 3 or 5, the number itself should be returned</p>
| 0debug
|
static void __cpu_ppc_store_decr(PowerPCCPU *cpu, uint64_t *nextp,
QEMUTimer *timer,
void (*raise_excp)(PowerPCCPU *),
uint32_t decr, uint32_t value,
int is_excp)
{
CPUPPCState *env = &cpu->env;
ppc_tb_t *tb_env = env->tb_env;
uint64_t now, next;
LOG_TB("%s: %08" PRIx32 " => %08" PRIx32 "\n", __func__,
decr, value);
if (kvm_enabled()) {
return;
}
now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
next = now + muldiv64(value, get_ticks_per_sec(), tb_env->decr_freq);
if (is_excp) {
next += *nextp - now;
}
if (next == now) {
next++;
}
*nextp = next;
timer_mod(timer, next);
if ((tb_env->flags & PPC_DECR_UNDERFLOW_TRIGGERED)
&& (value & 0x80000000)
&& !(decr & 0x80000000)) {
(*raise_excp)(cpu);
}
}
| 1threat
|
Scirpt didn't work on Firefox, 0 reaction on hover : I have a script that working perfectly on Chrome, but in Firefox there is no action after hovering linked object.
I tried to divide the script.js file for separate documents, but It won't help at all.
Here is the whole effect:
https://jsfiddle.net/lszewczyk45/9unawydo/9/
```javascript
$(document).ready(function () {
const effect = new Effects('hover-effects');
effect.addEffect(document.querySelector('#cityEffect'), 'city', [ONMOUSEOVER]);
});
```
I think the problem is in calling the script - the lines at the end of the file, I pasted it above.
| 0debug
|
hot to collapse 2 variables by dummies in panel data [stata] : I have to collapse a some variable of my dataset but I’m getting issues.
Basicaly, there are 2 variables valor_receita_propria (in english is own_revenue_value) and qt_tec_total (or total_tec_qt, the quantity of technician in a institution). There are 2 dummy variables which specify if the value of the above mentioned variables refer to each individual plant or to his enterprise.
For example, if in_refT is equal 1, then the value of qt_tec_total of that plant actually refers to the whole enterprise. If the inrefT is equal 2, then the value of that plant refers to that singular plnat.
What I need to do is agregate all the values for enterprise. My plan was take the mean of all values referring to the enterprise and take the sum of all values referring to each plant, so I wrote:
“
. collapse (sum) receitasum=vl_receita_propria if in_refC==2 (sum) tecsum=qt_tec_total if in_refT==2 (mean) receitasum=vl_receita_propria if in_refC==1 (mean) tecsum=qt_tec_total if in_refT==1 (sum) em_exerc (sum) doc_do (sum) qt_matricula_curso1, by (ano CO_MANT3)
“
Of course, I need that it results only one variable of each kind referring only and exclusively to each whole enterprise.
However, it shows this error:
“
invalid '('
r(198);
“
| 0debug
|
static int get_aac_sample_rates(AVFormatContext *s, AVCodecParameters *par,
int *sample_rate, int *output_sample_rate)
{
MPEG4AudioConfig mp4ac;
if (avpriv_mpeg4audio_get_config(&mp4ac, par->extradata,
par->extradata_size * 8, 1) < 0) {
av_log(s, AV_LOG_ERROR,
"Error parsing AAC extradata, unable to determine samplerate.\n");
return AVERROR(EINVAL);
}
*sample_rate = mp4ac.sample_rate;
*output_sample_rate = mp4ac.ext_sample_rate;
return 0;
}
| 1threat
|
static void postfilter(EVRCContext *e, float *in, const float *coeff,
float *out, int idx, const struct PfCoeff *pfc,
int length)
{
float wcoef1[FILTER_ORDER], wcoef2[FILTER_ORDER],
scratch[SUBFRAME_SIZE], temp[SUBFRAME_SIZE],
mem[SUBFRAME_SIZE];
float sum1 = 0.0, sum2 = 0.0, gamma, gain;
float tilt = pfc->tilt;
int i, n, best;
bandwidth_expansion(wcoef1, coeff, pfc->p1);
bandwidth_expansion(wcoef2, coeff, pfc->p2);
for (i = 0; i < length - 1; i++)
sum2 += in[i] * in[i + 1];
if (sum2 < 0.0)
tilt = 0.0;
for (i = 0; i < length; i++) {
scratch[i] = in[i] - tilt * e->last;
e->last = in[i];
}
residual_filter(&e->postfilter_residual[ACB_SIZE], scratch, wcoef1, e->postfilter_fir, length);
best = idx;
for (i = FFMIN(MIN_DELAY, idx - 3); i <= FFMAX(MAX_DELAY, idx + 3); i++) {
for (n = ACB_SIZE, sum2 = 0; n < ACB_SIZE + length; n++)
sum2 += e->postfilter_residual[n] * e->postfilter_residual[n - i];
if (sum2 > sum1) {
sum1 = sum2;
best = i;
}
}
for (i = ACB_SIZE, sum1 = 0; i < ACB_SIZE + length; i++)
sum1 += e->postfilter_residual[i - best] * e->postfilter_residual[i - best];
for (i = ACB_SIZE, sum2 = 0; i < ACB_SIZE + length; i++)
sum2 += e->postfilter_residual[i] * e->postfilter_residual[i - best];
if (sum2 * sum1 == 0 || e->bitrate == RATE_QUANT) {
memcpy(temp, e->postfilter_residual + ACB_SIZE, length * sizeof(float));
} else {
gamma = sum2 / sum1;
if (gamma < 0.5)
memcpy(temp, e->postfilter_residual + ACB_SIZE, length * sizeof(float));
else {
gamma = FFMIN(gamma, 1.0);
for (i = 0; i < length; i++) {
temp[i] = e->postfilter_residual[ACB_SIZE + i] + gamma *
pfc->ltgain * e->postfilter_residual[ACB_SIZE + i - best];
}
}
}
memcpy(scratch, temp, length * sizeof(float));
memcpy(mem, e->postfilter_iir, FILTER_ORDER * sizeof(float));
synthesis_filter(scratch, wcoef2, mem, length, scratch);
for (i = 0, sum1 = 0, sum2 = 0; i < length; i++) {
sum1 += in[i] * in[i];
sum2 += scratch[i] * scratch[i];
}
gain = sum2 ? sqrt(sum1 / sum2) : 1.0;
for (i = 0; i < length; i++)
temp[i] *= gain;
synthesis_filter(temp, wcoef2, e->postfilter_iir, length, out);
memcpy(e->postfilter_residual,
e->postfilter_residual + length, ACB_SIZE * sizeof(float));
}
| 1threat
|
I believe my scraper got blocked, but I can access the website via a regular browser, how can they do this? : <p>I recently wrote a rather simple scraper using requests and BeautifulSoup. The scraper worked perfectly until one day, I ran it and received a "Connection reset by peer, Error 54". Despite there being multiple questions about getting around Error 54's that is not what I am wondering. </p>
<p>To test whether or not the blocked my specific IP or computer, I ran the code on a different machine and IP address and it worked fine. The troubling thing however, is that even on my old machine, I can access the site on a regular browser perfectly. </p>
<p>I am wondering both how the website was able to do this without blocking my IP outright and if anyone has any tips for avoiding this in the future.</p>
| 0debug
|
Is go evaluation order between member invocations guaranteed? : <p>Let's say I have a struct with state, and a few member functions on that struct.
Let's say that the struct member returns an instance of its own type, and I call additional functions on that instance, and pass the result of calling some other member on the initial instance as an argument.
Is the order of invocation between the first invocation, and the argument invocation, guaranteed?</p>
<p>(This pattern comes up a lot when trying to build "builder" type objects that have some internal state, like an expression stack.)</p>
<pre><code>package main
import (
"fmt"
)
type q struct {
val int
}
func (s *q) getVal() int {
return s.val
}
func (s *q) a() *q {
s.val += 1
return s
}
func (s *q) b(i int) int {
return i + s.val
}
func main() {
s := &q{}
// this currently prints 2
// but is that guaranteed?
fmt.Println(s.a().b(s.getVal()))
}
</code></pre>
<p>Specifically, is the relative invocation order of <code>s.a()</code> versus <code>s.getVal()</code> guaranteed?
Golang defines the "lexical left-to-right order," but only for an individual expression, and <code>s.a().b()</code> seems like it's technically a different expression than <code>s.getVal()</code>.</p>
<p>The behavior it currently has is the behavior I'd want and expect, but I can't tell whether it's also a behavior I can rely on "forever."</p>
| 0debug
|
How to check an If statement for any version of text : I Am a beginner programmer in Visual Basic and i wanted to create a fake run box to use agianst Technical Support Scammers to waste they're time and all, Anyway i want to make it so some specified text runs a msgbox but i want to know if they're is away to accept all versions i.e (notepad, NoTePaD, NOTEPAD etc.)
i don't know any easy easy way to do this but i hope someone can be useful
I Can migrate to use case statements if neccasary
What im stuck with fornow
If textbox1.text = "Notepad" Then
Msgbox("Unable to open")
I Basically need a way to cover all versions of it
| 0debug
|
this regx @"^(?:\s*)((?:[a-zA-Z]+[\s-]?)+[a-zA-Z]+)(?:\s*)$ is taking long time : This regx **@"^(?:\s*)((?:[a-zA-Z]+[\s-]?)+[a-zA-Z]+)(?:\s*)$** is taking so long time.
In some complex cases, it is horrible.
can you please how can optimize this regx. Using for c# development in Web Application.
| 0debug
|
Hiding image in another image in java : I have been trying to hide an image in another image(both of same type) by making changes in the pixels.But it gives an error like this:
**Exception in thread "main" java.lang.NumberFormatException: For input
string: "010010101101111111"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Image.main(Image.java:160)**
The code is shown as below:
public class Image {
public static void main(String argv[]) throws Exception
{
String imageFile1 = "C:/Users/Desktop/1.jpg";
String imageFile2 = "C:/Users/Desktop/2.jpg";
File file1 = new File(imageFile1);
FileInputStream fis1 = null;
try {
fis1 = new FileInputStream(imageFile1);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
File file2 = new File(imageFile2);
FileInputStream fis2 = null;
try {
fis2 = new FileInputStream(imageFile2);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedImage oimage1 = ImageIO.read(file1);
BufferedImage oimage2 = ImageIO.read(file2);
ByteArrayOutputStream baos1=new ByteArrayOutputStream();
byte[] buf1 = new byte[1024];
try {
for (int readNum; (readNum = fis1.read(buf1)) != -1;) {
baos1.write(buf1, 0, readNum);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ByteArrayOutputStream baos2=new ByteArrayOutputStream();
byte[] buf2 = new byte[1024];
try {
for (int readNum; (readNum = fis2.read(buf1)) != -1;) {
baos2.write(buf2, 0, readNum);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final byte[] imageInByte1 = baos1.toByteArray();
final int size1 = imageInByte1.length;
final byte[] imageInByte2 = baos2.toByteArray();
final int size2 = imageInByte2.length;
int width1 = oimage1.getWidth();
int height1 = oimage1.getHeight();
int pixel1 = 0;
int red1,green1,blue1;
int width2 = oimage2.getWidth();
int height2 = oimage2.getHeight();
int pixel2=0,red2,green2,blue2;
final BufferedImage newimg1 = new BufferedImage(width1, height1, BufferedImage.TYPE_INT_ARGB);
final BufferedImage newimg2 = new BufferedImage(width2, height2, BufferedImage.TYPE_INT_ARGB);
for (int i = 0; i < width1; i++)
for (int j = 0; j < height1; j++) {
//scan through each pixel
pixel1 = oimage1.getRGB(i, j);
pixel2 = oimage2.getRGB(i, j);
//for red
String redpix1=Integer.toBinaryString(pixel1);
String binaryred1 = redpix1.substring(20,23);
String redpix2=Integer.toBinaryString(pixel2);
String binaryred2=redpix2.substring(20,23);
String newred= binaryred1 + binaryred2;
//for green
String greenpix1=Integer.toBinaryString(pixel1);
String binarygreen1=greenpix1.substring(12,15);
String greenpix2=Integer.toBinaryString(pixel2);
String binarygreen2=greenpix2.substring(12,15);
String newgreen= binarygreen1 + binarygreen2;
//for blue
String bluepix1=Integer.toBinaryString(pixel1);
String binaryblue1=bluepix1.substring(4,7);
String bluepix2=Integer.toBinaryString(pixel2);
String binaryblue2=bluepix2.substring(4,7);
String newblue= binaryblue1 + binaryblue2;
//combining the new values
String spixel=newred +newgreen + newblue;
int newpixel = Integer.parseInt(spixel);
newimg2.setRGB(i,j,newpixel);
}
JFrame f =new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JLabel(new ImageIcon(newimg2)));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
The size of 1.jpg is greater than size of 2.jpg.
Can this code be modified to get output? or is any another easy way to embed the image?
| 0debug
|
How to get 'State'(means state of Country) information using Current Location in ios using CoreLocation framework? : I want the information about user is in which state?i want the name of state.how can i get?
| 0debug
|
In SSRS Online CRM using Fetch XML , get all Contacts born on specific month (report which is a parameter) : I think the question is nail straight , SSRS Parameter will be :
Month : Jan-Dec
I know few workarounds which can achieve this requirement , but any way in CRM itself to do.
| 0debug
|
Symofny - query sum : I am writing a query which will return amount of total spent money for that user. Total spent = sum of all transaction amounts, where type = spend. I have set my type field in a base to 'spend'..
It returns
> Invalid parameter: token type is not defined in the query.
My code.
public function getTotal(User $user, $type)
{
$query = $this->getSpendingRepository()
->createQueryBuilder('p')
->select("count(p.amount) as total_amount")
->where('p.type = :spend')
->andWhere('p.user = :user')
->setParameters(['user' => $user,
'type' => $type])
->getQuery()
->getOneOrNullResult();
return $query;
}
| 0debug
|
Custom alerts in iOS 9 : <p>I wonder what is the right way to show custom alerts in iOS 9? My alert should have an icon with a label and one button to hide it. It is designed not in iOS style so from what I understand I can't use UIViewAlert? </p>
| 0debug
|
Notebook stuck on "Initializing" when using GPU backend : <p>I frequently get stuck with the runtime status "Initializing" when opening Google Colab notebooks using GPUs.</p>
<p>Are other people having this problem? Is it from a shortage of GPUs in the runtime cluster? Has anyone found a better solution than just coming back later?</p>
| 0debug
|
Python evaluating/compiling a string : <p>I want to evaluate a string to accomplish the following. The string will be coming from an xml config file. This is how I would configure a serial option without a config file:</p>
<pre><code>import serial
ser = serial.Serial(/dev/ttyUSB0)
ser.parity = serial.PARITY_MARK
...configure other options
</code></pre>
<p>Now this is the equivalent of what I want to do but...</p>
<pre><code> str = "PARITY_MARK"
ser.parity = some_wrapper("serial." + str)
</code></pre>
| 0debug
|
Security framework of XStream not initialized, XStream is probably vulnerable : <p><code>Security framework of XStream not initialized, XStream is probably vulnerable</code></p>
<p>I keep getting this console error in red while using XStream (1.4.10)</p>
<p>I tried the following:</p>
<p><code>XStream.setupDefaultSecurity(xs);</code></p>
<p>and</p>
<p><code>xs.addPermission(AnyTypePermission.ANY);</code>
<code>xs.addPermission(NoTypePermission.NONE);</code></p>
<p>none of which got rid of it.</p>
<p>I do not need any fancy security settings, I just want to silence that warning. Maybe also prepare the code for 1.5.x</p>
| 0debug
|
Using Variables - Java Eclipse. : When I run the program, the first step is to add a number and another etc. whenever i input m or l (the variables i created) an error pops up, however is works fine when i just use numbers. How do i make my variables usable to input. (Apologies if im not making sense, its hard to explain)
package pizza;
import java.util.Scanner;
public class size {
public static void main(String args[]) {
double m, l;
m = 4;
l = 5;
Scanner pizzasize = new Scanner(System.in);
double fstep, sstep, tstep, ostep, lstep, tot;
m = 4;
l = 5;
System.out.println("Enter pizza size:");
fstep = pizzasize.nextDouble();
System.out.println("Enter pizza size:");
sstep = pizzasize.nextDouble();
System.out.println("Enter pizza size:");
tstep = pizzasize.nextDouble();
System.out.println("Enter pizza size:");
ostep = pizzasize.nextDouble();
System.out.println("Enter pizza size:");
lstep = pizzasize.nextDouble();
tot = fstep+sstep+tstep+ostep+lstep;
System.out.println(tot);
pizzasize.close();
| 0debug
|
Detect current CMake version using CMake : <p>I am working on a project that uses CMake. The top <code>CMakeLists.txt</code> file contains the following line:</p>
<pre><code>cmake_minimum_required(VERSION 3.7.2) # Kittens will die if you switch to an earlier version of CMake. We suggest using CMake 3.8.0.
</code></pre>
<p>I want to force all developers to switch to CMake 3.8.0, but for some reasons, not all developers have administration rights and are not able to switch from 3.7.2 to 3.8.0 immediately. Actually, we do not need any new features of version 3.8.0, but our policy is to use always the newest and greatest tools to prevent "porting up" problems in the future - for instance switching fast from Qt4 to Qt5 was a good decission in the past - I know switching always to the newest libraries and tools has also some drawbacks as discussed <a href="https://www.joelonsoftware.com/2002/01/06/fire-and-motion/" rel="noreferrer">here</a>, but we want to do it this way.</p>
<p>Because of this, instead of forcing everyone to use version 3.8.0, I'd like to output a warning message if CMake 3.7.2 is used. Somehow like this:</p>
<pre><code># not working - just pseudocode
if(CMAKE_VERSION == "3.7.2")
message("Please consider to switch to CMake 3.8.0")
endif()
</code></pre>
<p>I tried to read the <code>VERSION</code> variable, but this does not work. Does anyone now how this check can be achieved?</p>
| 0debug
|
How to parse all the log file inside a directory using a similar pattern and do calculations using python : I have a code that reads all the lines from multiple log file inside a directory using a given pattern:
here is the code
Now what the output of the above code gives me all the required lines from the log file with the time stamp.
./xxxxx.xxxxxx.xxxxxxx.v1.0_Final:2019-01-30 08:34:46.463 -0800 INFO [626] - Program Ended: xxxxxx::xxxxx::xxxxx::xxxxxxx for exports [logfilenamexxxx] [xxxxxx_xxxxx] pid 626 user sthapa after 00:26:15
.....................and so on..
So i want to fetch all the last lines that contains the timestamp i.e. 00:26:15
and calculate the total and average time for all the timstamp collected from those log files.
Please help me with the issue......
| 0debug
|
Do While Loop to get an Input : <p>In my c++ code I want to get an input from the user repeatedly until the user inputs "0" as the input. But the loop doesn't work at all.
Here is my code....</p>
<pre><code>#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
int option;
do
{
cout<<"Enter your Option"<<endl;
cin>>option;
}
while(option == 0);
char ch;
cin>>ch;
return 0;
}
</code></pre>
| 0debug
|
auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups' : <p>In my Django project I have a <code>user_manage</code> app.</p>
<p>I create a model named <code>UserManage</code> in my <code>user_manage</code> app's model.py:</p>
<pre><code>from django.db import models
from django.contrib.auth.models import AbstractUser
class UserManage(AbstractUser):
username = models.CharField(max_length=12)
</code></pre>
<p>Then I run:</p>
<pre><code>$ python3 manage.py makemigrations
</code></pre>
<p>There comes the error:</p>
<pre><code>ERRORS:
auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'.
HINT: Add or change a related_name argument to the definition for 'User.groups' or 'UserManage.groups'.
auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'UserManage.user_permissions'.
HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'UserManage.user_permissions'.
users_management.UserManage.groups: (fields.E304) Reverse accessor for 'UserManage.groups' clashes with reverse accessor for 'User.groups'.
HINT: Add or change a related_name argument to the definition for 'UserManage.groups' or 'User.groups'.
users_management.UserManage.user_permissions: (fields.E304) Reverse accessor for 'UserManage.user_permissions' clashes with reverse accessor for 'User.user_permissions'.
HINT: Add or change a related_name argument to the definition for 'UserManage.user_permissions' or 'User.user_permissions'.
</code></pre>
| 0debug
|
void ff_aac_search_for_pred(AACEncContext *s, SingleChannelElement *sce)
{
int sfb, i, count = 0, cost_coeffs = 0, cost_pred = 0;
const int pmax = FFMIN(sce->ics.max_sfb, ff_aac_pred_sfb_max[s->samplerate_index]);
float *O34 = &s->scoefs[128*0], *P34 = &s->scoefs[128*1];
float *SENT = &s->scoefs[128*2], *S34 = &s->scoefs[128*3];
float *QERR = &s->scoefs[128*4];
if (sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
sce->ics.predictor_present = 0;
return;
}
if (!sce->ics.predictor_initialized) {
reset_all_predictors(sce->predictor_state);
sce->ics.predictor_initialized = 1;
memcpy(sce->prcoeffs, sce->coeffs, 1024*sizeof(float));
for (i = 1; i < 31; i++)
sce->ics.predictor_reset_count[i] = i;
}
update_pred_resets(sce);
memcpy(sce->band_alt, sce->band_type, sizeof(sce->band_type));
for (sfb = PRED_SFB_START; sfb < pmax; sfb++) {
int cost1, cost2, cb_p;
float dist1, dist2, dist_spec_err = 0.0f;
const int cb_n = sce->band_type[sfb];
const int start_coef = sce->ics.swb_offset[sfb];
const int num_coeffs = sce->ics.swb_offset[sfb + 1] - start_coef;
const FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[sfb];
if (start_coef + num_coeffs > MAX_PREDICTORS ||
(s->cur_channel && sce->band_type[sfb] >= INTENSITY_BT2) ||
sce->band_type[sfb] == NOISE_BT)
continue;
abs_pow34_v(O34, &sce->coeffs[start_coef], num_coeffs);
dist1 = quantize_and_encode_band_cost(s, NULL, &sce->coeffs[start_coef], NULL,
O34, num_coeffs, sce->sf_idx[sfb],
cb_n, s->lambda / band->threshold, INFINITY, &cost1, 0);
cost_coeffs += cost1;
for (i = 0; i < num_coeffs; i++)
SENT[i] = sce->coeffs[start_coef + i] - sce->prcoeffs[start_coef + i];
abs_pow34_v(S34, SENT, num_coeffs);
if (cb_n < RESERVED_BT)
cb_p = find_min_book(find_max_val(1, num_coeffs, S34), sce->sf_idx[sfb]);
else
cb_p = cb_n;
quantize_and_encode_band_cost(s, NULL, SENT, QERR, S34, num_coeffs,
sce->sf_idx[sfb], cb_p, s->lambda / band->threshold, INFINITY,
&cost2, 0);
for (i = 0; i < num_coeffs; i++)
sce->prcoeffs[start_coef + i] += QERR[i] != 0.0f ? (sce->prcoeffs[start_coef + i] - QERR[i]) : 0.0f;
abs_pow34_v(P34, &sce->prcoeffs[start_coef], num_coeffs);
if (cb_n < RESERVED_BT)
cb_p = find_min_book(find_max_val(1, num_coeffs, P34), sce->sf_idx[sfb]);
else
cb_p = cb_n;
dist2 = quantize_and_encode_band_cost(s, NULL, &sce->prcoeffs[start_coef], NULL,
P34, num_coeffs, sce->sf_idx[sfb],
cb_p, s->lambda / band->threshold, INFINITY, NULL, 0);
for (i = 0; i < num_coeffs; i++)
dist_spec_err += (O34[i] - P34[i])*(O34[i] - P34[i]);
dist_spec_err *= s->lambda / band->threshold;
dist2 += dist_spec_err;
if (dist2 <= dist1 && cb_p <= cb_n) {
cost_pred += cost2;
sce->ics.prediction_used[sfb] = 1;
sce->band_alt[sfb] = cb_n;
sce->band_type[sfb] = cb_p;
count++;
} else {
cost_pred += cost1;
sce->band_alt[sfb] = cb_p;
}
}
if (count && cost_coeffs < cost_pred) {
count = 0;
for (sfb = PRED_SFB_START; sfb < pmax; sfb++)
RESTORE_PRED(sce, sfb);
memset(&sce->ics.prediction_used, 0, sizeof(sce->ics.prediction_used));
}
sce->ics.predictor_present = !!count;
}
| 1threat
|
How to build a release version of an iOS framework in Xcode? : <p>Let's say I do the following:</p>
<ol>
<li>Open Xcode 7</li>
<li>File | New | Project | Cocoa Touch Framework</li>
<li>Create "TestFramework" with the Swift language</li>
<li>Create a file Hello.swift with public func hello() { print("Hello") }.</li>
</ol>
<p>From here, I can build a debug build of the framework (inside the Debug-iphoneos folder), but I cannot figure out how to build the release version of the framework (inside Release-iphoneos). I thought Archive might do it, but it doesn't. Pointers please?</p>
| 0debug
|
Fetch API - using response.json() throws an unexpected end of input error : <p>When using the Fetch API to fetch some JSON from a REST API on my local server and trying to parse the response with <code>response.json()</code>, I am receiving an <code>unexpected end of input</code> error.</p>
<p>The error is easily reproducible on my local server with the following one-liner:</p>
<pre><code>fetch(new Request('http://localhost:9950/RestService/v2/search/find/1', {mode: 'no-cors'})).then(function(response) { response.json(); });
// Output from Chrome console:
// Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
// VM424:1 Uncaught (in promise) SyntaxError: Unexpected end of input
// at SyntaxError (native)
// at <anonymous>:1:128
</code></pre>
<p>If I view the Network tab, I can see that my request was fulfilled by the server, and if I preview the response I can see that there is valid JSON available there (I double-checked this by copying and pasting the JSON from the Network Response tab in to jsonlint.com). Here is a sample of the response I am getting from the server:</p>
<pre><code>{
"SearchMatches": [{
"Extracts": ["<b>1<\/b>.txt...", "<b>1<\/b>"],
"Title": "1.txt",
"Url": "C:\\TestShare4\\500Docs\\1.txt"
}]
}
</code></pre>
<p>If I try to use <code>response.text()</code> instead of <code>response.json()</code> I get an empty string.</p>
<p>Any thoughts on where I could be going wrong with this?</p>
<p>Note that I have a requirement to not depend on any other frameworks or libraries other than what is natively supported by the browser.</p>
| 0debug
|
Can`t load jQuery libary : <p>Im trying to load jQuery libary following videos but it does not work. When im trying to load some jQuery function, it writes that "jquery is not defined". I also tried CDN. Thanks</p>
<pre><code> <title>
GRID
</title>
<link rel="stylesheet" href="grid.css">
<link href="https://fonts.googleapis.com/css?
family=Ubuntu&display=swap" rel="stylesheet">
<script src="jquery-2.1.1.min.js"></script>
<script src="script.js"></script>
</head>```
</code></pre>
| 0debug
|
Sortable table jquery : order by name of first column with jquery,how can i modify this code , i don't have idea , anyone can help me? :
oTable_aziende = $('#table_aziende').dataTable({
"bJQueryUI": true,
//"sScrollY": 200,
//"bPaginate": false,
"bFilter": true,
"bStateSave" : true,
"oLanguage": {
"sUrl": "../js/dataTables.italian.txt"
},
"aoColumns": [
null,
null,
{ "bSortable": true },
{ "bSortable": false }
],
"sPaginationType": "full_numbers",
"fnDrawCallback": function (o) {
window.scrollTo(0,0)
},
"aaSorting": [[ 2, "desc" ]]
//"bRetrieve": true
});
| 0debug
|
How to get all the input elements data of a current div : This is m HTML code:
<div data-repeater-item class="mt-repeater-item prescribeData">
<div class="mt-repeater-cell">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon input-circle-left capsule-lightblue">
<i class="fa fa-stethoscope blue-icon-font"></i>
</span>
<input type="text" id="prescribe_test" class="form-control typeahead-prescribetest input-circle-right" placeholder="Prescribe Test">
</div>
<span class="help-block">Name of Investigation</span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon input-circle-left capsule-lightblue">
<i class="fa fa-stethoscope blue-icon-font"></i>
</span>
<input type="text" id="diagnosis_input" class="form-control typeahead-diagnosis input-circle-right" placeholder="Duration of Investigation (Optional)">
</div>
<span class="help-block">e.g. Once, Weekly, Monthly</span>
</div>
</div>
</div>
</div>
</div>
I want to get all the input elements data in a variable using a JQuery code:
I am currently using this code:
$(this).closest($(".prescribeData :input"));
But this code doesn't display the data that the elements are holding after inputting in it.
Please, can anyone help me with this logic?
| 0debug
|
Can't find variable: React : <p>I just started learning react so I apologise in advance if this may sound like a stupid question.
I'm trying to make a simple iOS page with a button that triggers an action.
I have followed the tutorial on how to get started and this is my index code:</p>
<pre><code>'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
Component,
AlertIOS // Thanks Kent!
} = React;
class myProj extends Component {
render() {
return (
<View style={styles.container}>
<Text>
Welcome to React Native!
</Text>
<TouchableHighlight style={styles.button}
onPress={this.showAlert}>
<Text style={styles.buttonText}>Go</Text>
</TouchableHighlight>
</View>
);
}
showAlert() {
AlertIOS.alert('Awesome Alert', 'This is my first React Native alert.', [{text: 'Thanks'}] )
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFFFFF'
},
buttonText: {
fontSize: 18,
color: 'white',
alignSelf: 'center'
},
button: {
height: 44,
flexDirection: 'row',
backgroundColor: '#48BBEC',
alignSelf: 'stretch',
justifyContent: 'center'
}
});
AppRegistry.registerComponent('myProj', () => myProj);
</code></pre>
<p>The problem is that when I run it from Xcode on my device I get</p>
<pre><code>Can't find variable: React
render
main.jsbundle:1509:6
mountComponent
mountChildren
</code></pre>
<p>I tried to search online for the answer but couldn't find anything that actually help. Any idea what might be the problem here?</p>
| 0debug
|
Problem with CORS : Browser and CURL work but XMLHttpRequest don't : <p>A web server runs on my local network. Let's say on:
<a href="http://192.168.1.12" rel="nofollow noreferrer">http://192.168.1.12</a></p>
<p>When I visit this url with a browser, it's working fine.</p>
<p>When I visit this url with curl (zsh), it's working too:</p>
<p><code>curl -s "http://192.168.1.12/"</code></p>
<p>But when I try with javascript with XMLHttpRequest:</p>
<pre><code>var x = new XMLHttpRequest();
x.open("GET", "http://192.168.1.12/", true);
x.send(null);
</code></pre>
<p>it fails (error message translated):
CORS header "Access-Control-Allow-Origin" is missing.</p>
<p>I cannot modify the server behavior, but I think I don't need to because it's working with curl.
What should I add to my javascript code to make it work?</p>
| 0debug
|
int h263_decode_picture_header(MpegEncContext *s)
{
int format, width, height, i;
uint32_t startcode;
align_get_bits(&s->gb);
startcode= get_bits(&s->gb, 22-8);
for(i= s->gb.size_in_bits - get_bits_count(&s->gb); i>24; i-=8) {
startcode = ((startcode << 8) | get_bits(&s->gb, 8)) & 0x003FFFFF;
if(startcode == 0x20)
break;
}
if (startcode != 0x20) {
av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n");
return -1;
}
s->picture_number = get_bits(&s->gb, 8);
if (get_bits1(&s->gb) != 1) {
av_log(s->avctx, AV_LOG_ERROR, "Bad marker\n");
return -1;
}
if (get_bits1(&s->gb) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "Bad H263 id\n");
return -1;
}
skip_bits1(&s->gb);
skip_bits1(&s->gb);
skip_bits1(&s->gb);
s->gob_number = 0;
format = get_bits(&s->gb, 3);
if (format != 7 && format != 6) {
s->h263_plus = 0;
width = h263_format[format][0];
height = h263_format[format][1];
if (!width)
return -1;
s->pict_type = I_TYPE + get_bits1(&s->gb);
s->h263_long_vectors = get_bits1(&s->gb);
if (get_bits1(&s->gb) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "H263 SAC not supported\n");
return -1;
}
s->obmc= get_bits1(&s->gb);
s->unrestricted_mv = s->h263_long_vectors || s->obmc;
if (get_bits1(&s->gb) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "H263 PB frame not supported\n");
return -1;
}
s->qscale = get_bits(&s->gb, 5);
skip_bits1(&s->gb);
s->width = width;
s->height = height;
} else {
int ufep;
s->h263_plus = 1;
ufep = get_bits(&s->gb, 3);
if (ufep == 1) {
format = get_bits(&s->gb, 3);
dprintf("ufep=1, format: %d\n", format);
skip_bits(&s->gb,1);
s->umvplus = get_bits(&s->gb, 1);
skip_bits1(&s->gb);
s->obmc= get_bits1(&s->gb);
s->unrestricted_mv = s->umvplus || s->obmc;
s->h263_aic = get_bits1(&s->gb);
if (get_bits1(&s->gb) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "Deblocking Filter not supported\n");
}
if (get_bits1(&s->gb) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "Slice Structured not supported\n");
}
if (get_bits1(&s->gb) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "Reference Picture Selection not supported\n");
}
if (get_bits1(&s->gb) != 0) {
av_log(s->avctx, AV_LOG_ERROR, "Independent Segment Decoding not supported\n");
}
s->alt_inter_vlc= get_bits1(&s->gb);
s->modified_quant= get_bits1(&s->gb);
skip_bits(&s->gb, 1);
skip_bits(&s->gb, 3);
} else if (ufep != 0) {
av_log(s->avctx, AV_LOG_ERROR, "Bad UFEP type (%d)\n", ufep);
return -1;
}
s->pict_type = get_bits(&s->gb, 3) + I_TYPE;
if (s->pict_type == 8 && s->avctx->codec_tag == ff_get_fourcc("ZYGO"))
s->pict_type = I_TYPE;
if (s->pict_type != I_TYPE &&
s->pict_type != P_TYPE)
return -1;
skip_bits(&s->gb, 2);
s->no_rounding = get_bits1(&s->gb);
skip_bits(&s->gb, 4);
if (ufep) {
if (format == 6) {
s->aspect_ratio_info = get_bits(&s->gb, 4);
dprintf("aspect: %d\n", s->aspect_ratio_info);
width = (get_bits(&s->gb, 9) + 1) * 4;
skip_bits1(&s->gb);
height = get_bits(&s->gb, 9) * 4;
dprintf("\nH.263+ Custom picture: %dx%d\n",width,height);
if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 8);
s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 8);
}else{
s->avctx->sample_aspect_ratio= pixel_aspect[s->aspect_ratio_info];
}
} else {
width = h263_format[format][0];
height = h263_format[format][1];
}
if ((width == 0) || (height == 0))
return -1;
s->width = width;
s->height = height;
if (s->umvplus) {
if(get_bits1(&s->gb)==0)
skip_bits1(&s->gb);
}
}
s->qscale = get_bits(&s->gb, 5);
}
while (get_bits1(&s->gb) != 0) {
skip_bits(&s->gb, 8);
}
s->f_code = 1;
if(s->h263_aic){
s->y_dc_scale_table=
s->c_dc_scale_table= ff_aic_dc_scale_table;
}else{
s->y_dc_scale_table=
s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
}
if(s->avctx->debug&FF_DEBUG_PICT_INFO){
av_log(s->avctx, AV_LOG_DEBUG, "qp:%d %c size:%d rnd:%d%s%s%s%s%s%s%s\n",
s->qscale, av_get_pict_type_char(s->pict_type),
s->gb.size_in_bits, 1-s->no_rounding,
s->obmc ? " AP" : "",
s->umvplus ? " UMV" : "",
s->h263_long_vectors ? " LONG" : "",
s->h263_plus ? " +" : "",
s->h263_aic ? " AIC" : "",
s->alt_inter_vlc ? " AIV" : "",
s->modified_quant ? " MQ" : ""
);
}
#if 1
if (s->pict_type == I_TYPE && s->avctx->codec_tag == ff_get_fourcc("ZYGO")){
int i,j;
for(i=0; i<85; i++) av_log(s->avctx, AV_LOG_DEBUG, "%d", get_bits1(&s->gb));
av_log(s->avctx, AV_LOG_DEBUG, "\n");
for(i=0; i<13; i++){
for(j=0; j<3; j++){
int v= get_bits(&s->gb, 8);
v |= get_sbits(&s->gb, 8)<<8;
av_log(s->avctx, AV_LOG_DEBUG, " %5d", v);
}
av_log(s->avctx, AV_LOG_DEBUG, "\n");
}
for(i=0; i<50; i++) av_log(s->avctx, AV_LOG_DEBUG, "%d", get_bits1(&s->gb));
}
#endif
return 0;
}
| 1threat
|
static void nbd_client_close(NBDClient *client)
{
qemu_set_fd_handler2(client->sock, NULL, NULL, NULL, NULL);
close(client->sock);
client->sock = -1;
if (client->close) {
client->close(client);
}
nbd_client_put(client);
}
| 1threat
|
Installing NodeJS LTS for Ansible : <p>I'm looking for an appropriate Ansible Role or Ansible YAML file for installing NodeJS LTS on a Ubuntu 16.04.3 xenial system. I tried more than 10 Ansible roles from Galaxy but didn't find any of them working (throws error such as <code>potentially dangerous to add this PPA etc.</code>.</p>
<p>Can anyone provide any Ansible playbook or suggest me a role to install NodeJS LTS on Ubuntu 16.04?</p>
| 0debug
|
React Router - how to constrain params in route matching? : <p>I don't really get how to constrain params with, for example a regex.<br>
How to differentiate these two routes?</p>
<pre><code> <Router>
<Route path="/:alpha_index" component={Child1} />
<Route path="/:numeric_index" component={Child2} />
</Router>
</code></pre>
<p>And prevent "/123" from firing the first route?</p>
| 0debug
|
static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
{
int i, x;
if (s->buf_end - s->buf < 1)
return AVERROR_INVALIDDATA;
x = bytestream_get_byte(&s->buf);
q->nguardbits = x >> 5;
q->quantsty = x & 0x1f;
if (q->quantsty == JPEG2000_QSTY_NONE) {
n -= 3;
if (s->buf_end - s->buf < n)
return AVERROR_INVALIDDATA;
for (i = 0; i < n; i++)
q->expn[i] = bytestream_get_byte(&s->buf) >> 3;
} else if (q->quantsty == JPEG2000_QSTY_SI) {
if (s->buf_end - s->buf < 2)
return AVERROR_INVALIDDATA;
x = bytestream_get_be16(&s->buf);
q->expn[0] = x >> 11;
q->mant[0] = x & 0x7ff;
for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) {
int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
q->expn[i] = curexpn;
q->mant[i] = q->mant[0];
}
} else {
n = (n - 3) >> 1;
if (s->buf_end - s->buf < n)
return AVERROR_INVALIDDATA;
for (i = 0; i < n; i++) {
x = bytestream_get_be16(&s->buf);
q->expn[i] = x >> 11;
q->mant[i] = x & 0x7ff;
}
}
return 0;
}
| 1threat
|
How to show a variable "sentence" in a TextView : <p>I have a dilemma.
I've created this random sentence generator script for java. And I want to show "sentence" in a text view like you would print it out to the system on line 25 in android studio.</p>
<p>Here's my Random Sentence Generator Code</p>
<pre><code>package com.tech.littlest.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.Random;
public class Activity2 extends AppCompatActivity {
final static int NO_DEDICATED_ARRAYS = 12; // This number is equal to the number of arrays in a string NOTE: This number MUST be constant across all strings
final static int NO_OUTPUT_SENTENCES = 1; // How many sentences generated and displayed for the user
final static String SPACER = " "; // Inputs a " " character (Space) into the display
final static String PERIOD = ".";
static Random r = new Random();
public static void main( String args[] ){
String proposition_user[] = { "You should build and invention that", "You should build a robot that", "You should create a whatchamacallit that", "There should be a device that", "Create a futuristic thing that", "Make a thing that", "Make something cool that", "I don't recall there being a thing that", "Create a sick thing that", "Devise a plan to create an object that", "I want a thing that", "If I just had an thingamajig that", "Create a thingimajig that"};
String plural_noun[] = { "children", "chickens", "the ocean", "cars", "apples", "houses", "water", "buildings", "people", "your friends", "farms", "the human race" };
String verb[] = { "directs you to", "drives on", "manages", "develops", "makes","eats", "helps", "relocates", "fixes", "feeds", "runs on", "washes" };
String sentence;
for (int i = 0; i < NO_OUTPUT_SENTENCES; i++){
sentence = proposition_user[rand()];
char c = sentence.charAt(0);
sentence = sentence.replace( c, Character.toUpperCase(c) );
sentence += SPACER;
sentence += (verb[rand()]);
sentence += (SPACER + plural_noun[rand()]);
sentence += PERIOD;
sentence += "";
System.out.println(sentence);
}
}
static int rand(){
int ri = r.nextInt() % NO_DEDICATED_ARRAYS;
if ( ri < 0 )
ri += NO_DEDICATED_ARRAYS;
return ri;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
}
}
</code></pre>
<p>My XML file with my textview</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tech.littlest.myapplication.Activity2">
<TextView
android:id="@+id/mytextview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</code></pre>
<p>Thanks!</p>
| 0debug
|
Text to Colomn in Python : def Text2Col(df_File):
for i in range(0,len(df_File)):
with open(df_File.iloc[i]['Input']) as inf:
with open(df_File.iloc[i]['Output'], 'w') as outf:
i=0
for line in inf:
i=i+1
if i==2 or i==3:
continue
outf.write(','.join(line.split(';')))
Above code is used to convert a csv file from text to column.
This code makes all values string ( because split() ) which is problematic for me.
I tried using map function but cant make it.
Is there any other way in which I can do this.
My input file has 5 column, First column is string, second is int and rest are float.
I think it required some modification in last statement
outf.write(','.join(line.split(';')))
Please let me know if any other input is required.
| 0debug
|
C++ pointer not storing value : <pre><code>word word::Addstr(char * &arr)
{
char * baka = nullptr;
if (sent != nullptr)
{
baka = new char[size + strlen(arr) + 3];
for (int i = 0; i < size; i++)
{
baka[i] = sent[i];
}
baka[size] = ' ';
int a = 0;
for (int i = size +2; i < size + strlen(arr) + 3; i++)
{
baka[i] = arr[a];
a++;
}
}
else
{
baka = new char[strlen(arr) + 1];
for (int i = 0; i < strlen(arr) + 1; i++)
{
baka[i] = arr[i];
}
}
word ustad(baka);
return ustad;
}
</code></pre>
<p>Here in the second loop char *baka is not storing arr[]'s value. I have sent the char pointer by reference yet still it's not working.</p>
<pre><code>for (int i = size +2; i < size + strlen(arr) + 3; i++)
{
baka[i] = arr[a];
a++;
}
</code></pre>
<p>The constructors and all other things are accurate. Baka stores value in the first loop but in the second one it doesn't. Even here:</p>
<pre><code>baka[size] = ' ';
</code></pre>
<p>Can someone pleases help with this!</p>
| 0debug
|
downloading pdf files using php : <p>I have PHP files stored on my server, and their names in the mysql database, I want to download those files. What code should I write for the same? I am using PHP as coding language. Please help.</p>
| 0debug
|
static void qemu_wait_io_event(CPUState *env)
{
while (!tcg_has_work())
qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
qemu_mutex_unlock(&qemu_global_mutex);
qemu_mutex_lock(&qemu_fair_mutex);
qemu_mutex_unlock(&qemu_fair_mutex);
qemu_mutex_lock(&qemu_global_mutex);
qemu_wait_io_event_common(env);
}
| 1threat
|
static void omap_tcmi_init(MemoryRegion *memory, target_phys_addr_t base,
struct omap_mpu_state_s *mpu)
{
memory_region_init_io(&mpu->tcmi_iomem, &omap_tcmi_ops, mpu,
"omap-tcmi", 0x100);
memory_region_add_subregion(memory, base, &mpu->tcmi_iomem);
omap_tcmi_reset(mpu);
}
| 1threat
|
Why does the compiler allow throws when the method will never throw the Exception : <p>I am wondering why the java compiler allows throws in the method declaration when the method will never throw the Exception. Because "throws" is a way of handling the exception (telling the caller to handle it).</p>
<p>Since there are two ways of handling exception (throws & try/catch). In a try/catch, it doesn't allow the catch of an exception not thrown in the try block but it allows a throws in a method that does may not throw the exception.</p>
<pre><code>private static void methodA() {
try {
// Do something
// No IO operation here
} catch (IOException ex) { //This line does not compile because
//exception is never thrown from try
// Handle
}
}
private static void methodB() throws IOException { //Why does this //compile when excetion is never thrown in function body
//Do Something
//No IO operation
}
</code></pre>
| 0debug
|
Registering vue components globally : <p>I have a vue app that I created using the vue-cli</p>
<p>Im creating some components and I want to use them like this:</p>
<pre><code><template>
<oi-list>
<oi-list-header>Task ID</oi-list-header>
<oi-list-header>Tasks Title</oi-list-header>
<oi-list-header>Task Status</oi-list-header>
<div v-for="task in tasks">
<oi-list-item>{{ task.id }}</oi-list-item>
<oi-list-item>{{ task.title }}</oi-list-item>
<oi-list-item>{{ task.status }}</oi-list-item>
</div>
</oi-list>
</tempalte>
</code></pre>
<p>The probelm I have is where ever I use the list component I have to write the following:</p>
<pre><code><script>
import List from '@/components/List'
import ListHeader from '@/components/ListHeader'
import ListItem from '@/components/ListItem'
export default {
name: "Tasks",
components: {
'oi-list': List,
'oi-list-header': ListHeader,
'oi-list-item': ListItem
}
<script>
</code></pre>
<p>What I would like is for reusable components to either be registered globally so i dont have to import them and their sub components every time i want to use them, or some how have them load dynamically when I use them. Is this possible?</p>
<p>I have used <a href="https://vuetifyjs.com/en/" rel="noreferrer">Vuetify</a> in the past and that doesn't require you to import each component in order to use it.</p>
<p>Please can someone point me in the right direction? Thanks.</p>
| 0debug
|
std::in_place_t and friends in C++17 : <p>As of the time of writing, cppreference gives a <a href="http://en.cppreference.com/w/cpp/utility/in_place" rel="noreferrer">reasonably simple definition</a> of the <code>std::in_place_t</code> family:</p>
<pre><code>struct in_place_t {
explicit in_place_t() = default;
};
inline constexpr std::in_place_t in_place{};
template <class T>
struct in_place_type_t {
explicit in_place_type_t() = default;
};
template <class T>
inline constexpr std::in_place_type_t<T> in_place_type{};
template <size_t I> struct in_place_index_t {
explicit in_place_index_t() = default;
};
template <size_t I>
inline constexpr in_place_index_t<I> in_place_index{};
</code></pre>
<p>However, the latest draft of the C++17 standard <a href="http://open-std.org/JTC1/SC22/WG21/docs/papers/2016/n4606.pdf" rel="noreferrer">linked from isocpp.org</a> has a rather more complicated definition (section 20.2.7, page 536):</p>
<pre><code>struct in_place_tag {
in_place_tag() = delete;
};
using in_place_t = in_place_tag(&)(unspecified );
template <class T>
using in_place_type_t = in_place_tag(&)(unspecified <T>);
template <size_t I>
using in_place_index_t = in_place_tag(&)(unspecified <I>);
in_place_tag in_place(unspecified );
template <class T>
in_place_tag in_place(unspecified <T>);
template <size_t I>
in_place_tag in_place(unspecified <I>);
</code></pre>
<p>The first version is simple and easy to understand, but second version is quite opaque to me. So, questions:</p>
<ul>
<li><p>Which version is correct, post-Issaqua (November 2016)? (Presumably the second, but it's possible that N4606 hasn't yet been updated after the latest meeting and cppreference has.)</p></li>
<li><p>Clearly this has changed at some point in time; does anyone have a link to a paper mentioning the change?</p></li>
<li><p>Most importantly, can anyone explain how the second version is intended to work? What would a sample implementation look like?</p></li>
</ul>
| 0debug
|
uint16_t acpi_pm1_evt_get_sts(ACPIREGS *ar)
{
int64_t d = acpi_pm_tmr_get_clock();
if (d >= ar->tmr.overflow_time) {
ar->pm1.evt.sts |= ACPI_BITMASK_TIMER_STATUS;
}
return ar->pm1.evt.sts;
}
| 1threat
|
static uint8_t get_sot(Jpeg2000DecoderContext *s, int n)
{
Jpeg2000TilePart *tp;
uint16_t Isot;
uint32_t Psot;
uint8_t TPsot;
if (s->buf_end - s->buf < 4)
return AVERROR(EINVAL);
Isot = bytestream_get_be16(&s->buf);
if (Isot) {
av_log(s->avctx, AV_LOG_ERROR,
"Not a DCINEMA JP2K file: more than one tile\n");
return -1;
}
Psot = bytestream_get_be32(&s->buf);
TPsot = bytestream_get_byte(&s->buf);
bytestream_get_byte(&s->buf);
tp = s->tile[s->curtileno].tile_part + TPsot;
tp->tile_index = Isot;
tp->tp_len = Psot;
tp->tp_idx = TPsot;
if (JPEG2000_SOD == bytestream_get_be16(&s->buf))
tp->tp_start_bstrm = s->buf;
else {
av_log(s->avctx, AV_LOG_ERROR, "SOD marker not found \n");
return -1;
}
tp->tp_end_bstrm = s->buf + (tp->tp_len - n - 4);
s->buf = tp->tp_end_bstrm;
return 0;
}
| 1threat
|
ls and ls -la not displaying a file that I am trying to compile (Java) : <p><a href="http://i.stack.imgur.com/QgqND.png" rel="nofollow">ls and ls -la commands are not displaying files that I want to compile. Why are my files not showing up? </a></p>
| 0debug
|
Convert List<String> to string C# - asp.net - sql server - : <p>I am new to this and I am asking for help to convert a string type data, I made an sql connection where I returned a name, address and phone number found in another table</p>
<p><a href="https://i.stack.imgur.com/7UVEp.png" rel="nofollow noreferrer"><code>List string eTelefono</code></a>
<a href="https://i.stack.imgur.com/VNAOq.png" rel="nofollow noreferrer"> <code>while _Reader.Read</code></a>
<a href="https://i.stack.imgur.com/z9Ud6.png" rel="nofollow noreferrer">Builder</a></p>
<p>(If you see something in spanish is beacause im from Uruguay)
This the error
<a href="https://i.stack.imgur.com/6TxWB.png" rel="nofollow noreferrer"><code>error System.String to System.Collections.Generic.List 1 System.String</code></a></p>
<p>Does anyone know how to convert <code>List <string></code> to <code>string</code>?</p>
<p>Thanks!
If you need more captures just ask</p>
| 0debug
|
How to make a for-loop more understandable in python? : <p>I am currently teaching some python programming to some fairly young students. One thing I want them to learn is how to write a for-loop.</p>
<p>So far, the way I have shown it to the students is like this:</p>
<pre><code>for i in range(1,11):
print(i)
</code></pre>
<p>which gives a loop where <code>i</code> goes from 1 to 10.</p>
<p>My problem is that it seems strange to students that they need to write 11 as the second argument to <code>range(1,11)</code> when they want the loop to go up to 10. The students find this confusing.</p>
<p>In C/C++ and related languages, such a loop can be written like this:</p>
<pre><code>for(int i = 1; i <= 10; i++)
{ /* do something */ }
</code></pre>
<p>It seems to me like the C++ way of expressing the loop is more intuitive since in that case I can explicitly write 1 and 10 which are the first and last values that I want the loop variable to take.</p>
<p>When working with for-loops in python, I end up telling the students something like <em>"we just have to accept that we need to write 11 when we want the loop to go to 10, it is a bit annoying but you just have to learn that the range function works in that way"</em>. I am not happy about that; I want them to learn that programming is fun and I am afraid this kind of thing makes it less fun.</p>
<p>Since python is often described as a language emphasizing readability, I suspect there is a nicer way to express a for-loop, a way that would cause less confusion for my students.</p>
<p>Is there a better and/or less confusing way to express this kind of for-loop in the python language?</p>
| 0debug
|
int inet_dgram_opts(QemuOpts *opts, Error **errp)
{
struct addrinfo ai, *peer = NULL, *local = NULL;
const char *addr;
const char *port;
int sock = -1, rc;
memset(&ai,0, sizeof(ai));
ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
ai.ai_family = PF_UNSPEC;
ai.ai_socktype = SOCK_DGRAM;
addr = qemu_opt_get(opts, "host");
port = qemu_opt_get(opts, "port");
if (addr == NULL || strlen(addr) == 0) {
addr = "localhost";
}
if (port == NULL || strlen(port) == 0) {
error_setg(errp, "remote port not specified");
return -1;
}
if (qemu_opt_get_bool(opts, "ipv4", 0))
ai.ai_family = PF_INET;
if (qemu_opt_get_bool(opts, "ipv6", 0))
ai.ai_family = PF_INET6;
if (0 != (rc = getaddrinfo(addr, port, &ai, &peer))) {
error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
gai_strerror(rc));
return -1;
}
memset(&ai,0, sizeof(ai));
ai.ai_flags = AI_PASSIVE;
ai.ai_family = peer->ai_family;
ai.ai_socktype = SOCK_DGRAM;
addr = qemu_opt_get(opts, "localaddr");
port = qemu_opt_get(opts, "localport");
if (addr == NULL || strlen(addr) == 0) {
addr = NULL;
}
if (!port || strlen(port) == 0)
port = "0";
if (0 != (rc = getaddrinfo(addr, port, &ai, &local))) {
error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
gai_strerror(rc));
goto err;
}
sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
if (sock < 0) {
error_setg_errno(errp, errno, "Failed to create socket");
goto err;
}
socket_set_fast_reuse(sock);
if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
error_setg_errno(errp, errno, "Failed to bind socket");
goto err;
}
if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
error_setg_errno(errp, errno, "Failed to connect socket");
goto err;
}
freeaddrinfo(local);
freeaddrinfo(peer);
return sock;
err:
if (-1 != sock)
closesocket(sock);
if (local)
freeaddrinfo(local);
if (peer)
freeaddrinfo(peer);
return -1;
}
| 1threat
|
Nested Json Array into Mysql with PHP : <p>This is my first time working with json, just playing around with some data.</p>
<p>This is part of my json</p>
<pre><code>Array
(
[DataSet] => Array
(
[Table] => Array
(
[0] => Array
(
[Driver] => John Doe
[Shift Date] => 2018-01-05T00:00:00-05:00
</code></pre>
<p>I want to be able to get all the [Driver] and [Shift Date] fields and put them into a table. It has 2 columns Driver and ShiftDate, not sure where I go from here. </p>
| 0debug
|
[HELP]Website layout not positioning right : I am trying to make a template for my website from scratch and everything was going good until I wanted to make a news bar underneath my navbar and welcome message bar. For some reason the spot that would be for news goes above the navbar and I can't figure out why!
[Screenshot of what my webpage looks like.][1]
[1]: https://i.stack.imgur.com/iOA2Q.png
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
body {
margin: 0;
background: #0e0e0f;
font-family: Impact;
font-size: 22px;
}
#navbar{
text-align: left;
margin-top: 55px;
}
#navbar ul li{
display: inline;
text-align: center;
}
#navbar ul li{
margin: 10px;
color:rgba(255, 255, 255, 0.2);
text-transform: uppercase;
}
#navbar ul li a{
text-decoration: none;
}
#navbar ul li a:hover{
color: yellow;
}
#navbar ul li a:visited{
text-decoration: none;
color:rgba(255, 255, 255, 0.2);
}
#navbar ul li a:visited:hover{
text-decoration: none;
color: yellow;
}
#top-container{
margin: 0;
background: black:;
background: linear-gradient(black, grey);
width: 100%;
height: 650px;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
position: absolute;
}
#welcome-message{
margin: 250px 150px 100px 300px;
color: white;
}
.main-content{
width: 100%;
height: 650px;
background: #1f1f21;
background-size: cover;
margin-top: 700px;
}
<!-- language: lang-html -->
<!DOCTYPE html>
<html>
<head>
<title>Placeholder</title>
<link rel="stylesheet" type="text/css" href="styles.css"/>
</head>
<body>
<div id="top-container">
<nav id="navbar">
<ul>
<li><a href="#Home" class="active">Place Holder</a></li>
<li><a href="#">Place Holder</a></li>
<li><a href="#">Place Holder</a></li>
<li><a href="#">Place Holder</a></li>
<li><a href="#">Place Holder</a></li>
<li><a href="#">Place Holder</a></li>
</ul>
</nav>
<h1 id="welcome-message">Welcome to<br>
Place holder!</h1>
</div>
<div class="main-content">
<h1>News Placeholder</h1></div>
</div>
</body>
</html>
<!-- end snippet -->
| 0debug
|
Choosing number of Steps per Epoch : <p>If I want to train a model with train_generator, is there a significant difference between chosing</p>
<ul>
<li>10 Epochs with 500 Steps each</li>
</ul>
<p>and</p>
<ul>
<li>100 Epochs with 50 Steps each</li>
</ul>
<p>Currently I am training for 10 epochs, because each epoch takes a long time, but any graph showing improvement looks very "jumpy" because I only have 10 datapoints. I figure I can get a smoother graph if I use 100 Epochs, but I want to know first if there is any downside to this </p>
| 0debug
|
Using template metaprogramming in C++, find the GCD of two integers : <p>I want to know a <strong>template meta-programming</strong> solution to the problem of finding the GCD of two numbers using using the recursive Euclid's Algorithm, given below for your reference. </p>
<pre><code>function gcd(a, b)
if b = 0
return a;
else
return gcd(b, a mod b);
</code></pre>
<p>Any help would be highly appreciated!</p>
| 0debug
|
how get data from database by matching first two characters in a columns usinh like query or something else : I am trying to get data from database by matching first two characters or the characters appears before comma `,`
id | company_name | country_id | city_id | main_category
-------------------------------------------------------
1 | ABC | 1 | 2 | 12,3,6
2 | XYZ | 1 | 2 | 1,12,9
what i want is to get the following results when the user input is `12` and if `12` exist in main_category than result should be shown but the `12` should be exits before the first comma or we can say the first two characters
id | company_name | country_id | city_id | main_category
-------------------------------------------------------
1 | ABC | 1 | 2 | 12,3,6
Query i tried
$getResult = $compaies->where([
["company_name", "LIKE", "%$keyword%"],
['main_category', "LIKE", "%$sector%"]
])->get();
| 0debug
|
Can I have a do while statement in C++ that checks for both a character and a int value before looping? : <p>I very new at this and have an assignment in which I would like for a loop to exit if the user inputs(trans) 'e' but also end if a calculation balance(bal) is less than a constant I have set. Basically as my question states one is a character and the other an integer, will that work? I'm not trying to get people to do my homework for me, so I'm not posting all of my code or assignment, hope it makes sense.</p>
<pre><code>This is the line of code I have
do {
ask user input(&trans)
e or calculation
{
while (trans != 'e'| bal < -OVR);
</code></pre>
| 0debug
|
static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVQcowState *s = bs->opaque;
int len, i, shift, ret;
QCowHeader header;
ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
if (ret < 0) {
be32_to_cpus(&header.magic);
be32_to_cpus(&header.version);
be64_to_cpus(&header.backing_file_offset);
be32_to_cpus(&header.backing_file_size);
be32_to_cpus(&header.mtime);
be64_to_cpus(&header.size);
be32_to_cpus(&header.crypt_method);
be64_to_cpus(&header.l1_table_offset);
if (header.magic != QCOW_MAGIC) {
error_setg(errp, "Image not in qcow format");
if (header.version != QCOW_VERSION) {
char version[64];
snprintf(version, sizeof(version), "QCOW version %" PRIu32,
header.version);
error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
bs->device_name, "qcow", version);
ret = -ENOTSUP;
if (header.size <= 1) {
error_setg(errp, "Image size is too small (must be at least 2 bytes)");
if (header.cluster_bits < 9 || header.cluster_bits > 16) {
error_setg(errp, "Cluster size must be between 512 and 64k");
if (header.crypt_method > QCOW_CRYPT_AES) {
error_setg(errp, "invalid encryption method in qcow header");
s->crypt_method_header = header.crypt_method;
if (s->crypt_method_header) {
bs->encrypted = 1;
s->cluster_bits = header.cluster_bits;
s->cluster_size = 1 << s->cluster_bits;
s->cluster_sectors = 1 << (s->cluster_bits - 9);
s->l2_bits = header.l2_bits;
s->l2_size = 1 << s->l2_bits;
bs->total_sectors = header.size / 512;
s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
shift = s->cluster_bits + s->l2_bits;
s->l1_size = (header.size + (1LL << shift) - 1) >> shift;
s->l1_table_offset = header.l1_table_offset;
s->l1_table = g_malloc(s->l1_size * sizeof(uint64_t));
ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
s->l1_size * sizeof(uint64_t));
if (ret < 0) {
for(i = 0;i < s->l1_size; i++) {
be64_to_cpus(&s->l1_table[i]);
s->l2_cache = g_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
s->cluster_cache = g_malloc(s->cluster_size);
s->cluster_data = g_malloc(s->cluster_size);
s->cluster_cache_offset = -1;
if (header.backing_file_offset != 0) {
len = header.backing_file_size;
if (len > 1023) {
len = 1023;
ret = bdrv_pread(bs->file, header.backing_file_offset,
bs->backing_file, len);
if (ret < 0) {
bs->backing_file[len] = '\0';
error_set(&s->migration_blocker,
QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
"qcow", bs->device_name, "live migration");
migrate_add_blocker(s->migration_blocker);
qemu_co_mutex_init(&s->lock);
return 0;
fail:
g_free(s->l1_table);
g_free(s->l2_cache);
g_free(s->cluster_cache);
g_free(s->cluster_data);
return ret;
| 1threat
|
ActiveRecord log which query went to which database : <p>In an ActiveRecord application with multiple connections to different databases, nothing in the log indicates which query went to which database. These queries to separate databases:</p>
<pre><code>Base1.connection.select_value("select * from foo")
Base2.connection.select_value("select * from foo")
</code></pre>
<p>Emit these log entries:</p>
<pre><code>D, [2017-03-13T09:27:11.844395 #22112] DEBUG -- : (0.6ms) select * from foo
D, [2017-03-13T09:27:11.844539 #22112] DEBUG -- : (0.1ms) select * from foo
</code></pre>
<p>How can I cause the ActiveRecord database log to indicate which database a query was being done against?</p>
<h1>Standalone example</h1>
<pre><code>begin
require "bundler/inline"
rescue LoadError => e
$stderr.puts "Bundler version 1.10 or later is required."
raise e
end
gemfile(true) do
source "https://rubygems.org"
# Activate the gem you are reporting the issue against.
gem "activerecord", "4.2.8"
gem "sqlite3"
end
require "active_record"
require "logger"
class Base1 < ActiveRecord::Base
self.abstract_class = true
end
class Base2 < ActiveRecord::Base
self.abstract_class = true
end
Base1.establish_connection(adapter: "sqlite3", database: ":memory:")
Base2.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
Base1.connection.execute("create table foo(i int)")
Base2.connection.execute("create table foo(i int)")
Base1.connection.execute("insert into foo(i) values (1)")
Base2.connection.execute("insert into foo(i) values (2)")
raise unless Base1.connection.select_value("select * from foo") == 1
raise unless Base2.connection.select_value("select * from foo") == 2
</code></pre>
<p>The output:</p>
<pre><code>D, [2017-03-13T09:27:11.842939 #22112] DEBUG -- : (0.2ms) create table foo(i int)
D, [2017-03-13T09:27:11.843478 #22112] DEBUG -- : (0.2ms) create table foo(i int)
D, [2017-03-13T09:27:11.843612 #22112] DEBUG -- : (0.1ms) insert into foo(i) values (1)
D, [2017-03-13T09:27:11.843720 #22112] DEBUG -- : (0.0ms) insert into foo(i) values (2)
D, [2017-03-13T09:27:11.844395 #22112] DEBUG -- : (0.6ms) select * from foo
D, [2017-03-13T09:27:11.844539 #22112] DEBUG -- : (0.1ms) select * from foo
</code></pre>
<h1>I tried creating a separate logger for each connection</h1>
<p>I tried giving each connection its own logger, so that I could change each log's formatting:</p>
<pre><code>Base1.logger = Logger.new(STDOUT)
Base2.logger = Logger.new(STDOUT)
</code></pre>
<p>But, unfortunately, there appears to be only one logger in ActiveRecord, as shown by this line which does not raise an exception:</p>
<pre><code>raise unless Base1.logger.object_id == Base2.logger.object_id
</code></pre>
<h1>Versions</h1>
<ul>
<li>ruby-2.3.3</li>
<li>activerecord 4.2.8</li>
<li>In this example, sqlite3 1.13.3 (1)</li>
<li>In production, mysql2 0.4.5 (1) and activerecord-sqlserver-adapter 4.2.15 (1)</li>
</ul>
<p>(1) This problem is not specific to any particular database adapter. I've listed adapter versions for completeness.</p>
| 0debug
|
How to use USB drive as remote : <p>I have local copies of a GitHub repo on Laptop and Desktop. The Desktop is ahead of the Laptop and the remote GitHub <code>origin</code>. I want to pull changes onto the Laptop, but don't want to push to the public <code>origin</code>. How do I set up a USB stick/external HDD as a remote?</p>
| 0debug
|
Is it good to use two tables seperately, or one table with both data within? : Is it good to do:
**Phone Table:**
id name
1 blabla
2 blabla
3 blabla
.
..
**Laptop Table:**
id name
1 blabla
2 blabla
3 blabla
.
..
**OR**
**Products Table:**
id name type
1 blabla laptop
2 blabla phone
3 blabla laptop
.
..
Thanks All :)
| 0debug
|
Puppeteer: pass variable in .evaluate() : <p>I'm trying to pass a variable into a <code>page.evaluate()</code> function in <a href="https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pageevaluatepagefunction-args" rel="noreferrer">Puppeteer</a>, but when I use the following very simplified example, the variable <code>evalVar</code> is undefined.</p>
<p>I'm new to Puppeteer and can't find any examples to build on, so I need help passing that variable into the <code>page.evaluate()</code> function so I can use it inside.</p>
<pre><code>const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
const evalVar = 'WHUT??';
try {
await page.goto('https://www.google.com.au');
await page.waitForSelector('#fbar');
const links = await page.evaluate((evalVar) => {
console.log('evalVar:', evalVar); // appears undefined
const urls = [];
hrefs = document.querySelectorAll('#fbar #fsl a');
hrefs.forEach(function(el) {
urls.push(el.href);
});
return urls;
})
console.log('links:', links);
} catch (err) {
console.log('ERR:', err.message);
} finally {
// browser.close();
}
})();
</code></pre>
| 0debug
|
Vue 2.0 setting up routes - Do not use 'new' for side effects : <p>I am configuring a vue project. I used the webpack template. ( npm install init webpack ). I am getting an error in the terminal -- </p>
<pre><code>ERROR in ./src/main.js
✘ http://eslint.org/docs/rules/no-new Do not use 'new' for side effects
/Users/uz067252/Documents/Development/Vue/workex/vue-project/src/main.js:21:1
new Vue({
^
✘ 1 problem (1 error, 0 warnings)
Errors:
1 http://eslint.org/docs/rules/no-new
</code></pre>
<p>Here's the main.js</p>
<pre><code>import Vue from 'vue'
import App from './App.vue'
import Hello from './components/Hello.vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
// We want to apply VueResource and VueRouter
// to our Vue instance
Vue.use(VueResource)
Vue.use(VueRouter)
// Pointing routes to the components they should use
var router = new VueRouter({
routes: [
{ path: '/hello', component: Hello },
{ path: '*', redirect: '/hello' }
]
})
new Vue({
el: '#app',
router: router,
render: h => h(App)
})
</code></pre>
<p>Thanks</p>
| 0debug
|
Range of unicode characters GHC accepts : <p>This may sound a bit ridiculous, but GHC fails to compile my string containing bacon, a croissant, cucumber, and a potato:</p>
<pre><code>main = putStrLn "🥓 🥐 🥒 🥔"
</code></pre>
<p>I realize I could easily write</p>
<pre><code>main = putStrLn "\x1F953 \x1F950 \x1F952 \x1F954"
</code></pre>
<p>to the same effect, but I had always assumed GHC would accept any unicode in its source. So: <strong>what are the actual restrictions on unicode characters GHC accepts in source files</strong>?</p>
<hr>
<p>BTW: I realize that supporting this sort of thing is hell for the GHC lexer (actually I ran across the above problem while writing test cases for a lexer I wrote), but I still am a tad bit disappointed.</p>
| 0debug
|
Integration testing with in-memory IdentityServer : <p>I have an API that uses IdentityServer4 for token validation.
I want to unit test this API with an in-memory TestServer. I'd like to host the IdentityServer in the in-memory TestServer. </p>
<p>I have managed to create a token from the IdentityServer. </p>
<p>This is how far I've come, but I get an error "Unable to obtain configuration from <a href="http://localhost:54100/.well-known/openid-configuration" rel="noreferrer">http://localhost:54100/.well-known/openid-configuration</a>"</p>
<p>The Api uses [Authorize]-attribute with different policies. This is what I want to test. </p>
<p>Can this be done, and what am I doing wrong?
I have tried to look at the source code for IdentityServer4, but have not come across a similar integration test scenario. </p>
<pre><code>protected IntegrationTestBase()
{
var startupAssembly = typeof(Startup).GetTypeInfo().Assembly;
_contentRoot = SolutionPathUtility.GetProjectPath(@"<my project path>", startupAssembly);
Configure(_contentRoot);
var orderApiServerBuilder = new WebHostBuilder()
.UseContentRoot(_contentRoot)
.ConfigureServices(InitializeServices)
.UseStartup<Startup>();
orderApiServerBuilder.Configure(ConfigureApp);
OrderApiTestServer = new TestServer(orderApiServerBuilder);
HttpClient = OrderApiTestServer.CreateClient();
}
private void InitializeServices(IServiceCollection services)
{
var cert = new X509Certificate2(Path.Combine(_contentRoot, "idsvr3test.pfx"), "idsrv3test");
services.AddIdentityServer(options =>
{
options.IssuerUri = "http://localhost:54100";
})
.AddInMemoryClients(Clients.Get())
.AddInMemoryScopes(Scopes.Get())
.AddInMemoryUsers(Users.Get())
.SetSigningCredential(cert);
services.AddAuthorization(options =>
{
options.AddPolicy(OrderApiConstants.StoreIdPolicyName, policy => policy.Requirements.Add(new StoreIdRequirement("storeId")));
});
services.AddSingleton<IPersistedGrantStore, InMemoryPersistedGrantStore>();
services.AddSingleton(_orderManagerMock.Object);
services.AddMvc();
}
private void ConfigureApp(IApplicationBuilder app)
{
app.UseIdentityServer();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
var options = new IdentityServerAuthenticationOptions
{
Authority = _appsettings.IdentityServerAddress,
RequireHttpsMetadata = false,
ScopeName = _appsettings.IdentityServerScopeName,
AutomaticAuthenticate = false
};
app.UseIdentityServerAuthentication(options);
app.UseMvc();
}
</code></pre>
<p>And in my unit-test: </p>
<pre><code>private HttpMessageHandler _handler;
const string TokenEndpoint = "http://localhost/connect/token";
public Test()
{
_handler = OrderApiTestServer.CreateHandler();
}
[Fact]
public async Task LeTest()
{
var accessToken = await GetToken();
HttpClient.SetBearerToken(accessToken);
var httpResponseMessage = await HttpClient.GetAsync("stores/11/orders/asdf"); // Fails on this line
}
private async Task<string> GetToken()
{
var client = new TokenClient(TokenEndpoint, "client", "secret", innerHttpMessageHandler: _handler);
var response = await client.RequestClientCredentialsAsync("TheMOON.OrderApi");
return response.AccessToken;
}
</code></pre>
| 0debug
|
static int mmu_translate_pte(CPUS390XState *env, target_ulong vaddr,
uint64_t asc, uint64_t asce,
target_ulong *raddr, int *flags, int rw)
{
if (asce & _PAGE_INVALID) {
DPRINTF("%s: PTE=0x%" PRIx64 " invalid\n", __func__, asce);
trigger_page_fault(env, vaddr, PGM_PAGE_TRANS, asc, rw);
return -1;
}
if (asce & _PAGE_RO) {
*flags &= ~PAGE_WRITE;
}
*raddr = asce & _ASCE_ORIGIN;
PTE_DPRINTF("%s: PTE=0x%" PRIx64 "\n", __func__, asce);
return 0;
}
| 1threat
|
How to inverse an array without forming a new one in C/C++ : I wanted to write a function that would inverse an array and would print the inverted array without forming a new one.
I wrote a code that can inverse an array, but I have to form a new array in order to do that.
```c++
#include<iostream>
using namespace std;
void inverse(int arr[], int size) {
int arr2[size];
for (int i = 0; i < size; i++)
arr2[arr[i] - 1] = i + 1;
for (int i = 0; i < size; i++)
cout << arr2[i] << " ";
}
int main() {
int arr[] = {2, 3, 4, 5, 1};
int size = sizeof(arr) / sizeof(arr[0]);
inverse(arr, size);
return 0;
}
```
| 0debug
|
how to get logitude and latitude from firebase real time database and display the location markers in android google map api? : i am building an android app to track the location of the multiple devices. i did the app to save the longitude and latitude of the devices to the Firebase, but i do not know how to retrieve the longitude and latitude from Firebase and display them as markers in the google map.
| 0debug
|
static void tcg_out_qemu_st_slow_path (TCGContext *s, TCGLabelQemuLdst *label)
{
int s_bits;
int ir;
int opc = label->opc;
int mem_index = label->mem_index;
int data_reg = label->datalo_reg;
int data_reg2 = label->datahi_reg;
int addr_reg = label->addrlo_reg;
uint8_t *raddr = label->raddr;
uint8_t **label_ptr = &label->label_ptr[0];
s_bits = opc & 3;
reloc_pc14 (label_ptr[0], (tcg_target_long) s->code_ptr);
ir = 3;
tcg_out_mov (s, TCG_TYPE_I32, ir++, TCG_AREG0);
#if TARGET_LONG_BITS == 32
tcg_out_mov (s, TCG_TYPE_I32, ir++, addr_reg);
#else
#ifdef TCG_TARGET_CALL_ALIGN_ARGS
ir |= 1;
#endif
tcg_out_mov (s, TCG_TYPE_I32, ir++, label->addrhi_reg);
tcg_out_mov (s, TCG_TYPE_I32, ir++, addr_reg);
#endif
switch (opc) {
case 0:
tcg_out32 (s, (RLWINM
| RA (ir)
| RS (data_reg)
| SH (0)
| MB (24)
| ME (31)));
break;
case 1:
tcg_out32 (s, (RLWINM
| RA (ir)
| RS (data_reg)
| SH (0)
| MB (16)
| ME (31)));
break;
case 2:
tcg_out_mov (s, TCG_TYPE_I32, ir, data_reg);
break;
case 3:
#ifdef TCG_TARGET_CALL_ALIGN_ARGS
ir |= 1;
#endif
tcg_out_mov (s, TCG_TYPE_I32, ir++, data_reg2);
tcg_out_mov (s, TCG_TYPE_I32, ir, data_reg);
break;
}
ir++;
tcg_out_movi (s, TCG_TYPE_I32, ir, mem_index);
tcg_out_call (s, (tcg_target_long) qemu_st_helpers[opc], 1);
tcg_out32 (s, B | 8);
tcg_out32 (s, (tcg_target_long) raddr);
tcg_out_b (s, 0, (tcg_target_long) raddr);
}
| 1threat
|
void breakpoint_handler(CPUX86State *env)
{
CPUBreakpoint *bp;
if (env->watchpoint_hit) {
if (env->watchpoint_hit->flags & BP_CPU) {
env->watchpoint_hit = NULL;
if (check_hw_breakpoints(env, 0))
raise_exception(env, EXCP01_DB);
else
cpu_resume_from_signal(env, NULL);
}
} else {
QTAILQ_FOREACH(bp, &env->breakpoints, entry)
if (bp->pc == env->eip) {
if (bp->flags & BP_CPU) {
check_hw_breakpoints(env, 1);
raise_exception(env, EXCP01_DB);
}
break;
}
}
}
| 1threat
|
python - invalid value encountered in log : <p>I have the following expression:
<code>log = np.sum(np.nan_to_num(-y*np.log(a+ 1e-7)-(1-y)*np.log(1-a+ 1e-7)))</code></p>
<p>it is giving me the following warning:</p>
<pre><code>RuntimeWarning: invalid value encountered in log
log = np.sum(np.nan_to_num(-y*np.log(a+ 1e-7)-(1-y)*np.log(1-a+ 1e-7)))
</code></pre>
<p>I don't understand what might be the invalid value or why am I getting it. Any and every help is appreciated.</p>
<p><strong>NOTE</strong>: This is a cross-entropy cost function where I added <code>1e-7</code> to avoid having zeros inside log. <code>y</code> & <code>a</code> are numpy arrays and <code>numpy</code> is imported as <code>np</code>.</p>
| 0debug
|
def check_triplet(A, n, sum, count):
if count == 3 and sum == 0:
return True
if count == 3 or n == 0 or sum < 0:
return False
return check_triplet(A, n - 1, sum - A[n - 1], count + 1) or\
check_triplet(A, n - 1, sum, count)
| 0debug
|
how to listen of angular template driven form changes : <p>in my form:</p>
<pre><code><form>
<label class="form-check-label">
<input [(ngModel)]="options.o1" name="o1"
type="checkbox" class="form-check-input" >
Option 1
</label>
<label class="form-check-label">
<input [(ngModel)]="options.o2" name="o2"
type="checkbox" class="form-check-input" >
Option 2
</label>
</form>
</code></pre>
<p>I want to be informed whenever one of the two checkboxes is changed, not by adding an event handler to each of the checkboxes but by adding an event handler to the form, in reality there are much more fields in the form.</p>
| 0debug
|
MySql Hospital Management Database system : <p>How to diffentiate multiple column with same name I.e. patient table full name and doctor table full name</p>
<p>How to know the doctor that is assign to each patient.</p>
<p>Thanks</p>
| 0debug
|
Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error : <p>After the latest update of PHP Intelephense that I get today, the intelephense keep showing an error for an undefined symbol for my route (and other class too), there is no error like this before and it's bothering me.</p>
<p>Here is the error screenshot :</p>
<p><a href="https://i.stack.imgur.com/DQ8AW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DQ8AW.png" alt="enter image description here"></a></p>
<p>And this is my code :</p>
<pre><code>Route::group(['prefix' => 'user', 'namespace' => 'Membership', 'name' => 'user.'], function () {
Route::get('profile', 'ProfileController@show')->name('profile.show');
Route::patch('profile', 'ProfileController@update')->name('profile.update');
Route::patch('change-password', 'ChangePasswordController@change')->name('change-password');
Route::get('role', 'ProfileController@getRole')->name('profile.role');
Route::get('summary', 'SummaryController@show')->name('summary');
Route::get('reserved', 'AuctionController@reservedAuction')->name('reserved');
});
</code></pre>
<p>Actually there's no error in this code but the intelephense keeps showing an error so is there a way to fix this?</p>
| 0debug
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.