problem
stringlengths
26
131k
labels
class label
2 classes
Which is better approach? : <p>I need to find subject, but it could be null. So have to do this without throwing exception. I have two approach and please suggest which is better?</p> <pre><code>public static String getSafeSubject(SNSEvent.SNSRecord record){ try{ return record.getSNS().getSubject(); }catch (Exception e){ return "Failed to retrieve subject"; } } </code></pre> <pre><code>public static String getSafeSubject(SNSEvent.SNSRecord record){ if(record == null || record.getSNS() == null || record.getSNS().getSubject() == null){ return "Failed to retrieve subject"; } return record.getSNS().getSubject(); } </code></pre>
0debug
Python appends only one value : <p>Here is my Python Code</p> <pre><code>pos = 0 for i in range(-10,10): x = 3*i + 1 dataX = [] #dataX.append(x) dataX.insert(pos,x) print("insert "+str(x)+" at "+ str(pos) + "|" + str(dataX)) pos += 1 print(dataX) </code></pre> <p>Simply append should work right? but it does not, but so is insert..</p> <p>Both returns same values as following..</p> <pre><code>insert 1.9 at 13|[1.9] </code></pre> <p>that is 13th iteration as shown, and yet it does not do either insert nor append which should have generated list of data</p> <p>I have no idea I've tried append as shown but results in [1.9] even with previous data.</p>
0debug
int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options, int flags, BlockDriver *drv, Error **errp) { int ret; char tmp_filename[PATH_MAX + 1]; BlockDriverState *file = NULL; QDict *file_options = NULL; const char *drvname; Error *local_err = NULL; if (options == NULL) { options = qdict_new(); } bs->options = options; options = qdict_clone_shallow(options); if (flags & BDRV_O_SNAPSHOT) { BlockDriverState *bs1; int64_t total_size; BlockDriver *bdrv_qcow2; QEMUOptionParameter *create_options; char backing_filename[PATH_MAX]; if (qdict_size(options) != 0) { error_setg(errp, "Can't use snapshot=on with driver-specific options"); ret = -EINVAL; goto fail; } assert(filename != NULL); bs1 = bdrv_new(""); ret = bdrv_open(bs1, filename, NULL, 0, drv, &local_err); if (ret < 0) { bdrv_unref(bs1); goto fail; } total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK; bdrv_unref(bs1); ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename)); if (ret < 0) { error_setg_errno(errp, -ret, "Could not get temporary filename"); goto fail; } if (path_has_protocol(filename)) { snprintf(backing_filename, sizeof(backing_filename), "%s", filename); } else if (!realpath(filename, backing_filename)) { ret = -errno; error_setg_errno(errp, errno, "Could not resolve path '%s'", filename); goto fail; } bdrv_qcow2 = bdrv_find_format("qcow2"); create_options = parse_option_parameters("", bdrv_qcow2->create_options, NULL); set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size); set_option_parameter(create_options, BLOCK_OPT_BACKING_FILE, backing_filename); if (drv) { set_option_parameter(create_options, BLOCK_OPT_BACKING_FMT, drv->format_name); } ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err); free_option_parameters(create_options); if (ret < 0) { error_setg_errno(errp, -ret, "Could not create temporary overlay " "'%s': %s", tmp_filename, error_get_pretty(local_err)); error_free(local_err); local_err = NULL; goto fail; } filename = tmp_filename; drv = bdrv_qcow2; bs->is_temporary = 1; } if (flags & BDRV_O_RDWR) { flags |= BDRV_O_ALLOW_RDWR; } qdict_extract_subqdict(options, &file_options, "file."); ret = bdrv_file_open(&file, filename, file_options, bdrv_open_flags(bs, flags | BDRV_O_UNMAP), &local_err); if (ret < 0) { goto fail; } drvname = qdict_get_try_str(options, "driver"); if (drvname) { drv = bdrv_find_format(drvname); qdict_del(options, "driver"); if (!drv) { error_setg(errp, "Invalid driver: '%s'", drvname); ret = -EINVAL; goto unlink_and_fail; } } if (!drv) { ret = find_image_format(file, filename, &drv, &local_err); } if (!drv) { goto unlink_and_fail; } ret = bdrv_open_common(bs, file, options, flags, drv, &local_err); if (ret < 0) { goto unlink_and_fail; } if (bs->file != file) { bdrv_unref(file); file = NULL; } if ((flags & BDRV_O_NO_BACKING) == 0) { QDict *backing_options; qdict_extract_subqdict(options, &backing_options, "backing."); ret = bdrv_open_backing_file(bs, backing_options, &local_err); if (ret < 0) { goto close_and_fail; } } if (qdict_size(options) != 0) { const QDictEntry *entry = qdict_first(options); error_setg(errp, "Block format '%s' used by device '%s' doesn't " "support the option '%s'", drv->format_name, bs->device_name, entry->key); ret = -EINVAL; goto close_and_fail; } QDECREF(options); if (!bdrv_key_required(bs)) { bdrv_dev_change_media_cb(bs, true); } return 0; unlink_and_fail: if (file != NULL) { bdrv_unref(file); } if (bs->is_temporary) { unlink(filename); } fail: QDECREF(bs->options); QDECREF(options); bs->options = NULL; if (error_is_set(&local_err)) { error_propagate(errp, local_err); } return ret; close_and_fail: bdrv_close(bs); QDECREF(options); if (error_is_set(&local_err)) { error_propagate(errp, local_err); } return ret; }
1threat
static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); int version = 0; uint32_t tag = track->tag; if (track->mode == MODE_MOV) { if (track->timescale > UINT16_MAX) { if (mov_get_lpcm_flags(track->enc->codec_id)) tag = AV_RL32("lpcm"); version = 2; } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) || track->enc->codec_id == AV_CODEC_ID_ADPCM_MS || track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || track->enc->codec_id == AV_CODEC_ID_QDM2) { version = 1; } } avio_wb32(pb, 0); avio_wl32(pb, tag); avio_wb32(pb, 0); avio_wb16(pb, 0); avio_wb16(pb, 1); avio_wb16(pb, version); avio_wb16(pb, 0); avio_wb32(pb, 0); if (version == 2) { avio_wb16(pb, 3); avio_wb16(pb, 16); avio_wb16(pb, 0xfffe); avio_wb16(pb, 0); avio_wb32(pb, 0x00010000); avio_wb32(pb, 72); avio_wb64(pb, av_double2int(track->enc->sample_rate)); avio_wb32(pb, track->enc->channels); avio_wb32(pb, 0x7F000000); avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id)); avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id)); avio_wb32(pb, track->sample_size); avio_wb32(pb, get_samples_per_packet(track)); } else { if (track->mode == MODE_MOV) { avio_wb16(pb, track->enc->channels); if (track->enc->codec_id == AV_CODEC_ID_PCM_U8 || track->enc->codec_id == AV_CODEC_ID_PCM_S8) avio_wb16(pb, 8); else avio_wb16(pb, 16); avio_wb16(pb, track->audio_vbr ? -2 : 0); } else { avio_wb16(pb, 2); avio_wb16(pb, 16); avio_wb16(pb, 0); } avio_wb16(pb, 0); avio_wb16(pb, track->enc->sample_rate <= UINT16_MAX ? track->enc->sample_rate : 0); avio_wb16(pb, 0); } if(version == 1) { avio_wb32(pb, track->enc->frame_size); avio_wb32(pb, track->sample_size / track->enc->channels); avio_wb32(pb, track->sample_size); avio_wb32(pb, 2); } if(track->mode == MODE_MOV && (track->enc->codec_id == AV_CODEC_ID_AAC || track->enc->codec_id == AV_CODEC_ID_AC3 || track->enc->codec_id == AV_CODEC_ID_AMR_NB || track->enc->codec_id == AV_CODEC_ID_ALAC || track->enc->codec_id == AV_CODEC_ID_ADPCM_MS || track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || track->enc->codec_id == AV_CODEC_ID_QDM2 || (mov_pcm_le_gt16(track->enc->codec_id) && version==1))) mov_write_wave_tag(pb, track); else if(track->tag == MKTAG('m','p','4','a')) mov_write_esds_tag(pb, track); else if(track->enc->codec_id == AV_CODEC_ID_AMR_NB) mov_write_amr_tag(pb, track); else if(track->enc->codec_id == AV_CODEC_ID_AC3) mov_write_ac3_tag(pb, track); else if(track->enc->codec_id == AV_CODEC_ID_ALAC) mov_write_extradata_tag(pb, track); else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) mov_write_wfex_tag(pb, track); else if (track->vos_len > 0) mov_write_glbl_tag(pb, track); if (track->mode == MODE_MOV && track->enc->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_chan_tag(pb, track); return update_size(pb, pos); }
1threat
android app on kitkat works on lollipop don't : i'm asking to you some help beacause i can't find the solution. i'm doing an android app and i have decided to add in my app the contact list. i have take this from google android developpers http://developer.android.com/training/contacts-provider/retrieve-names.html and i have take the code and add all the features to my app(xml/layout/images/javacode etc) and in my main activity i call the contactlist activity. if i attack my cellular phone with kitkat 4.4.2 via debug on android studio my app comes and in mymain activity when i call the contacts activity it does so well... but if i attack my cellular phone with lollipop 5.1.1 when i call the contacts activity it does so well the titlebar is hide and then when i click one contact the app crashes... it crashes at this instruction if (Utils.hasHoneycomb()) { // Enables action bar "up" navigation getActionBar().setDisplayHomeAsUpEnabled(true); } and it give to me 02-18 13:41:15.304 31435-31435/todonotes.com.todonotes_buildfinale E/AndroidRuntime: FATAL EXCEPTION: main Process: todonotes.com.todonotes_buildfinale, PID: 31435 java.lang.RuntimeException: Unable to start activity ComponentInfo{todonotes.com.todonotes_buildfinale/todonotes.com.todonotes_buildfinale.ContactDetailActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2378) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2440) at android.app.ActivityThread.access$800(ActivityThread.java:162) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1348) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5422) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference at todonotes.com.todonotes_buildfinale.ContactDetailActivity.onCreate(ContactDetailActivity.java:59) at android.app.Activity.performCreate(Activity.java:6057) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2440) at android.app.ActivityThread.access$800(ActivityThread.java:162) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1348) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5422) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707) my manifest is: <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="todonotes.com.todonotes_buildfinale"> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_CONTACTS"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.NoActionBar"> <activity android:name="todonotes.com.todonotes_buildfinale.SplashScreen" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="todonotes.com.todonotes_buildfinale.LoginActivity" android:theme="@style/AppTheme.Dark" android:label="@string/app_name"> <intent-filter> <action android:name="todonotes.com.todonotes_buildfinale.SIGNUPACTIVITY"/> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="todonotes.com.todonotes_buildfinale.ContactsListActivity" android:theme="@style/AppTheme" android:label="@string/activity_contacts_list" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <!-- Add intent-filter for search intent action and specify searchable configuration via meta-data tag. This allows this activity to receive search intents via the system hooks. In this sample this is only used on older OS versions (pre-Honeycomb) via the activity search dialog. See the Search API guide for more information: http://developer.android.com/guide/topics/search/search-dialog.html --> <intent-filter> <action android:name="android.intent.action.SEARCH" /> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable_contacts" /> </activity> <activity android:name="todonotes.com.todonotes_buildfinale.ContactDetailActivity" android:theme="@style/AppTheme" android:label="@string/activity_contact_detail" android:parentActivityName="todonotes.com.todonotes_buildfinale.ContactDetailActivity"> <!-- Define hierarchical parent of this activity, both via the system parentActivityName attribute (added in API Level 16) and via meta-data annotation. This allows use of the support library NavUtils class in a way that works over all Android versions. See the "Tasks and Back Stack" guide for more information: http://developer.android.com/guide/components/tasks-and-back-stack.html --> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="todonotes.com.todonotes_buildfinale.ContactDetailActivity" /> </activity> <activity android:name="todonotes.com.todonotes_buildfinale.SignupActivity" android:theme="@style/AppTheme.Dark"></activity> <activity android:name="todonotes.com.todonotes_buildfinale.ConfirmActivity" android:theme="@style/AppTheme.Dark"></activity> <activity android:name="todonotes.com.todonotes_buildfinale.ListNoteActivity" android:theme="@style/AppTheme.Dark"></activity> </application> </manifest> how can i resolve this?? is urgent
0debug
System.setProperty() in selenium : //In selenium, why do we add System.setProperty("webdriver.chrome.driver", "E://chromedriver.exe"); within static{} ? public class Demo{ static{ System.setProperty("webdriver.chrome.driver", "E://chromedriver.exe"); } public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("http://www.google.com"); } }
0debug
How to write output compiler in java? : <p>Is there a way to make a quine in java, then have some sort of program recognize the output as a program, then run that and give an output, and keep on doing so infinitely? I'm trying to write a self-replicating code and get it to infinitely reproduce itself, thereby technically creating life. I have a superiority complex, I suppose</p>
0debug
Pointer equal in C : I know normally, * and & signs. But our teacher gives us an example and she said "Problem occurs here" int *a1; int *a2 = new int[100]; a1=a2 //What does this line mean??? delete []a2; k=a1[0]//she said error occurs here. I couldn't understand what is a1 = a2 ? and why does error occur?
0debug
Piping a file into docker run : <p>I need to pipe (inject) a file or some data into docker as part of the run command and have it written to a file within the container as part of the startup. Is there best practise way to do this ? </p> <p>I've tried this.</p> <pre><code>cat data.txt | docker run -a stdin -a stdout -i -t ubuntu /bin/bash -c 'cat &gt;/data.txt' </code></pre> <p>But can't seem to get it to work. </p>
0debug
JSON.parse - Unexpected token ', n : <p>When I tried to send to my express server JSON like this one:</p> <pre><code>"{ name: '...', description: '...' }" </code></pre> <p>This error had been throwed: </p> <pre><code>SyntaxError: Unexpected token n ... </code></pre> <p>Trying to parse JSON like this in Chrome:</p> <pre><code>"{ 'name': '...', 'description': '...' }" </code></pre> <p>Leads to this error:</p> <pre><code>SyntaxError: Unexpected token ' ... </code></pre> <p>Why parsing those JSONs leads to an error? Especially the second JSON looks valid (using <code>'</code> instead of <code>"</code>).</p>
0debug
how to compare dictionary values in python : Can someone tell me how can i compare all values to each other on the same dictionary please? Ex: dictionary whitch contains lot of sequences (sequence=key) whitch correspond to a lot of amino acide seuquences (dna translation, trans = value) dic_trans[sequence]=trans Thanks
0debug
Convert TEXT files to TRECTEXT format : <p>I want to convert my input text file which have this structure :</p> <pre><code>600 NJoussot 38 fr Twitter hn 2015 Taubira huée au festival de Cannes ... </code></pre> <p>to obtain TRECTEXT format which is like this :</p> <pre><code>&lt;DOC&gt; &lt;DOCNO&gt; 600 &lt;/DOCNO&gt; &lt;TEXT&gt; Taubira huée au festival de Cannes. &lt;/TEXT&gt; &lt;/DOC&gt; </code></pre> <p>Thanks for help :)</p>
0debug
log a message in my terminal server (localhost:8000) : def clean_expired_requests(): now = datetime.datetime.now() qs = Request.objects.filter( expires_at__date=now, state__in=[ 'documents', 'validation', 'evaluation', 'signature']) for req in qs: log.debug('Request %s expired' % req) req.expired_at_state = req.state.name req.save() req.expire() EmailFromTemplate('expired-request').send_to(req.customer.user) I am working on a Django project with this method. I would like to insert something which will advise me that has been called. I thought it could write me a message in my terminal server 'clean_expired_request has been called!'. How could I do such thing?
0debug
static int get_coc(J2kDecoderContext *s, J2kCodingStyle *c, uint8_t *properties) { int compno; if (s->buf_end - s->buf < 2) return AVERROR(EINVAL); compno = bytestream_get_byte(&s->buf); c += compno; c->csty = bytestream_get_byte(&s->buf); get_cox(s, c); properties[compno] |= HAD_COC; return 0; }
1threat
Why does C++ allow nested namespace with same name? : <p>Codes bellowing compiles:</p> <pre><code>namespace x { namespace y { namespace x { struct C { C () { std::cout &lt;&lt; "x::y::z::C" &lt;&lt; std::endl; } }; } } struct C { C () { std::cout &lt;&lt; "x::C" &lt;&lt; std::endl; } }; } </code></pre> <p><code>x::C</code> and <code>x::y::x::C</code> are not same, but it's sometimes confusing.</p> <p>Why is <code>x::y::x</code> allowed in C++? Isn't it more clear to forbid this?</p>
0debug
static int mpc7_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t * buf, int buf_size) { MPCContext *c = avctx->priv_data; GetBitContext gb; uint8_t *bits; int i, j, ch, t; int mb = -1; Band bands[BANDS]; int Q[2][MPC_FRAME_SIZE]; int off; float mul; int bits_used, bits_avail; memset(bands, 0, sizeof(bands)); if(buf_size <= 4){ av_log(avctx, AV_LOG_ERROR, "Too small buffer passed (%i bytes)\n", buf_size); } bits = av_malloc((buf_size - 1) & ~3); c->dsp.bswap_buf(bits, buf + 4, (buf_size - 4) >> 2); init_get_bits(&gb, bits, (buf_size - 4)* 8); skip_bits(&gb, buf[0]); for(i = 0; i <= c->bands; i++){ for(ch = 0; ch < 2; ch++){ if(i) t = get_vlc2(&gb, hdr_vlc.table, MPC7_HDR_BITS, 1) - 5; if(!i || (t == 4)) bands[i].res[ch] = get_bits(&gb, 4); else bands[i].res[ch] = bands[i-1].res[ch] + t; } if(bands[i].res[0] || bands[i].res[1]){ mb = i; if(c->MSS) bands[i].msf = get_bits1(&gb); } } for(i = 0; i <= mb; i++) for(ch = 0; ch < 2; ch++) if(bands[i].res[ch]) bands[i].scfi[ch] = get_vlc2(&gb, scfi_vlc.table, MPC7_SCFI_BITS, 1); for(i = 0; i <= mb; i++){ for(ch = 0; ch < 2; ch++){ if(bands[i].res[ch]){ bands[i].scf_idx[ch][2] = c->oldDSCF[ch][i]; t = get_vlc2(&gb, dscf_vlc.table, MPC7_DSCF_BITS, 1) - 7; bands[i].scf_idx[ch][0] = (t == 8) ? get_bits(&gb, 6) : (bands[i].scf_idx[ch][2] + t); switch(bands[i].scfi[ch]){ case 0: t = get_vlc2(&gb, dscf_vlc.table, MPC7_DSCF_BITS, 1) - 7; bands[i].scf_idx[ch][1] = (t == 8) ? get_bits(&gb, 6) : (bands[i].scf_idx[ch][0] + t); t = get_vlc2(&gb, dscf_vlc.table, MPC7_DSCF_BITS, 1) - 7; bands[i].scf_idx[ch][2] = (t == 8) ? get_bits(&gb, 6) : (bands[i].scf_idx[ch][1] + t); break; case 1: t = get_vlc2(&gb, dscf_vlc.table, MPC7_DSCF_BITS, 1) - 7; bands[i].scf_idx[ch][1] = (t == 8) ? get_bits(&gb, 6) : (bands[i].scf_idx[ch][0] + t); bands[i].scf_idx[ch][2] = bands[i].scf_idx[ch][1]; break; case 2: bands[i].scf_idx[ch][1] = bands[i].scf_idx[ch][0]; t = get_vlc2(&gb, dscf_vlc.table, MPC7_DSCF_BITS, 1) - 7; bands[i].scf_idx[ch][2] = (t == 8) ? get_bits(&gb, 6) : (bands[i].scf_idx[ch][1] + t); break; case 3: bands[i].scf_idx[ch][2] = bands[i].scf_idx[ch][1] = bands[i].scf_idx[ch][0]; break; } c->oldDSCF[ch][i] = bands[i].scf_idx[ch][2]; } } } memset(Q, 0, sizeof(Q)); off = 0; for(i = 0; i < BANDS; i++, off += SAMPLES_PER_BAND) for(ch = 0; ch < 2; ch++) idx_to_quant(c, &gb, bands[i].res[ch], Q[ch] + off); memset(c->sb_samples, 0, sizeof(c->sb_samples)); off = 0; for(i = 0; i <= mb; i++, off += SAMPLES_PER_BAND){ for(ch = 0; ch < 2; ch++){ if(bands[i].res[ch]){ j = 0; mul = mpc_CC[bands[i].res[ch]] * mpc7_SCF[bands[i].scf_idx[ch][0]]; for(; j < 12; j++) c->sb_samples[ch][j][i] = mul * Q[ch][j + off]; mul = mpc_CC[bands[i].res[ch]] * mpc7_SCF[bands[i].scf_idx[ch][1]]; for(; j < 24; j++) c->sb_samples[ch][j][i] = mul * Q[ch][j + off]; mul = mpc_CC[bands[i].res[ch]] * mpc7_SCF[bands[i].scf_idx[ch][2]]; for(; j < 36; j++) c->sb_samples[ch][j][i] = mul * Q[ch][j + off]; } } if(bands[i].msf){ int t1, t2; for(j = 0; j < SAMPLES_PER_BAND; j++){ t1 = c->sb_samples[0][j][i]; t2 = c->sb_samples[1][j][i]; c->sb_samples[0][j][i] = t1 + t2; c->sb_samples[1][j][i] = t1 - t2; } } } mpc_synth(c, data); av_free(bits); bits_used = get_bits_count(&gb); bits_avail = (buf_size - 4) * 8; if(!buf[1] && ((bits_avail < bits_used) || (bits_used + 32 <= bits_avail))){ av_log(NULL,0, "Error decoding frame: used %i of %i bits\n", bits_used, bits_avail); return -1; } if(c->frames_to_skip){ c->frames_to_skip--; *data_size = 0; return buf_size; } *data_size = (buf[1] ? c->lastframelen : MPC_FRAME_SIZE) * 4; return buf_size; }
1threat
How to create a map with zipcode dataset? ( US Zipcode ) : <blockquote> <p>How to create a map in R with zipcode dataset?</p> </blockquote> <p><code>data &lt;- c("22313","10100","25001")</code> [example zipcode]</p> <p><strong><em>In this moment, I have a dataset full of zipcode and I would like to print in a map and save it in pdf.</em></strong></p> <p><strong><em>Best regards,</em></strong></p> <p><strong><em>E.P.</em></strong></p>
0debug
How can i use fragment back button to go one step behind? : I am beginner in android.I am working on a small project.There is multiple fragment in that.I'd like to add a back button in fragment to go back.How can i do that? Thanks.
0debug
How to get the names of songs in a directory using Javascript : <p>There is a directory in my server where there are lots of mp3 and ogg files. And there is a player in my site that gets an array of those songs in that directory and play them. The array should be defined like this:</p> <pre><code>[ 'song1', 'song2', 'song3', 'songx' ] </code></pre> <p>How can I get the name of those songs like this array using javascript in my template?</p> <p>Thanks in advance</p>
0debug
static void decode_gain_info(GetBitContext *gb, int *gaininfo) { int i, n; while (get_bits1(gb)) { } n = get_bits_count(gb) - 1; i = 0; while (n--) { int index = get_bits(gb, 3); int gain = get_bits1(gb) ? get_bits(gb, 4) - 7 : -1; while (i <= index) gaininfo[i++] = gain; } while (i <= 8) gaininfo[i++] = 0; }
1threat
Error when launching my Android app : I made a custom adapter for my listView following this tutorial (https://droidhat.com/android-listview-using-custom-cursoradapter-sqlite-database). But when I run my app on my Android device, it gives an error when it's launching. The error appears when the onCreate method from MainActivity tries to call the getData method from the NotesDbHelper class. Can you help me? **MainActivity.java** public class MainActivity extends Activity { private EditText mEditText; private Button mButton; NotesCustomAdapter notesCustomAdapter = null; ListView listView = null; NotesDbHelper database = null; ArrayList<Notes> notes = null; /** Called when the activity is first created. * @param savedInstanceState */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = (Button) findViewById(R.id.button); mEditText = (EditText) findViewById(R.id.editText); database = new NotesDbHelper(this); notes = database.getData(); notesCustomAdapter= new NotesCustomAdapter(this,R.layout.notes_details,notes); listView = (ListView) findViewById(R.id.simpleListView); listView.setAdapter(notesCustomAdapter); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String input = mEditText.getText().toString(); if (input.length() > 0) { database.insertNote(input); } } }); listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> a, View v, final int position, long id) { AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this); adb.setTitle("Delete?"); adb.setMessage("Are you sure you want to delete this note?"); final int positionToRemove = position; adb.setNegativeButton("Cancel", null); adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { database.deleteNote(which); notes.remove(positionToRemove); notesCustomAdapter.remove(String.valueOf(positionToRemove)); notesCustomAdapter.notifyDataSetChanged(); }}); adb.show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } **NotesDbHelper.java** public class NotesDbHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "Notes.db"; public static final String NOTES_TABLE_NAME = "Notes.user"; public static final String NOTES_COLUMN_ID = "id"; public static final String NOTES_COLUMN_NAME = "n_text"; public NotesDbHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + NOTES_TABLE_NAME + "(_id integer primary key AUTOINCREMENT NOT NULL," + NOTES_COLUMN_NAME + ")" ); } @Override public void onUpgrade(SQLiteDatabase db, int i, int i1) { db.execSQL("DROP TABLE IF EXISTS "+ DATABASE_NAME); onCreate(db); } public boolean insertNote(String text) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("n_text", text); db.insert(NOTES_TABLE_NAME, null, contentValues); return true; } public ArrayList<Notes> getData() { SQLiteDatabase db = this.getReadableDatabase(); ArrayList<Notes> notes = new ArrayList<Notes>(); Cursor result = db.rawQuery("select * from "+ NOTES_TABLE_NAME , null); while(result.moveToNext()){ notes.add( new Notes(result.getString(result.getColumnIndex(NOTES_COLUMN_NAME)))); } return notes; } public boolean updateNotes(int id, int text) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("n_text", text); db.update(NOTES_TABLE_NAME, contentValues, "id = ? ", new String[]{Integer.toString(id)}); return true; } public Integer deleteNote(Integer id) { SQLiteDatabase db = this.getWritableDatabase(); return db.delete(NOTES_TABLE_NAME, "id = ? ", new String[]{Integer.toString(id)}); } } **Notes.java** public class Notes { String text; public Notes(String text) { this.text = text; } public String getText() { return text; } public void setText(String text) { this.text = text; } } **NotesCustomAdapter.java** public class NotesCustomAdapter extends ArrayAdapter{ private Context context; private ArrayList<Notes> notes; public NotesCustomAdapter(Context context, int textViewResourceId, ArrayList objects) { super(context,textViewResourceId, objects); this.context= context; notes=objects; } private class ViewHolder { TextView text; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder=null; if (convertView == null) { LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = vi.inflate(R.layout.notes_details, null); holder = new ViewHolder(); holder.text = (TextView) convertView.findViewById(R.id.text); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } Notes textNotes = notes.get(position); holder.text.setText(textNotes.getText()); return convertView; } } **LogCat** the first line says: java.lang.RuntimeException: Unable to start activity ComponentInfo{agenda.com/agenda.com.MainActivity}: android.database.sqlite.SQLiteException: unknown database Notes (code 1): , while compiling: create table Notes.user(_id integer primary key AUTOINCREMENT NOT NULL,n_text) [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/oEuu7.png
0debug
static void uc32_cpu_realizefn(DeviceState *dev, Error **errp) { UniCore32CPUClass *ucc = UNICORE32_CPU_GET_CLASS(dev); ucc->parent_realize(dev, errp); }
1threat
static void usbredir_handle_interrupt_out_data(USBRedirDevice *dev, USBPacket *p, uint8_t ep) { struct usb_redir_interrupt_packet_header interrupt_packet; uint8_t buf[p->iov.size]; DPRINTF("interrupt-out ep %02X len %zd id %"PRIu64"\n", ep, p->iov.size, p->id); if (usbredir_already_in_flight(dev, p->id)) { p->status = USB_RET_ASYNC; return; } interrupt_packet.endpoint = ep; interrupt_packet.length = p->iov.size; usb_packet_copy(p, buf, p->iov.size); usbredir_log_data(dev, "interrupt data out:", buf, p->iov.size); usbredirparser_send_interrupt_packet(dev->parser, p->id, &interrupt_packet, buf, p->iov.size); usbredirparser_do_write(dev->parser); p->status = USB_RET_ASYNC; }
1threat
Access $scope angular variable to HTMl JS Code : I have angular code in my controller is <div ng-controller = "myCtrl"> $scope.name = "Hello"; </div> In My HTML file, I have javascript code where I want this $scope.name value : <html> <script> // But this seems not possible with {{ name}} </script> </html> Is there any possibilities to access this $scope variable in JS code ?
0debug
PHP Symfony redirection : <p>I have taken a new job and the codes are a little complex. I'm looking for a page to edit. The older programmer used PHP Symfony framework with no comment tags.</p> <p>My question is:</p> <p>Pages are loaded by GET request like that: www.asd.com/asd.php/manage</p> <p>I just can't find where is file and where 'manage' loads from.</p> <p>Thank you.</p>
0debug
How to transform Future<List<Map> to List<Map> in Dart language? : <p>I have a question in coding with dart language. How to transform a Future to the normal List? In my program, I need the result from web to continue next step and I don't know how to do it. In my case, I need to return the value of variable "data" as a List.</p> <pre><code>class _MyAppState extends State&lt;MyApp&gt; { static List getList() { var url = "http://watcherman.cn/web/json.php"; var data; HttpClient client = new HttpClient(); client.getUrl(Uri.parse(url)) .then((HttpClientRequest request) =&gt; request.close()) .then((HttpClientResponse response) { response.transform(UTF8.decoder).listen((contents) { String jsonContent = contents.toString(); data = JSON.decode(jsonContent); }); }); return data; } } </code></pre> <p>But it seems like not execute the network part. The flutter code part seems can't accept a Future.</p> <pre><code>class _MyAppState extends State&lt;MyApp&gt; { static List content = getList(); @override Widget build(BuildContext context) { return new Container( child: new ListView.builder( scrollDirection: Axis.vertical, padding: new EdgeInsets.all(6.0), itemCount: content.length, itemBuilder: (BuildContext context, int index) { return new Container( alignment: FractionalOffset.center, margin: new EdgeInsets.only(bottom: 6.0), padding: new EdgeInsets.all(6.0), color: Colors.blueGrey, child: new Text(content[index]["title"]) ); } ) ); } } </code></pre>
0debug
static int proxy_parse_opts(QemuOpts *opts, struct FsDriverEntry *fs) { const char *socket = qemu_opt_get(opts, "socket"); const char *sock_fd = qemu_opt_get(opts, "sock_fd"); if (!socket && !sock_fd) { fprintf(stderr, "socket and sock_fd none of the option specified\n"); return -1; } if (socket && sock_fd) { fprintf(stderr, "Both socket and sock_fd options specified\n"); return -1; } if (socket) { fs->path = g_strdup(socket); fs->export_flags = V9FS_PROXY_SOCK_NAME; } else { fs->path = g_strdup(sock_fd); fs->export_flags = V9FS_PROXY_SOCK_FD; } return 0; }
1threat
sqlalchemy classical mapping relationship issue : <p>I am on a mission to finally learn sqlAlchemy so that I can reap the benefits in the years to come. </p> <p>I am neck deep in the sqlalchemy documents and have been for the past two days. I am hell bent on learning the classical mapping way, instead of the declarative, bc the db I want to hook up to exists, and does not have a unique id column in all of it's tables. <a href="http://www.blog.pythonlibrary.org/2010/09/10/sqlalchemy-connecting-to-pre-existing-databases/">According to this article classical mapping is the way to go under such circumstances</a></p> <p>I have been following the classical examples from the sqlalchemy site, but I just cannot seem to find the correct relationship configuration to get this to work. </p> <p>Here is all my code: </p> <pre><code>engine = create_engine( "mssql+pyodbc://someaddress/test?driver=FreeTDS?TDS_version=8.0", echo=True) metadata = MetaData(engine) class User(object): def __repr__(self): return "&lt;User(User_id='%s', name='%s', age='%s')&gt;" % ( self.user_id, self.name, self.age) class Email(object): def __repr__(self): return "&lt;User(email_id='%s', address='%s', user_id='%s')&gt;" % ( self.email_id, self.address, self.user_id) users = Table('users', metadata, Column('user_id', Integer, primary_key=True), Column('name', String(40)), Column('age', Integer), schema='test.dbo.users') mapper(User, users, properties={'Email': relationship(Email, primaryjoin=users.c.user_id==emails.c.user_id)}) emails = Table('emails', metadata, Column('email_id', Integer, primary_key=True), Column('address', String), Column('user_id', Integer, ForeignKey('test.dbo.users.user_id')), schema='test.dbo.emails') mapper(Email, emails) Session = sessionmaker(bind=engine) session = Session() mary = session.query(User, Email).filter(User.user_id == Email.user_id) </code></pre> <p>The pursuing error message makes it clear that it is the mapper / relationship that is the problem.</p> <pre><code>InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Original exception was: Could not determine join condition between parent/child tables on relationship User.Email - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression. </code></pre> <p>I have tried a long list of different things to try to remedy, but I just cannot get to the bottom of it. </p> <p>Any pointers in the right direction would be much appreciated!</p> <p>The sqlalchemy version I am on is; </p> <pre><code>'1.0.12' </code></pre>
0debug
Google map in Flutter not responding to touch events : <p>I got two different screens inside Flutter app that use Google Map (provided by this <a href="https://pub.dartlang.org/packages/google_maps_flutter" rel="noreferrer">library</a>).</p> <p>Widget structure for first one is </p> <blockquote> <p>Scaffold -> ListView -> Visibility -> Center -> SizedBox -> GoogleMap</p> </blockquote> <p>and for second screen it is </p> <blockquote> <p>Scaffold -> Container -> Column -> SizedBox -> GoogleMap</p> </blockquote> <p>On both screens I got same map settings but for some reason on the first screen map is not responding to any touch events.</p>
0debug
HTML button don't submit : <p>I have this HTML code in a JSP page, but when I click it does not do anything</p> <pre><code>&lt;button class="btn btn-grey" type="submit"&gt;Save device&lt;/button&gt; </code></pre>
0debug
Show strings seperated by commas : I am trying to show contact numbers separated by commas But i am not able to do it. Right now I am ble to show them line by line.How to show them like 9999999999,8888888888....etc Below is my code snippet String displayName = contact.getPhone(0); result.append(displayName + "\n");
0debug
x11grab_read_header(AVFormatContext *s1) { struct x11_grab *x11grab = s1->priv_data; Display *dpy; AVStream *st = NULL; enum PixelFormat input_pixfmt; XImage *image; int x_off = 0; int y_off = 0; int screen; int use_shm; char *param, *offset; int ret = 0; AVRational framerate; param = av_strdup(s1->filename); if (!param) goto out; offset = strchr(param, '+'); if (offset) { sscanf(offset, "%d,%d", &x_off, &y_off); x11grab->draw_mouse = !strstr(offset, "nomouse"); *offset= 0; } if ((ret = av_parse_video_size(&x11grab->width, &x11grab->height, x11grab->video_size)) < 0) { av_log(s1, AV_LOG_ERROR, "Couldn't parse video size.\n"); goto out; } if ((ret = av_parse_video_rate(&framerate, x11grab->framerate)) < 0) { av_log(s1, AV_LOG_ERROR, "Could not parse framerate: %s.\n", x11grab->framerate); goto out; } av_log(s1, AV_LOG_INFO, "device: %s -> display: %s x: %d y: %d width: %d height: %d\n", s1->filename, param, x_off, y_off, x11grab->width, x11grab->height); dpy = XOpenDisplay(param); if(!dpy) { av_log(s1, AV_LOG_ERROR, "Could not open X display.\n"); ret = AVERROR(EIO); goto out; } st = avformat_new_stream(s1, NULL); if (!st) { ret = AVERROR(ENOMEM); goto out; } avpriv_set_pts_info(st, 64, 1, 1000000); screen = DefaultScreen(dpy); if (x11grab->follow_mouse) { int screen_w, screen_h; Window w; screen_w = DisplayWidth(dpy, screen); screen_h = DisplayHeight(dpy, screen); XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, &x_off, &y_off, &ret, &ret, &ret); x_off -= x11grab->width / 2; y_off -= x11grab->height / 2; x_off = FFMIN(FFMAX(x_off, 0), screen_w - x11grab->width); y_off = FFMIN(FFMAX(y_off, 0), screen_h - x11grab->height); av_log(s1, AV_LOG_INFO, "followmouse is enabled, resetting grabbing region to x: %d y: %d\n", x_off, y_off); } use_shm = XShmQueryExtension(dpy); av_log(s1, AV_LOG_INFO, "shared memory extension %s found\n", use_shm ? "" : "not"); if(use_shm) { int scr = XDefaultScreen(dpy); image = XShmCreateImage(dpy, DefaultVisual(dpy, scr), DefaultDepth(dpy, scr), ZPixmap, NULL, &x11grab->shminfo, x11grab->width, x11grab->height); x11grab->shminfo.shmid = shmget(IPC_PRIVATE, image->bytes_per_line * image->height, IPC_CREAT|0777); if (x11grab->shminfo.shmid == -1) { av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n"); ret = AVERROR(ENOMEM); goto out; } x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0); x11grab->shminfo.readOnly = False; if (!XShmAttach(dpy, &x11grab->shminfo)) { av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n"); ret = AVERROR(EIO); goto out; } } else { image = XGetImage(dpy, RootWindow(dpy, screen), x_off,y_off, x11grab->width, x11grab->height, AllPlanes, ZPixmap); } switch (image->bits_per_pixel) { case 8: av_log (s1, AV_LOG_DEBUG, "8 bit palette\n"); input_pixfmt = PIX_FMT_PAL8; break; case 16: if ( image->red_mask == 0xf800 && image->green_mask == 0x07e0 && image->blue_mask == 0x001f ) { av_log (s1, AV_LOG_DEBUG, "16 bit RGB565\n"); input_pixfmt = PIX_FMT_RGB565; } else if (image->red_mask == 0x7c00 && image->green_mask == 0x03e0 && image->blue_mask == 0x001f ) { av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n"); input_pixfmt = PIX_FMT_RGB555; } else { av_log(s1, AV_LOG_ERROR, "RGB ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel); av_log(s1, AV_LOG_ERROR, "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n", image->red_mask, image->green_mask, image->blue_mask); ret = AVERROR(EIO); goto out; } break; case 24: if ( image->red_mask == 0xff0000 && image->green_mask == 0x00ff00 && image->blue_mask == 0x0000ff ) { input_pixfmt = PIX_FMT_BGR24; } else if ( image->red_mask == 0x0000ff && image->green_mask == 0x00ff00 && image->blue_mask == 0xff0000 ) { input_pixfmt = PIX_FMT_RGB24; } else { av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel); av_log(s1, AV_LOG_ERROR, "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n", image->red_mask, image->green_mask, image->blue_mask); ret = AVERROR(EIO); goto out; } break; case 32: input_pixfmt = PIX_FMT_RGB32; break; default: av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel); ret = AVERROR(EINVAL); goto out; } x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel/8; x11grab->dpy = dpy; x11grab->time_base = (AVRational){framerate.den, framerate.num}; x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base); x11grab->x_off = x_off; x11grab->y_off = y_off; x11grab->image = image; x11grab->use_shm = use_shm; st->codec->codec_type = AVMEDIA_TYPE_VIDEO; st->codec->codec_id = CODEC_ID_RAWVIDEO; st->codec->width = x11grab->width; st->codec->height = x11grab->height; st->codec->pix_fmt = input_pixfmt; st->codec->time_base = x11grab->time_base; st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(x11grab->time_base) * 8; out: return ret; }
1threat
How to show products in Volusion when insert it by Volusion API : I am importing the products through the Volusion API, the product is insert but not show in the front end of my store. Anyone who know that how to show the products in front end.
0debug
static void do_mchk_interrupt(CPUS390XState *env) { S390CPU *cpu = s390_env_get_cpu(env); uint64_t mask, addr; LowCore *lowcore; MchkQueue *q; int i; if (!(env->psw.mask & PSW_MASK_MCHECK)) { cpu_abort(CPU(cpu), "Machine check w/o mchk mask\n"); } if (env->mchk_index < 0 || env->mchk_index > MAX_MCHK_QUEUE) { cpu_abort(CPU(cpu), "Mchk queue overrun: %d\n", env->mchk_index); } q = &env->mchk_queue[env->mchk_index]; if (q->type != 1) { cpu_abort(CPU(cpu), "Unknown machine check type %d\n", q->type); } if (!(env->cregs[14] & (1 << 28))) { return; } lowcore = cpu_map_lowcore(env); for (i = 0; i < 16; i++) { lowcore->floating_pt_save_area[i] = cpu_to_be64(env->fregs[i].ll); lowcore->gpregs_save_area[i] = cpu_to_be64(env->regs[i]); lowcore->access_regs_save_area[i] = cpu_to_be32(env->aregs[i]); lowcore->cregs_save_area[i] = cpu_to_be64(env->cregs[i]); } lowcore->prefixreg_save_area = cpu_to_be32(env->psa); lowcore->fpt_creg_save_area = cpu_to_be32(env->fpc); lowcore->tod_progreg_save_area = cpu_to_be32(env->todpr); lowcore->cpu_timer_save_area[0] = cpu_to_be32(env->cputm >> 32); lowcore->cpu_timer_save_area[1] = cpu_to_be32((uint32_t)env->cputm); lowcore->clock_comp_save_area[0] = cpu_to_be32(env->ckc >> 32); lowcore->clock_comp_save_area[1] = cpu_to_be32((uint32_t)env->ckc); lowcore->mcck_interruption_code[0] = cpu_to_be32(0x00400f1d); lowcore->mcck_interruption_code[1] = cpu_to_be32(0x40330000); lowcore->mcck_old_psw.mask = cpu_to_be64(get_psw_mask(env)); lowcore->mcck_old_psw.addr = cpu_to_be64(env->psw.addr); mask = be64_to_cpu(lowcore->mcck_new_psw.mask); addr = be64_to_cpu(lowcore->mcck_new_psw.addr); cpu_unmap_lowcore(lowcore); env->mchk_index--; if (env->mchk_index == -1) { env->pending_int &= ~INTERRUPT_MCHK; } DPRINTF("%s: %" PRIx64 " %" PRIx64 "\n", __func__, env->psw.mask, env->psw.addr); load_psw(env, mask, addr); }
1threat
Access object from object within the object : <p>I try to program a small feed-forward neural network in oop java. I have three different classes called layer, synapse and neuron. One layer consists of a variable amount of nodes. Each Synapse has a start and end-neuron and also a weight. Now I want to access each weight attribute of the ingoing synapses from within the neurons. Somehow I can't wrap my mind around this. Am I missing something? I also tried working with a weighted graph, but I don't exactly know how to do it.</p> <p>Thank you for helping!</p>
0debug
pvscsi_dbg_dump_tx_rings_config(PVSCSICmdDescSetupRings *rc) { int i; trace_pvscsi_tx_rings_ppn("Rings State", rc->ringsStatePPN); trace_pvscsi_tx_rings_num_pages("Request Ring", rc->reqRingNumPages); for (i = 0; i < rc->reqRingNumPages; i++) { trace_pvscsi_tx_rings_ppn("Request Ring", rc->reqRingPPNs[i]); } trace_pvscsi_tx_rings_num_pages("Confirm Ring", rc->cmpRingNumPages); for (i = 0; i < rc->cmpRingNumPages; i++) { trace_pvscsi_tx_rings_ppn("Confirm Ring", rc->reqRingPPNs[i]); } }
1threat
static int dpx_probe(AVProbeData *p) { const uint8_t *b = p->buf; if (AV_RN32(b) == AV_RN32("SDPX") || AV_RN32(b) == AV_RN32("XPDS")) return AVPROBE_SCORE_EXTENSION + 1; return 0; }
1threat
def pair_wise(l1): temp = [] for i in range(len(l1) - 1): current_element, next_element = l1[i], l1[i + 1] x = (current_element, next_element) temp.append(x) return temp
0debug
return NSDate will in swift 2 : when When I change my streng to Nsdate , return nill and show error : > fatal error: unexpectedly found nil while unwrapping an Optional value for example : date = 8/9/2016 9:45:19 AM convertDate(DateString:String) -> NSDate{ let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MM/dd/yyyy hh:mm:ss a" let date = dateFormatter.dateFromString(DateString) print(date) // return nil return date! } You can guide what is the reason?
0debug
refactor function update model : My model: street_address, postal_code, latitude, longitude Controller (update): if @address.update(address_params) postal_code = address_params[:address_attributes][:postal_code] latitude, longitude = get_coordinate(postal_code) @address.latitude = latitude @address.longitude = longitude @address.save end I want if the function get_coordinate can't get the coordinate the operation update will return false. How can I refactor this piece of code ?
0debug
Firebase & Swift: How to use another database for storing larger files? : <p>I am currently trying to build a chat application in swift whilst using Firebase for real-time messaging. My only issue is I want users to send images, I want them to have profiles with images but I know Firebase has limited storage (or at least storage per pay tier is low for the number of connections you get)</p> <p>So I would like to know how to connect up another database and make calls when needed between the two. So when and image is sent in a message, rather than Firebase storing the image, it stores a URL to the image in the other database.</p> <p>I am under the impression something like AWS S3 is my best bet. any help is appreciated!</p>
0debug
when i click on a check box in header all the below checkbox should be checked : [enter image description here][1] [1]: https://i.stack.imgur.com/5fItf.png Please help me out. My code is Please help me out. My code is <asp:TemplateColumn HeaderText="Delete" HeaderStyle-ForeColor="White"> <HeaderTemplate> <asp:CheckBox ID="CheckBox3" Checked="false" onclick="CheckAll(this)" AutoPostBack="true" runat="server" /> </HeaderTemplate> <ItemTemplate> <asp:CheckBox ID="chkDelete_SO" runat="server" /> </ItemTemplate> <HeaderStyle CssClass="SentinelGridHeader" /> </asp:TemplateColumn> Please help me out. My code is This is for my grid id <asp:Panel ID="ShiftOverridePanel" runat="server"> <asp:DataGrid ID="dgShiftOverrideData" runat="server" AllowPaging="True" AllowSorting="True" OnSortCommand="Sort_Grid_SO" AutoGenerateColumns="False" Width="100%" OnItemCommand="dgShiftOverrideData_ItemCommand" OnPageIndexChanged="dgShiftOverrideData_PageIndexChanged" CssClass="Grid" DataKeyField="SOExceptionID">
0debug
int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags) { if(min_ts > ts || max_ts < ts) return -1; if (s->iformat->read_seek2) { int ret; ff_read_frame_flush(s); if (stream_index == -1 && s->nb_streams == 1) { AVRational time_base = s->streams[0]->time_base; ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base); min_ts = av_rescale_rnd(min_ts, time_base.den, time_base.num * (int64_t)AV_TIME_BASE, AV_ROUND_UP); max_ts = av_rescale_rnd(max_ts, time_base.den, time_base.num * (int64_t)AV_TIME_BASE, AV_ROUND_DOWN); } ret = s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags); if (ret >= 0) avformat_queue_attached_pictures(s); return ret; } if(s->iformat->read_timestamp){ } if (s->iformat->read_seek || 1) { int dir = (ts - (uint64_t)min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0); int ret = av_seek_frame(s, stream_index, ts, flags | dir); if (ret<0 && ts != min_ts && max_ts != ts) { ret = av_seek_frame(s, stream_index, dir ? max_ts : min_ts, flags | dir); if (ret >= 0) ret = av_seek_frame(s, stream_index, ts, flags | (dir^AVSEEK_FLAG_BACKWARD)); } return ret; } }
1threat
static void gic_reset(gic_state *s) { int i; memset(s->irq_state, 0, GIC_NIRQ * sizeof(gic_irq_state)); for (i = 0 ; i < NUM_CPU(s); i++) { s->priority_mask[i] = 0xf0; s->current_pending[i] = 1023; s->running_irq[i] = 1023; s->running_priority[i] = 0x100; #ifdef NVIC s->cpu_enabled[i] = 1; #else s->cpu_enabled[i] = 0; #endif } for (i = 0; i < 16; i++) { GIC_SET_ENABLED(i); GIC_SET_TRIGGER(i); } #ifdef NVIC s->enabled = 1; #else s->enabled = 0; #endif }
1threat
static int fill_default_ref_list(H264Context *h){ MpegEncContext * const s = &h->s; int i; int smallest_poc_greater_than_current = -1; Picture sorted_short_ref[32]; if(h->slice_type==B_TYPE){ int out_i; int limit= -1; for(out_i=0; out_i<h->short_ref_count; out_i++){ int best_i=-1; int best_poc=INT_MAX; for(i=0; i<h->short_ref_count; i++){ const int poc= h->short_ref[i]->poc; if(poc > limit && poc < best_poc){ best_poc= poc; best_i= i; } } assert(best_i != -1); limit= best_poc; sorted_short_ref[out_i]= *h->short_ref[best_i]; tprintf("sorted poc: %d->%d poc:%d fn:%d\n", best_i, out_i, sorted_short_ref[out_i].poc, sorted_short_ref[out_i].frame_num); if (-1 == smallest_poc_greater_than_current) { if (h->short_ref[best_i]->poc >= s->current_picture_ptr->poc) { smallest_poc_greater_than_current = out_i; } } } } if(s->picture_structure == PICT_FRAME){ if(h->slice_type==B_TYPE){ int list; tprintf("current poc: %d, smallest_poc_greater_than_current: %d\n", s->current_picture_ptr->poc, smallest_poc_greater_than_current); for(list=0; list<2; list++){ int index = 0; int j= -99; int step= list ? -1 : 1; for(i=0; i<h->short_ref_count && index < h->ref_count[list]; i++, j+=step) { while(j<0 || j>= h->short_ref_count){ if(j != -99 && step == (list ? -1 : 1)) return -1; step = -step; j= smallest_poc_greater_than_current + (step>>1); } if(sorted_short_ref[j].reference != 3) continue; h->default_ref_list[list][index ]= sorted_short_ref[j]; h->default_ref_list[list][index++].pic_id= sorted_short_ref[j].frame_num; } for(i = 0; i < 16 && index < h->ref_count[ list ]; i++){ if(h->long_ref[i] == NULL) continue; if(h->long_ref[i]->reference != 3) continue; h->default_ref_list[ list ][index ]= *h->long_ref[i]; h->default_ref_list[ list ][index++].pic_id= i;; } if(list && (smallest_poc_greater_than_current<=0 || smallest_poc_greater_than_current>=h->short_ref_count) && (1 < index)){ Picture temp= h->default_ref_list[1][0]; h->default_ref_list[1][0] = h->default_ref_list[1][1]; h->default_ref_list[1][1] = temp; } if(index < h->ref_count[ list ]) memset(&h->default_ref_list[list][index], 0, sizeof(Picture)*(h->ref_count[ list ] - index)); } }else{ int index=0; for(i=0; i<h->short_ref_count; i++){ if(h->short_ref[i]->reference != 3) continue; h->default_ref_list[0][index ]= *h->short_ref[i]; h->default_ref_list[0][index++].pic_id= h->short_ref[i]->frame_num; } for(i = 0; i < 16; i++){ if(h->long_ref[i] == NULL) continue; if(h->long_ref[i]->reference != 3) continue; h->default_ref_list[0][index ]= *h->long_ref[i]; h->default_ref_list[0][index++].pic_id= i;; } if(index < h->ref_count[0]) memset(&h->default_ref_list[0][index], 0, sizeof(Picture)*(h->ref_count[0] - index)); } }else{ if(h->slice_type==B_TYPE){ }else{ } } #ifdef TRACE for (i=0; i<h->ref_count[0]; i++) { tprintf("List0: %s fn:%d 0x%p\n", (h->default_ref_list[0][i].long_ref ? "LT" : "ST"), h->default_ref_list[0][i].pic_id, h->default_ref_list[0][i].data[0]); } if(h->slice_type==B_TYPE){ for (i=0; i<h->ref_count[1]; i++) { tprintf("List1: %s fn:%d 0x%p\n", (h->default_ref_list[1][i].long_ref ? "LT" : "ST"), h->default_ref_list[1][i].pic_id, h->default_ref_list[0][i].data[0]); } } #endif return 0; }
1threat
target_ulong helper_yield(target_ulong arg1) { if (arg1 < 0) { if (arg1 != -2) { if (env->CP0_VPEControl & (1 << CP0VPECo_YSI) && env->active_tc.CP0_TCStatus & (1 << CP0TCSt_DT)) { env->CP0_VPEControl &= ~(0x7 << CP0VPECo_EXCPT); env->CP0_VPEControl |= 4 << CP0VPECo_EXCPT; helper_raise_exception(EXCP_THREAD); } } } else if (arg1 == 0) { if (0 ) { env->CP0_VPEControl &= ~(0x7 << CP0VPECo_EXCPT); helper_raise_exception(EXCP_THREAD); } else { } } else if (arg1 > 0) { env->CP0_VPEControl &= ~(0x7 << CP0VPECo_EXCPT); env->CP0_VPEControl |= 2 << CP0VPECo_EXCPT; helper_raise_exception(EXCP_THREAD); } return env->CP0_YQMask; }
1threat
static av_cold int vcr1_decode_init(AVCodecContext *avctx) { avctx->pix_fmt = AV_PIX_FMT_YUV410P; return 0;
1threat
Can I use all the HTML tags inside a script tag of type javascript : <p>I've tried placing some of the HTML tags inside a JavaScript tag but its not working.can anyone explain it.</p>
0debug
How to writing a "if/unless" for an integer variable : I am trying to write a conditional where if a ends in 1 then it will answer with "st root" unless it ends with an 11 so it will be like 1st root or 11th root (Then also work in similar ways for 2/12 and 3/13) Here is the code I have tried def n(): print("Only enter whole numbers\n ") base = float(input("Enter number to take the root of, then hit enter:\n ")) input_string = input("Enter degree of roots (if more than one, separate by space) then hit enter:\n ") list = input_string.split() a = 1 for num in list: base **= (1/float(num)) for num in list: a *= int(num) if str(a)[-1] == '1': if str(a)[-1] != '11': print(a,"st root",base) elif str(a)[-1] == '2': if str(a)[-1] != '12': print(a,"nd root",base) elif str(a)[-1] == '3': if str(a)[-1] != '13': print(a,"rd root",base) else: print(a,"th root",base) n()
0debug
Building Progressive Web Apps using Python Flask : <p>Is it possible to build PWA's with Flask? More specifically, is it possible to register a service worker using Flask template rendering? If so, could anyone give some information on how to go about that or point to some resources? Because I was unable to find anything. Thank you.</p>
0debug
Running a local kibana in a container : <p>I am trying to run use kibana console with my local elasticsearch (container) In the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html" rel="noreferrer">ElasticSearch documentation</a> I see </p> <pre><code>docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:6.2.2 </code></pre> <p>Which lets me run the community edition in a quick one liner.</p> <p>Looking at the <a href="https://www.docker.elastic.co/#" rel="noreferrer">kibana documentation</a> i see only </p> <pre><code>docker pull docker.elastic.co/kibana/kibana:6.2.2 </code></pre> <p>Replacing pull with run it looks for the x-pack (I think it means not community) and fails to find the ES </p> <pre><code>Unable to revive connection: http://elasticsearch:9200/ </code></pre> <p>Is there a one liner that could easily set up kibana localy in a container? All I need is to work with the console (Sense replacement)</p>
0debug
webstorm: what does "Element is not exported" warning mean? : <p>if i write such code in webstorm </p> <pre><code>export class someOne { constructor(param) { this.test = param; } useTest(){ return this.test; } } console.log(new someOne(123).useTest()); </code></pre> <p>and mouseover on "this.test" i see the warning: "Element is not exported"</p> <p><a href="https://i.stack.imgur.com/UPh9s.png"><img src="https://i.stack.imgur.com/UPh9s.png" alt="element is not exported wtf"></a></p> <p>what does it mean? if i change the <code>.test</code> to <code>.test1</code> the warning disappears</p>
0debug
Git clone. key_load_public: invalid format Permission denied (publickey) : <p>I used puttygen.exe on Windows 10 to generate private and public keys. I saved that keys in C:\Users\Alexander\.ssh\</p> <p>Public key was added to remote repo (Not by me. I don't have an access).</p> <p>Then I used command in Git Bash: </p> <pre><code>git clone git@ipaddress:project_name.git </code></pre> <p>And I got an error:</p> <pre><code>key_load_public: invalid format Permission denied (publickey). fatal: Could not read from remote repository. </code></pre> <p>Example keys (generated for just for example)</p> <p>id_rsa.ppk</p> <pre><code>PuTTY-User-Key-File-2: ssh-rsa Encryption: none Comment: rsa-key-20170110 Public-Lines: 6 AAAAB3NzaC1yc2EAAAABJQAAAQEAx0UhtZcgUT5XpoNlcoVFGHbArEsARQVCv5m0 TRh90Xq15gxOvL+x7I0B29xOuOP054RtQaOzHqnKUzpMdrIoZFkYEYJ11p42kC05 PVR/CwtKBuONJZzoIveJlNG1IhbC3G8DMZD5j68T5OVbCqftHMIBe4CTr7TewJ9T /lmSZPytWXk/Xtcvn1i1TQZS2ShtSNOwtx77fLzkVmC6F4uM2JgJ9bSM2xQZTX/j DYZTtoEsmyBadANAEZx4kQAoITwxXVRPBPJnB74EdSMXNhrDBJ+sZSEy7kxmc3a/ UK6CzdN3wiEMd/Bb1nuzR2cpWrWhniG66lnOTJb3sF8iiVtw7Q== Private-Lines: 14 AAABAEtmRBsyQ5RcxzgWCrW14sr8gEExIrJVBH/ZSyQXGtmkDXmjysP1gZfGpsHk qCpIaoEdWcXPPNsrfPzloGRDaTq57W5otvdCyImUkjLhs4ejaB5IQz6qEqVya2i+ DS9+O+S0YhLBO9WAhBFrijtiIl3oivB11wQ2mXlRCwZLZ9MugQ3rPfS0O/E2asrO +MyiR2uv84lVb2wUT0Be3eeubnT2Qp8CoX3qV93LwBM053tepmD0jtSBsaXepADw mdjBfIkUm+z/69PKtsEoYtIRe5DQRGQhUrwZasJnrfwAvdkr56NKM/rEL0ocUPDX pXQalD88fKHKog5pr25c8aImklUAAACBAPmqhoRBWy+VJxgZ2BeMYv2PbmQCrQyp ZVqua9byU59cANjarPcEb1zSUVEJyO8KlTW1eiTeMrya3cdrqbk3Rhp8XgolRsrv ZK2rMQxP5nIoHyndtG1CCVqrWnwjIsb4r4cq2aBaUWjQJ+ofpiUHVkHev+h58zEA zpDZs0Jrv5n7AAAAgQDMU04pqQ1hnv050gs8C2Gy+DjbW8b/NbQl64x0HFik/lWB CRLrCd341ZQWY0PcU5ZjwNa8GwwJZPJI2bX84/a7dq2ENnT1+uYqpuK8lnPTcBDy WjlGcf/fWJyJpdLqqXkMZ7or4k9ReVIXz9A8xRkhGEH2xM8Vk2fyoLY88RFUNwAA AIA+zxdPdF8dPr8HwTJ5Pb0NQjl2likOxR24QmqxlCu/bD1p8R1tZzX5Jh2HP2on RO+KVLYHzNKqtKRZW/MHftYcm6AvYLhP7hxG/tFoNM9lEmsqdJenxaWP745LP9Pc k3qh7kC4KfTXyfgsd+C6dXzqhAokz81zL41QtyJxlQzR2w== Private-MAC: ce79771084cbabf61fc2bf3b1403e42a9957e2af </code></pre> <p>id_rsa.pub</p> <pre><code>---- BEGIN SSH2 PUBLIC KEY ---- Comment: "rsa-key-20170110" AAAAB3NzaC1yc2EAAAABJQAAAQEAx0UhtZcgUT5XpoNlcoVFGHbArEsARQVCv5m0 TRh90Xq15gxOvL+x7I0B29xOuOP054RtQaOzHqnKUzpMdrIoZFkYEYJ11p42kC05 PVR/CwtKBuONJZzoIveJlNG1IhbC3G8DMZD5j68T5OVbCqftHMIBe4CTr7TewJ9T /lmSZPytWXk/Xtcvn1i1TQZS2ShtSNOwtx77fLzkVmC6F4uM2JgJ9bSM2xQZTX/j DYZTtoEsmyBadANAEZx4kQAoITwxXVRPBPJnB74EdSMXNhrDBJ+sZSEy7kxmc3a/ UK6CzdN3wiEMd/Bb1nuzR2cpWrWhniG66lnOTJb3sF8iiVtw7Q== ---- END SSH2 PUBLIC KEY ---- </code></pre> <p>What may be wrong here?</p>
0debug
Collapsing CardView Animation not working correctly : <h2>What I'm trying to do</h2> <p>I have a <code>RecyclerView</code> with many items that are basically some <code>CardView</code>.</p> <p>Those cards have a supporting text in the middle of their bodies, which has the visibility set to <code>GONE</code> by default, and it's made <code>VISIBLE</code> when I click the arrow on the right of the card.</p> <p>I'm trying to animate the card while the text is revealed and while it's collapsed.</p> <p>The picture below shows the expanded card and the collapsed one:</p> <p><a href="https://i.stack.imgur.com/KPexfl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KPexfl.png" alt="cards"></a></p> <p>The <code>CardView</code> layout (I've removed some parts for readability):</p> <pre><code>&lt;android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" card_view:cardCornerRadius="3dp" card_view:cardElevation="4dp" card_view:cardUseCompatPadding="true" android:id="@+id/root"&gt; &lt;LinearLayout android:id="@+id/item_ll" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="@dimen/activity_vertical_margin"&gt; &lt;!-- The header with the title and the item --&gt; &lt;TextView android:id="@+id/body_content" style="@style/TextAppearance.AppCompat.Medium" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="8dp" android:layout_marginBottom="8dp" android:text="@string/about_page_description" android:textColor="@color/secondaryText" android:visibility="gone"/&gt; &lt;!-- The divider, and the footer with the timestamp --&gt; &lt;/LinearLayout&gt; &lt;/android.support.v7.widget.CardView&gt; </code></pre> <h2>The problem</h2> <p>The animations is working when the card is expanding and revealing the body <code>TextView</code>, however, when I try to collapse it back, the cards below the animated one overlaps the first one.</p> <p><strong>Example:</strong></p> <p><a href="https://i.stack.imgur.com/TCcc0.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/TCcc0.gif" alt="card animation"></a></p> <h2>What I've tried so far</h2> <p>I've already asked a <a href="https://stackoverflow.com/questions/41982987/collapsing-cardview-inside-recyclerview-when-animating">similar question about this behavior here</a> before, but that solution is not working for a <code>TextView</code> in the middle of the card.</p> <p>The code that's responsible for the animation part is inside the <code>RecyclerView</code> adapter. The arrow has a click listener that calls the method below:</p> <pre><code>private fun toggleVisibility() { if (bodyContent.visibility == View.GONE || bodyContent.visibility == View.INVISIBLE) { btSeeMore.animate().rotation(180f).start() TransitionManager.beginDelayedTransition(root, AutoTransition()) bodyContent.visibility = View.VISIBLE } else { btSeeMore.animate().rotation(0f).start() TransitionManager.beginDelayedTransition(root, AutoTransition()) bodyContent.visibility = View.GONE } } </code></pre> <p>Where <code>root</code> is my <code>CardView</code>.</p> <p>I've also tried to use the <code>LinearLayout</code> instead of the card itself for the delayed transition, but that didn't work either.</p> <p>How can I achieve that behavior for my layout?</p>
0debug
How to in Notepad ++ Short Case to Large Case Words? : I just want to use this method.... Short Case to Large Case Words.... ie: I have an email list....looks like... > abcdefg@example.org > abcde@example.org > abc@example.org2 > abcdefgh@example.org > abcdef@example.org > abcdefghi@example.org I want convert this list looks like... > abc@example.org > abcde@example.org > abcdef@example.org > abcdefg@example.org > abcdefgh@example.org > abcdefghi@example.org Please help me...
0debug
Why is visual studio code telling me that cout is not a member of std namespace? : <p>I am trying to setup visual studio code to program in c++. I have already installed the extensions <strong>C/C++</strong> and <strong>C/C++ Intellisense</strong></p> <p>Following is my code:</p> <pre><code>#include&lt;iostream&gt; using namespace std; int main() { cout&lt;&lt; "hello" ; } </code></pre> <p>The error I'm getting is <code>identifier cout is undefined</code> and when I write it as <code>std::cout</code> the error I get then is <code>namespace std has no member cout</code> . Following is my <code>task.json</code> file:</p> <pre><code>{ "version": "0.1.0", "command": "make", "isShellCommand": true, "tasks": [ { "taskName": "Makefile", // Make this the default build command. "isBuildCommand": true, // Show the output window only if unrecognized errors occur. "showOutput": "always", // No args "args": ["all"], // Use the standard less compilation problem matcher. "problemMatcher": { "owner": "cpp", "fileLocation": ["relative", "${workspaceRoot}"], "pattern": { "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$", "file": 1, "line": 2, "column": 3, "severity": 4, "message": 5 } } } ] } </code></pre> <p>How do i fix this?</p>
0debug
Unlink an existing firebase app? : <p>I want to "Link to new or existing Firebase project &amp; app" but the crashlytics dashboard told me my project is already linked,</p> <p>how to unlink my existing project ?</p> <p><a href="https://i.stack.imgur.com/Ybb97.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ybb97.png" alt="fabric"></a></p>
0debug
document.write('<script src="evil.js"></script>');
1threat
static uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri) { if (ri->type & ARM_CP_CONST) { return ri->resetvalue; } else if (ri->raw_readfn) { return ri->raw_readfn(env, ri); } else if (ri->readfn) { return ri->readfn(env, ri); } else { return raw_read(env, ri); } }
1threat
Python 3.6: What is the different between these two list comprehension calculations? : So, I'm still relatively new to python, and mostly self-taught. I've been running my own statistical analyses, but I'm curious as to why there are different outputs for the following two list comprehensions. I am using Jupyter Notebook on Ubuntu LTS 16.04: Input: "example = [[15, 16, 17], [18, 19, 20]] list1 = [item[0] + item[1] + item[2] for item in example] for item in example: list2 = [item[0] + item[1] + item[2]] list1, list2" Output: ([48, 57], [57]) Clearly the second function is printing the sum of the second row, but why not the first?
0debug
Flutter slideTransition is not animating : <p>So I'm trying to create a trivial slide transition element in flutter and I'm having some difficulty. What the below does is wait for the animation time, and then just display the <code>Text("hello there sailor")</code>. I don't know why this is not animating - it seems very similar to this previous post that has a trivial example (<a href="https://stackoverflow.com/questions/53278792/sliding-animation-to-bottom-in-flutter?noredirect=1&amp;lq=1">Sliding animation to bottom in flutter</a>).</p> <p>This is how I call the below code: <code>DeleteCheck(offsetBool: widget.model.deleteNotify, widthSlide: 0.50*width100)</code> where <code>double width100 = MediaQuery.of(context).size.width;</code>.</p> <p>Does anyone see what I am doing wrong?</p> <pre><code>class DeleteCheck extends StatefulWidget{ final offsetBool; final double widthSlide; DeleteCheck({ Key key, this.offsetBool, this.widthSlide }): super(key: key); @override State&lt;StatefulWidget&gt; createState() { return new _MyDeleteCheck(); } } class _MyDeleteCheck extends State&lt;DeleteCheck&gt; with TickerProviderStateMixin { AnimationController _controller; Animation&lt;Offset&gt; _offsetFloat; @override void initState() { super.initState(); _controller = AnimationController( vsync: this, duration: const Duration(seconds: 1), ); _offsetFloat = Tween&lt;Offset&gt;(begin: Offset(widget.widthSlide, 0.0), end: Offset.zero) .animate(_controller); _offsetFloat.addListener((){ setState((){}); }); _controller.forward(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { double height100 = MediaQuery.of(context).size.height; double width100 = MediaQuery.of(context).size.width; return new SlideTransition( position: _offsetFloat, child: Container( color: Colors.cyan, width: 0.525*width100-3.0, child: Text("hello there sailor") ) ); } } </code></pre>
0debug
How to Unwrap Type of a Promise : <p>Say I have the following code:</p> <pre><code>async promiseOne() { return 1 } // =&gt; Promise&lt;number&gt; const promisedOne = promiseOne() typeof promisedOne // =&gt; Promised&lt;number&gt; </code></pre> <p>How would I go about extracting the the type of the promise result (in this simplified case a number) as it's own type?</p>
0debug
def octal_To_Decimal(n): num = n; dec_value = 0; base = 1; temp = num; while (temp): last_digit = temp % 10; temp = int(temp / 10); dec_value += last_digit*base; base = base * 8; return dec_value;
0debug
static void qdev_print_devinfos(bool show_no_user) { static const char *cat_name[DEVICE_CATEGORY_MAX + 1] = { [DEVICE_CATEGORY_BRIDGE] = "Controller/Bridge/Hub", [DEVICE_CATEGORY_USB] = "USB", [DEVICE_CATEGORY_STORAGE] = "Storage", [DEVICE_CATEGORY_NETWORK] = "Network", [DEVICE_CATEGORY_INPUT] = "Input", [DEVICE_CATEGORY_DISPLAY] = "Display", [DEVICE_CATEGORY_SOUND] = "Sound", [DEVICE_CATEGORY_MISC] = "Misc", [DEVICE_CATEGORY_MAX] = "Uncategorized", }; GSList *list, *elt; int i; bool cat_printed; list = g_slist_sort(object_class_get_list(TYPE_DEVICE, false), devinfo_cmp); for (i = 0; i <= DEVICE_CATEGORY_MAX; i++) { cat_printed = false; for (elt = list; elt; elt = elt->next) { DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data, TYPE_DEVICE); if ((i < DEVICE_CATEGORY_MAX ? !test_bit(i, dc->categories) : !bitmap_empty(dc->categories, DEVICE_CATEGORY_MAX)) || (!show_no_user && dc->no_user)) { continue; } if (!cat_printed) { error_printf("%s%s devices:\n", i ? "\n" : "", cat_name[i]); cat_printed = true; } qdev_print_devinfo(dc); } } g_slist_free(list); }
1threat
Is there global .editorconfig in Visual Studio 2017 : <p>In Visual Studio 2017 we can use .editorconfig file in our project to set code style rules for the project. There is also a list of settings for Visual Studio itself presumably used when there is no editorconfig in the project. Is there a default editorconfig somewhere in Visual Studio that I can replace to set these settings rather than click through each of them?</p>
0debug
int main_loop(void *opaque) { struct pollfd ufds[3], *pf, *serial_ufd, *net_ufd, *gdb_ufd; int ret, n, timeout, serial_ok; uint8_t ch; CPUState *env = global_env; if (!term_inited) { term_inited = 1; term_init(); } serial_ok = 1; cpu_enable_ticks(); for(;;) { ret = cpu_x86_exec(env); if (reset_requested) { ret = EXCP_INTERRUPT; break; } if (ret == EXCP_DEBUG) { ret = EXCP_DEBUG; break; } if (ret == EXCP_HLT) timeout = 10; else timeout = 0; serial_ufd = NULL; pf = ufds; if (serial_ok && !(serial_ports[0].lsr & UART_LSR_DR)) { serial_ufd = pf; pf->fd = 0; pf->events = POLLIN; pf++; } net_ufd = NULL; if (net_fd > 0 && ne2000_can_receive(&ne2000_state)) { net_ufd = pf; pf->fd = net_fd; pf->events = POLLIN; pf++; } gdb_ufd = NULL; if (gdbstub_fd > 0) { gdb_ufd = pf; pf->fd = gdbstub_fd; pf->events = POLLIN; pf++; } ret = poll(ufds, pf - ufds, timeout); if (ret > 0) { if (serial_ufd && (serial_ufd->revents & POLLIN)) { n = read(0, &ch, 1); if (n == 1) { serial_received_byte(&serial_ports[0], ch); } else { serial_ok = 0; } } if (net_ufd && (net_ufd->revents & POLLIN)) { uint8_t buf[MAX_ETH_FRAME_SIZE]; n = read(net_fd, buf, MAX_ETH_FRAME_SIZE); if (n > 0) { if (n < 60) { memset(buf + n, 0, 60 - n); n = 60; } ne2000_receive(&ne2000_state, buf, n); } } if (gdb_ufd && (gdb_ufd->revents & POLLIN)) { uint8_t buf[1]; n = read(gdbstub_fd, buf, 1); if (n == 1) { ret = EXCP_INTERRUPT; break; } } } if (timer_irq_pending) { pic_set_irq(0, 1); pic_set_irq(0, 0); timer_irq_pending = 0; if (cmos_data[RTC_REG_B] & 0x40) { pic_set_irq(8, 1); } } if (gui_refresh_pending) { display_state.dpy_refresh(&display_state); gui_refresh_pending = 0; } } cpu_disable_ticks(); return ret; }
1threat
static void monitor_qapi_event_handler(void *opaque) { MonitorQAPIEventState *evstate = opaque; MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event]; trace_monitor_protocol_event_handler(evstate->event, evstate->qdict); qemu_mutex_lock(&monitor_lock); if (evstate->qdict) { int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME); monitor_qapi_event_emit(evstate->event, evstate->qdict); QDECREF(evstate->qdict); evstate->qdict = NULL; timer_mod_ns(evstate->timer, now + evconf->rate); } else { g_hash_table_remove(monitor_qapi_event_state, evstate); QDECREF(evstate->data); timer_free(evstate->timer); g_free(evstate); } qemu_mutex_unlock(&monitor_lock); }
1threat
void visit_type_size(Visitor *v, uint64_t *obj, const char *name, Error **errp) { int64_t value; if (!error_is_set(errp)) { if (v->type_size) { v->type_size(v, obj, name, errp); } else if (v->type_uint64) { v->type_uint64(v, obj, name, errp); } else { value = *obj; v->type_int(v, &value, name, errp); *obj = value; } } }
1threat
How to find height of status bar in Android through React Native? : <p>How can I find the height of the status bar on Android through React Native?</p> <p>If I check the <code>React.Dimensions</code> height the value seems to include the status bar height too but I'm trying to find the height of the layout without the status bar.</p>
0debug
int avresample_open(AVAudioResampleContext *avr) { int ret; avr->in_channels = av_get_channel_layout_nb_channels(avr->in_channel_layout); if (avr->in_channels <= 0 || avr->in_channels > AVRESAMPLE_MAX_CHANNELS) { av_log(avr, AV_LOG_ERROR, "Invalid input channel layout: %"PRIu64"\n", avr->in_channel_layout); return AVERROR(EINVAL); } avr->out_channels = av_get_channel_layout_nb_channels(avr->out_channel_layout); if (avr->out_channels <= 0 || avr->out_channels > AVRESAMPLE_MAX_CHANNELS) { av_log(avr, AV_LOG_ERROR, "Invalid output channel layout: %"PRIu64"\n", avr->out_channel_layout); return AVERROR(EINVAL); } avr->resample_channels = FFMIN(avr->in_channels, avr->out_channels); avr->downmix_needed = avr->in_channels > avr->out_channels; avr->upmix_needed = avr->out_channels > avr->in_channels || avr->am->matrix || (avr->out_channels == avr->in_channels && avr->in_channel_layout != avr->out_channel_layout); avr->mixing_needed = avr->downmix_needed || avr->upmix_needed; avr->resample_needed = avr->in_sample_rate != avr->out_sample_rate || avr->force_resampling; if (avr->internal_sample_fmt == AV_SAMPLE_FMT_NONE && (avr->mixing_needed || avr->resample_needed)) { enum AVSampleFormat in_fmt = av_get_planar_sample_fmt(avr->in_sample_fmt); enum AVSampleFormat out_fmt = av_get_planar_sample_fmt(avr->out_sample_fmt); int max_bps = FFMAX(av_get_bytes_per_sample(in_fmt), av_get_bytes_per_sample(out_fmt)); if (max_bps <= 2) { avr->internal_sample_fmt = AV_SAMPLE_FMT_S16P; } else if (avr->mixing_needed) { avr->internal_sample_fmt = AV_SAMPLE_FMT_FLTP; } else { if (max_bps <= 4) { if (in_fmt == AV_SAMPLE_FMT_S32P || out_fmt == AV_SAMPLE_FMT_S32P) { if (in_fmt == AV_SAMPLE_FMT_FLTP || out_fmt == AV_SAMPLE_FMT_FLTP) { avr->internal_sample_fmt = AV_SAMPLE_FMT_DBLP; } else { avr->internal_sample_fmt = AV_SAMPLE_FMT_S32P; } } else { avr->internal_sample_fmt = AV_SAMPLE_FMT_FLTP; } } else { avr->internal_sample_fmt = AV_SAMPLE_FMT_DBLP; } } av_log(avr, AV_LOG_DEBUG, "Using %s as internal sample format\n", av_get_sample_fmt_name(avr->internal_sample_fmt)); } if (avr->in_channels == 1) avr->in_sample_fmt = av_get_planar_sample_fmt(avr->in_sample_fmt); if (avr->out_channels == 1) avr->out_sample_fmt = av_get_planar_sample_fmt(avr->out_sample_fmt); avr->in_convert_needed = (avr->resample_needed || avr->mixing_needed) && avr->in_sample_fmt != avr->internal_sample_fmt; if (avr->resample_needed || avr->mixing_needed) avr->out_convert_needed = avr->internal_sample_fmt != avr->out_sample_fmt; else avr->out_convert_needed = avr->in_sample_fmt != avr->out_sample_fmt; if (avr->mixing_needed || avr->in_convert_needed) { avr->in_buffer = ff_audio_data_alloc(FFMAX(avr->in_channels, avr->out_channels), 0, avr->internal_sample_fmt, "in_buffer"); if (!avr->in_buffer) { ret = AVERROR(EINVAL); goto error; } } if (avr->resample_needed) { avr->resample_out_buffer = ff_audio_data_alloc(avr->out_channels, 0, avr->internal_sample_fmt, "resample_out_buffer"); if (!avr->resample_out_buffer) { ret = AVERROR(EINVAL); goto error; } } if (avr->out_convert_needed) { avr->out_buffer = ff_audio_data_alloc(avr->out_channels, 0, avr->out_sample_fmt, "out_buffer"); if (!avr->out_buffer) { ret = AVERROR(EINVAL); goto error; } } avr->out_fifo = av_audio_fifo_alloc(avr->out_sample_fmt, avr->out_channels, 1024); if (!avr->out_fifo) { ret = AVERROR(ENOMEM); goto error; } if (avr->in_convert_needed) { avr->ac_in = ff_audio_convert_alloc(avr, avr->internal_sample_fmt, avr->in_sample_fmt, avr->in_channels); if (!avr->ac_in) { ret = AVERROR(ENOMEM); goto error; } } if (avr->out_convert_needed) { enum AVSampleFormat src_fmt; if (avr->in_convert_needed) src_fmt = avr->internal_sample_fmt; else src_fmt = avr->in_sample_fmt; avr->ac_out = ff_audio_convert_alloc(avr, avr->out_sample_fmt, src_fmt, avr->out_channels); if (!avr->ac_out) { ret = AVERROR(ENOMEM); goto error; } } if (avr->resample_needed) { avr->resample = ff_audio_resample_init(avr); if (!avr->resample) { ret = AVERROR(ENOMEM); goto error; } } if (avr->mixing_needed) { ret = ff_audio_mix_init(avr); if (ret < 0) goto error; } return 0; error: avresample_close(avr); return ret; }
1threat
fatal error: unexpectedly found nil while unwrapping an Optional value - swift 3 : <p>my question isn't duplicate because I read them before.</p> <p>my code:</p> <pre><code>var str_images = "http://kashanmap.ir/images/apk_images/off/33/Cta_off _1_.jpg ,http://kashanmap.ir/images/apk_images/off/33/Cta_off _2_.jpg ,http://kashanmap.ir/images/apk_images/off/33/Cta_off-_4_.jpg" for one_img in multi_img{ print("one: \(one_img)") var img = one_img //self.imgs_slider.append(img) let alamofireSource = AlamofireSource(urlString: img)! images.append(alamofireSource) } </code></pre> <p>my console log:</p> <pre><code>one: http://kashanmap.ir/images/apk_images/off/33/Cta_off _1_.jpg fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) </code></pre> <p><a href="https://i.stack.imgur.com/xgVYA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xgVYA.png" alt="enter image description here"></a></p> <p>I changed this line:</p> <pre><code> var img = one_img </code></pre> <p>to:</p> <pre><code> var img = one_img? </code></pre> <p>or</p> <pre><code> var img = one_img! </code></pre> <p>but Xcode shows a red cycle to remove <code>?</code> or <code>!</code> . </p>
0debug
Android Studio Image Asset Launcher Icon Background Color : <p>I have a .png logo for my app which doesn't have a background, when I add it to android studio as an Image Asset I am forced to have a background. The hex field doesn't accept 8 digit color codes, 6 digits only. Is there anyway to keep the background invisible?</p>
0debug
Convert string to ArrayList of String in Java : <p>I have this string -</p> <pre><code>"["222.222.222.222", "21.21.21.21"]"; //Plain String which is actually an JSON Array </code></pre> <p>I want the output 222.222.222.222 and 21.21.21.21 in a ArrayList.</p> <p>Please assist.</p> <p>Thanks</p>
0debug
How can I take integer regex in Python? : I'm trying to use regex in Python for taking some parts of a text. From a text I need to take this kind of substring '2012-048984'. So what's the equivalent regex? Thank you very much.
0debug
static void test_sum_square(void) { INTFLOAT res0; INTFLOAT res1; LOCAL_ALIGNED_16(INTFLOAT, src, [256], [2]); declare_func(INTFLOAT, INTFLOAT (*x)[2], int n); randomize((INTFLOAT *)src, 256 * 2); res0 = call_ref(src, 256); res1 = call_new(src, 256); if (!float_near_abs_eps(res0, res1, EPS)) fail(); bench_new(src, 256); }
1threat
Passing data between a method and an event function : <p>Hello I have been struggling trying to get the event to trigger based on the object that it is passed.... I am not sure if that's how it should be worded but you guys can take a look at the book and give me some insight</p> <p>I am making a datagrid form, inside this form, there's a function</p> <pre><code>private void (List&lt;string&gt; listProducts&gt; { foreach (aProduct in listProducts) { // reset row data rowProduct = new string[10]; // add the row this.dataDisplay.Tables["ProductData"].Rows.Add(rowProduct); double checkingresult; checkingresult = checkDiameter(aProduct); } </code></pre> <p>Inside this form there's a function that would check the validity of the test product, so checkingresult would return 0 or 1</p> <p>Then I created an event button to click on to change the color of the cell in the datagrid when it is clicked</p> <pre><code> private void bttnChecking_Click(object sender, EventArgs e) { DataGridViewCellStyle style = new DataGridViewCellStyle(); style.Font = new Font(datagridProductData.Font, FontStyle.Bold); style.BackColor = Color.Red; style.ForeColor = Color.White; foreach (aProduct in ListProducts) { } for (int i = 0; i &lt; RowCount - 1; i++) { Rows[i].Cells[5].Style = style; } } } </code></pre> <p>my question is, how do I pass the "checkingresult" into the event to change the color when it returns 0 or 1. Pls halp </p>
0debug
Basic FTP-Client in Java? : I want to write a FTP-Client in Java with a restriction: No advanced libraries (e.g. .ftp, .url etc.) allowed. How do I implement a method to print the current directory, change directory and download a simple .txt-file?
0debug
authorizenet not working in live server : I am using this code to create customer profile http://developer.authorize.net/api/reference/index.html#customer-profiles-create-customer-profile this is working fine locally but not working in live server. Showing 500 server error when execute the line no 58. (see sample code in above link) My php version 5.4+ in server and met all requirement mentioned in https://github.com/AuthorizeNet/sdk-php even all dependent library available in server which is required for this SDK ** working on sandbox
0debug
int bdrv_open(BlockDriverState **pbs, const char *filename, const char *reference, QDict *options, int flags, BlockDriver *drv, Error **errp) { int ret; BlockDriverState *file = NULL, *bs; const char *drvname; Error *local_err = NULL; int snapshot_flags = 0; assert(pbs); if (reference) { bool options_non_empty = options ? qdict_size(options) : false; QDECREF(options); if (*pbs) { error_setg(errp, "Cannot reuse an existing BDS when referencing " "another block device"); return -EINVAL; } if (filename || options_non_empty) { error_setg(errp, "Cannot reference an existing block device with " "additional options or a new filename"); return -EINVAL; } bs = bdrv_lookup_bs(reference, reference, errp); if (!bs) { return -ENODEV; } bdrv_ref(bs); *pbs = bs; return 0; } if (*pbs) { bs = *pbs; } else { bs = bdrv_new(); } if (options == NULL) { options = qdict_new(); } ret = bdrv_fill_options(&options, &filename, flags, drv, &local_err); if (local_err) { goto fail; } drv = NULL; drvname = qdict_get_try_str(options, "driver"); if (drvname) { drv = bdrv_find_format(drvname); qdict_del(options, "driver"); if (!drv) { error_setg(errp, "Unknown driver: '%s'", drvname); ret = -EINVAL; goto fail; } } assert(drvname || !(flags & BDRV_O_PROTOCOL)); if (drv && !drv->bdrv_file_open) { flags &= ~BDRV_O_PROTOCOL; } bs->options = options; options = qdict_clone_shallow(options); if ((flags & BDRV_O_PROTOCOL) == 0) { if (flags & BDRV_O_RDWR) { flags |= BDRV_O_ALLOW_RDWR; } if (flags & BDRV_O_SNAPSHOT) { snapshot_flags = bdrv_temp_snapshot_flags(flags); flags = bdrv_backing_flags(flags); } assert(file == NULL); ret = bdrv_open_image(&file, filename, options, "file", bdrv_inherited_flags(flags), true, &local_err); if (ret < 0) { goto fail; } } bs->probed = !drv; if (!drv && file) { ret = find_image_format(file, filename, &drv, &local_err); if (ret < 0) { goto fail; } } else if (!drv) { error_setg(errp, "Must specify either driver or file"); ret = -EINVAL; goto fail; } ret = bdrv_open_common(bs, file, options, flags, drv, &local_err); if (ret < 0) { goto fail; } if (file && (bs->file != file)) { bdrv_unref(file); file = NULL; } if ((flags & BDRV_O_NO_BACKING) == 0) { QDict *backing_options; qdict_extract_subqdict(options, &backing_options, "backing."); ret = bdrv_open_backing_file(bs, backing_options, &local_err); if (ret < 0) { goto close_and_fail; } } bdrv_refresh_filename(bs); if (snapshot_flags) { ret = bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err); if (local_err) { goto close_and_fail; } } if (options && (qdict_size(options) != 0)) { const QDictEntry *entry = qdict_first(options); if (flags & BDRV_O_PROTOCOL) { error_setg(errp, "Block protocol '%s' doesn't support the option " "'%s'", drv->format_name, entry->key); } else { error_setg(errp, "Block format '%s' used by device '%s' doesn't " "support the option '%s'", drv->format_name, bdrv_get_device_name(bs), entry->key); } ret = -EINVAL; goto close_and_fail; } if (!bdrv_key_required(bs)) { if (bs->blk) { blk_dev_change_media_cb(bs->blk, true); } } else if (!runstate_check(RUN_STATE_PRELAUNCH) && !runstate_check(RUN_STATE_INMIGRATE) && !runstate_check(RUN_STATE_PAUSED)) { error_setg(errp, "Guest must be stopped for opening of encrypted image"); ret = -EBUSY; goto close_and_fail; } QDECREF(options); *pbs = bs; return 0; fail: if (file != NULL) { bdrv_unref(file); } QDECREF(bs->options); QDECREF(options); bs->options = NULL; if (!*pbs) { bdrv_unref(bs); } if (local_err) { error_propagate(errp, local_err); } return ret; close_and_fail: if (*pbs) { bdrv_close(bs); } else { bdrv_unref(bs); } QDECREF(options); if (local_err) { error_propagate(errp, local_err); } return ret; }
1threat
void cpu_reset (CPUMIPSState *env) { memset(env, 0, offsetof(CPUMIPSState, breakpoints)); tlb_flush(env, 1); #if defined(CONFIG_USER_ONLY) env->hflags = MIPS_HFLAG_UM; #else if (env->hflags & MIPS_HFLAG_BMASK) { env->CP0_ErrorEPC = env->active_tc.PC - 4; } else { env->CP0_ErrorEPC = env->active_tc.PC; env->active_tc.PC = (int32_t)0xBFC00000; env->CP0_Wired = 0; env->CP0_EBase = 0x80000000; env->CP0_Status = (1 << CP0St_BEV) | (1 << CP0St_ERL); env->CP0_IntCtl = 0xe0000000; { int i; for (i = 0; i < 7; i++) { env->CP0_WatchLo[i] = 0; env->CP0_WatchHi[i] = 0x80000000; env->CP0_WatchLo[7] = 0; env->CP0_WatchHi[7] = 0; env->CP0_Debug = (1 << CP0DB_CNT) | (0x1 << CP0DB_VER); env->hflags = MIPS_HFLAG_CP0; #endif env->exception_index = EXCP_NONE; cpu_mips_register(env, env->cpu_model);
1threat
What is the point of the constants in redux? : <p>For example from this example:</p> <pre><code>export const ADD_TODO = 'ADD_TODO' export const DELETE_TODO = 'DELETE_TODO' export const EDIT_TODO = 'EDIT_TODO' export const COMPLETE_TODO = 'COMPLETE_TODO' export const COMPLETE_ALL = 'COMPLETE_ALL' export const CLEAR_COMPLETED = 'CLEAR_COMPLETED' </code></pre> <p>It's not like you're saving characters. The variable name is exactly the same as the string, and will never change. I understand making constants if one day you were doing to do something like:</p> <pre><code>ADD_TODO = 'CREATE_TODO' </code></pre> <p>but that never happens. So what purpose do these constants serve?</p>
0debug
Compiling Code on Linux Server Seems to Run Differently : <p>I couldn't think of a good way to name this question, as the description of the issue is pretty lengthy. Basically, the issue I'm having is, code that I wrote in Xcode on my mac isn't running the same after I upload to a linux server for my school. I've never had this issue before. Its not a syntax issue, which is something that I might run into (IE maybe I dont need to include a certain header file on Xcode that needs to be included to run on the linux server, so I get an error when I try to compile there), but its a logic error. One specific if-else statement is evaluating entirely wrong. It works correctly in Xcode, but with the same .cc file uploaded to the linux server and compiled with a makefile, it has a totally different result, using the same exact input that was used in Xcode. I even open the .cc file with emacs after uploading to make sure none of the code has been altered from a botched upload, but nothing has changed at all. This is very strange. I've never ran into this sort of issue before. I'd like to provide the code, but it might be entirely too long, so I need to break it down into a smaller example. For now, I'd like to know if this is something anyone else has ever ran into. The assignment deals with graph theory. I'm typing in 'A' and 'B' to draw edges between two vertices. You can see it works from the Xcode build, but not from the Linux build.</p> <p><a href="https://i.stack.imgur.com/2Tpjd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2Tpjd.png" alt="Program Ran From Xcode Build In Terminal"></a> <a href="https://i.stack.imgur.com/PJNI9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PJNI9.png" alt="Program Ran after Compiling on Linux Server and Being Ran"></a></p>
0debug
Python for loop - to iterate or not to iterate? : I'm writing a hangman game using Python, based on a specific set of instructions. I specifically need to use a for loop in order to replace all the letters in a word with underscores and in fact I am succeeding in doing so. However I have one slight issue, I'm getting a new line of underscores printed for every letter in my word. Is there a way to get rid of this? Can someone guide me on what is wrong with my logic? Thanks in advance. word = "test" def createBlank(word): for letter in word: blanks = '_' * len(word) print(blanks) My result is as you would assume: >>> word 'test' >>> createBlank(word) ____ #<- only need this line to be printed.. is it even possible using a for? ____ ____ ____
0debug
int qemu_file_rate_limit(QEMUFile *f) { if (f->ops->rate_limit) return f->ops->rate_limit(f->opaque); return 0; }
1threat
int get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx, target_ulong eaddr, int rw, int access_type) { int ret; #if 0 qemu_log("%s\n", __func__); #endif if ((access_type == ACCESS_CODE && msr_ir == 0) || (access_type != ACCESS_CODE && msr_dr == 0)) { if (env->mmu_model == POWERPC_MMU_BOOKE) { ret = mmubooke_get_physical_address(env, ctx, eaddr, rw, access_type); } else if (env->mmu_model == POWERPC_MMU_BOOKE206) { ret = mmubooke206_get_physical_address(env, ctx, eaddr, rw, access_type); } else { ret = check_physical(env, ctx, eaddr, rw); } } else { ret = -1; switch (env->mmu_model) { case POWERPC_MMU_32B: case POWERPC_MMU_601: case POWERPC_MMU_SOFT_6xx: case POWERPC_MMU_SOFT_74xx: if (env->nb_BATs != 0) { ret = get_bat(env, ctx, eaddr, rw, access_type); } #if defined(TARGET_PPC64) case POWERPC_MMU_620: case POWERPC_MMU_64B: case POWERPC_MMU_2_06: #endif if (ret < 0) { ret = get_segment(env, ctx, eaddr, rw, access_type); } break; case POWERPC_MMU_SOFT_4xx: case POWERPC_MMU_SOFT_4xx_Z: ret = mmu40x_get_physical_address(env, ctx, eaddr, rw, access_type); break; case POWERPC_MMU_BOOKE: ret = mmubooke_get_physical_address(env, ctx, eaddr, rw, access_type); break; case POWERPC_MMU_BOOKE206: ret = mmubooke206_get_physical_address(env, ctx, eaddr, rw, access_type); break; case POWERPC_MMU_MPC8xx: cpu_abort(env, "MPC8xx MMU model is not implemented\n"); break; case POWERPC_MMU_REAL: cpu_abort(env, "PowerPC in real mode do not do any translation\n"); return -1; default: cpu_abort(env, "Unknown or invalid MMU model\n"); return -1; } } #if 0 qemu_log("%s address " TARGET_FMT_lx " => %d " TARGET_FMT_plx "\n", __func__, eaddr, ret, ctx->raddr); #endif return ret; }
1threat
How to convert String to Float Array? : I have a String like this String volt; and it has values like [1.2, 3.1, 5.3...] How can I convert the String to a float array ?
0debug
c# HastSet init takes too long : I'm dealing with the fact that I need to init a HashSet with a set of elements but without any kind of comparation class. After the init, any element added to the HashSet need to be passed with a comparator. How can I accomplish it? Now I have this: HashSet<Keyword> set = new HashSet<Keyword>(new KeyWordComparer()); The problem is that the init takes to long and there's no necessity in applying the comparation.
0debug
static int match_format(const char *name, const char *names) { const char *p; int len, namelen; if (!name || !names) return 0; namelen = strlen(name); while ((p = strchr(names, ','))) { len = FFMAX(p - names, namelen); if (!av_strncasecmp(name, names, len)) return 1; names = p + 1; } return !av_strcasecmp(name, names); }
1threat
Pandas: split column of lists of unequal length into multiple columns : <p>I have a Pandas dataframe that looks like the below:</p> <pre><code> codes 1 [71020] 2 [77085] 3 [36415] 4 [99213, 99287] 5 [99233, 99233, 99233] </code></pre> <p>I'm trying to split the lists in <code>df['codes']</code> into columns, like the below:</p> <pre><code> code_1 code_2 code_3 1 71020 2 77085 3 36415 4 99213 99287 5 99233 99233 99233 </code></pre> <p>where columns that don't have a value (because the list was not that long) are filled with blanks or NaNs or something.</p> <p>I've seen answers like <a href="https://stackoverflow.com/questions/35491274/pandas-split-column-of-lists-into-multiple-columns">this one</a> and others similar to it, and while they work on lists of equal length, they all throw errors when I try to use the methods on lists of unequal length. Is there a good way do to this?</p>
0debug
static void nop(DBDMA_channel *ch) { dbdma_cmd *current = &ch->current; if (conditional_wait(ch)) goto wait; current->xfer_status = cpu_to_le16(be32_to_cpu(ch->regs[DBDMA_STATUS])); dbdma_cmdptr_save(ch); conditional_interrupt(ch); conditional_branch(ch); wait: qemu_bh_schedule(dbdma_bh); }
1threat
static inline void RENAME(rgb16ToUV)(uint8_t *dstU, uint8_t *dstV, uint8_t *src1, uint8_t *src2, int width) { int i; assert(src1 == src2); for(i=0; i<width; i++) { int d0= ((uint32_t*)src1)[i]; int dl= (d0&0x07E0F81F); int dh= ((d0>>5)&0x07C0F83F); int dh2= (dh>>11) + (dh<<21); int d= dh2 + dl; int r= d&0x7F; int b= (d>>11)&0x7F; int g= d>>21; dstU[i]= ((2*RU*r + GU*g + 2*BU*b)>>(RGB2YUV_SHIFT+1-2)) + 128; dstV[i]= ((2*RV*r + GV*g + 2*BV*b)>>(RGB2YUV_SHIFT+1-2)) + 128; } }
1threat
C - Inconsistent Data from Socket : <p>I've got a simple proxy server program written in C for a course. I'm having some issues with inconsistent data. When I request the website, I save the resulting data in a file on the server side, then send it over to the client and save it on the client side as well. The results on both the client and server will be of different sizes and it appears that some of the HTML is being duplicated. Typically, the file saved on the server will be smaller than the one saved on the client, although both files are still larger than the actual web page (i.e., if I were to right click the page and 'save as', the resulting page is smaller than those returned by my code). I've tried various things to resolve this issue and nothing seems to work. The results even seem to differ between attempts at the same website. For instance, I can request the same website twice, yet the file sizes differ from both attempts. In very rare occasions, especially on small websites, both the client and server program return the correct web page and both files are of the appropriate size.</p> <p>Note: I'm aware that the code is still rather messy. I'm more worried about addressing this issue before I move any further. I will address issues (such as checking if the socket failed to open) once this issue is corrected, so please only address the issue I have outlined.</p> <p>Server.c</p> <pre><code>#include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netdb.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;regex.h&gt; #include &lt;time.h&gt; /*Code used to resolve URL into IP address adapted from following URL: http://www.binarytides.com/hostname-to-ip-address-c-sockets-linux/ */ //This code has been adapted from the server code provided in class int main(int argc, char** argv) { char str[655360]; char recvline[655360]; char parsedRecv[655360]; char domain[1025]; char directory[1025]; char absoluteURL[1025]; char temp[1025]; int listen_fd, conn_fd, n, tempCount; struct sockaddr_in servaddr; int bytesRead; int stringCounter; int port; FILE *fp; //Variables used for second socket and resolving of host char ip[100]; int sockfd, secondSocketCount; int len = sizeof(struct sockaddr); struct sockaddr_in secondServaddr; struct addrinfo *servinfo, *p; struct sockaddr_in *h; int rv; char simpleMatch[10]; int flag = 0; //End //Used for HTTP GET request char request[2049]; listen_fd = socket(AF_INET, SOCK_STREAM, 0); bzero(&amp;servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htons(INADDR_ANY); if(argc &lt; 2) { printf("Error! Enter a port number to run this server on.\n\tEx: ./server 22000\n\r\0"); return 0; } else { port = atoi(argv[1]); } servaddr.sin_port = htons(port); printf("\n"); printf("Awaiting connections...\n"); bind(listen_fd, (struct sockaddr*)&amp;servaddr, sizeof(servaddr)); listen(listen_fd, 10); //Once the server is listening, enter an infinite loop to keep listening while(1) { conn_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL); bytesRead = read(conn_fd, recvline, sizeof(recvline)); if(bytesRead &gt; 0) //data read { recvline[bytesRead] = '\0'; bzero(absoluteURL, 1025); strcpy(absoluteURL, recvline); //Extract host and page from recvline //For loop used to check if URL begins with HTTP or HTTPS for(stringCounter = 0; stringCounter &lt; 5; stringCounter++) { simpleMatch[stringCounter] = tolower(recvline[stringCounter]); } simpleMatch[strlen(simpleMatch)] = '\0'; if(strcmp("http:", simpleMatch) == 0) { for(stringCounter = 7, tempCount = 0; stringCounter &lt; strlen(recvline); stringCounter++, tempCount++) { temp[tempCount] = recvline[stringCounter]; } temp[strlen(temp)] = '\0'; strcpy(recvline, temp); } else if(strcmp("https", simpleMatch) == 0) { for(stringCounter = 8, tempCount = 0; stringCounter &lt; strlen(recvline); stringCounter++, tempCount++) { temp[tempCount] = recvline[stringCounter]; } temp[strlen(temp)] = '\0'; strcpy(recvline, temp); } //printf("\n\nAfter stripping HTTP, we are left with: %s\n\n", recvline); //Now that HTTP:// or HTTPS:// has been stripped, can parse for domain for(stringCounter = 0, tempCount = 0; stringCounter &lt; strlen(recvline); stringCounter++) { //moving domain into the domain string if(flag == 0) { if(recvline[stringCounter] != '/') { domain[stringCounter] = recvline[stringCounter]; } else { domain[stringCounter + 1] = '\0'; //directory[tempCount] = recvline[stringCounter]; flag = 1; tempCount++; } } else { directory[tempCount] = recvline[stringCounter]; tempCount++; } } //printf("\n\nDirectory is: %s\n\n", directory); //reset flag and append '\0' to directory and domain flag = 0; if(tempCount &lt; 1025) { directory[tempCount] = '\0'; } //directory[strlen(directory)] = '\0'; //domain[strlen(domain)] = '\0'; //Done extracting //Resolve hostname to IP if((rv = getaddrinfo(domain, NULL, NULL, &amp;servinfo)) != 0) { printf("Error: an IP address cannot be resolved for %s\n", domain); return 0; //fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); } else { for(p = servinfo; p != NULL; p = p-&gt;ai_next) { h = (struct sockaddr_in *) p-&gt;ai_addr; strcpy(ip, inet_ntoa(h-&gt;sin_addr)); } freeaddrinfo (servinfo); printf("%s resolved to: %s\n", domain, ip); } //End Resolve //Now that the IP is resolved, open a socket and connect to the IP //Open socket sockfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&amp;secondServaddr, sizeof(secondServaddr)); secondServaddr.sin_family = AF_INET; secondServaddr.sin_port = htons(80); inet_pton(AF_INET, ip, &amp;(secondServaddr.sin_addr)); //IP taken from earlier resolution connect(sockfd, (struct sockaddr*) &amp;secondServaddr, sizeof(secondServaddr)); //socket is open, can create and send request, finally bzero(request, 2049); //sprintf(request, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", directory, domain); //sprintf(request, "GET %s HTTP/1.1\r\n\r\n", absoluteURL); //sprintf(request, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", absoluteURL, domain); sprintf(request, "GET /%s HTTP/1.1\r\nHost: %s\r\n\r\n", directory, domain); write(sockfd, request, strlen(request)); printf("\tAttempting to retrieve data: this may be slow.\n"); bzero(recvline, 655360); bzero(parsedRecv, 655360); //Old method used to retrieve data //This was changed when I began to run into issues /*while(1) { secondSocketCount = read(sockfd, parsedRecv, sizeof(parsedRecv)); if(secondSocketCount == -1) { printf("Error receiving data: server terminating.\n"); return 0; } else if(secondSocketCount == 0) { //no more data break; } strcat(recvline, parsedRecv); }*/ //This while loop is used to read in data (the response from the server) bzero(str, 655360); while(secondSocketCount = read(sockfd, recvline, sizeof(recvline)) &gt; 0) { strcat(str, recvline); } //bzero(parsedRecv, 655360); //recvline[strlen(recvline)] = '\0'; printf("\tData retrieved from main server.\n"); //This for loop finds the end of the HTTP header and copies everything after into parsedRecv for(stringCounter = 0, tempCount = 0; stringCounter &lt; strlen(str); stringCounter++) { //lazy if statement to find two \r\n in a row to mark the end of the header if(str[stringCounter] == '\r' &amp;&amp; str[stringCounter + 1] == '\n' &amp;&amp; str[stringCounter + 2] == '\r' &amp;&amp; str[stringCounter + 3] == '\n' &amp;&amp; flag == 0) { flag = 1; stringCounter += 3; } if(flag == 1) { parsedRecv[tempCount] = str[stringCounter]; tempCount++; } } flag = 0; parsedRecv[strlen(parsedRecv)] = '\0'; fp = fopen("ReturnedPageServer.html", "w"); if(fp != NULL) { fprintf(fp, "%s", parsedRecv); //fprintf(fp, "%s", recvline); } fclose(fp); printf("\tData saved to ReturnedPageServer.html\n"); } //strcpy(str, "This is a test of the Hello World Broadcast System.\n"); bzero(str, 655360); strcpy(str, parsedRecv); write(conn_fd, str, strlen(str)); close(conn_fd); printf("\tData sent to client.\n"); printf("Awaiting further connections...\n"); //strcpy(directory, ""); //strcpy(domain, ""); //strcpy(recvline, ""); bzero(directory, 1025); bzero(domain, 1025); bzero(temp, 1025); bzero(recvline, 655360); } return 0; } </code></pre> <p>Client.c</p> <pre><code>#include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netdb.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; //Code adapted from client code provided in class int main(int argc, char** argv) { int sockfd, n, port; int len = sizeof(struct sockaddr); char sendline[10000]; char recvline[655360]; struct sockaddr_in servaddr; FILE *fp; sockfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&amp;servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; if(argc &lt; 2) { printf("Error! Enter the port number for the server.\n\tEx: ./client 22000\n\r\0"); return 0; } else { port = atoi(argv[1]); } servaddr.sin_port = htons(port); inet_pton(AF_INET, "129.120.151.94", &amp;(servaddr.sin_addr)); //CSE01 IP connect(sockfd, (struct sockaddr*) &amp;servaddr, sizeof(servaddr)); printf("url: "); scanf("%s", sendline); //strcpy(sendline, "The server should display this text.\n\0"); //printf("\nLength of string: %d\n", strlen(sendline)); //printf("\t%s\n", sendline); write(sockfd, sendline, strlen(sendline)); fp = fopen("ReturnedPageClient.html", "w"); bzero(recvline, 655360); while(n = read(sockfd, recvline, sizeof(recvline)) &gt; 0) { //printf("%s", recvline); if(fp != NULL) { fprintf(fp, "%s", recvline); } else { printf("\tError saving file: client terminating.\n"); fclose(fp); return 0; } } fclose(fp); printf("\tResponse received from proxy server.\n\tFile saved as \"ReturnedPageClient.html\"\n"); close(sockfd); return 0; } </code></pre>
0debug
void tcp_start_incoming_migration(const char *host_port, Error **errp) { Error *err = NULL; SocketAddressLegacy *saddr = tcp_build_address(host_port, &err); if (!err) { socket_start_incoming_migration(saddr, &err); } error_propagate(errp, err); }
1threat
C# Linking Array Properties : I have a class (Winforms application) that monitors status of a group of real-life switches, and stores their open/closed status in two arrays. One array is the status in binary (0,1) format, and the other in string ("open", "closed") format. The UI uses the string format, and internal calcs use both formats, so I need both arrays. I keep banging my head trying to figure the best way to link those two arrays, so that if the app Sets one element of either array, the corresponding array element of the other gets set automatically at the same time, in the correct format. I've considered using some sort of Binding, but apparently Winforms won't do binding between properties, only WPF. I've also considered using the Set of each property to have logic to set the other's element (see below), but I can't figure how to configure the Set to access individual array elements (indexer maybe, though I'm not sure if that's the right path since I know nothing about them). Here's the code I have at the moment, and of course it doesn't work because it doesn't know how to equate the array with the int in the logic statement. Any help with a solution would be greatly appreciated. Thanks. public class SystemStatus { public string[] strStatus { get { return strStatus; } set { strStatus = value; binStatus = value == "closed" ? 1 : 0; } } public int[] binStatus { get { return binStatus; } set { binStatus = value; strStatus = value == 1 ? "closed" : "open"; } }
0debug
static int nvdec_mpeg12_decode_slice(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size) { NVDECContext *ctx = avctx->internal->hwaccel_priv_data; void *tmp; tmp = av_fast_realloc(ctx->slice_offsets, &ctx->slice_offsets_allocated, (ctx->nb_slices + 1) * sizeof(*ctx->slice_offsets)); if (!tmp) return AVERROR(ENOMEM); ctx->slice_offsets = tmp; if (!ctx->bitstream) ctx->bitstream = (uint8_t*)buffer; ctx->slice_offsets[ctx->nb_slices] = buffer - ctx->bitstream; ctx->bitstream_len += size; ctx->nb_slices++; return 0; }
1threat
Android how to get Current location lattitude and longitude in marshmallow and above version : 1)first I want to check internet connection is connected or not .if not connected then show dilog box for start internet connection. 2)Then I want to check gps is on or not if on then get latitude and longitude location . 3)And show the latitude and longitude in text or in Toast.
0debug
Dynamic classname inside ngClass in angular 2 : <p>I need to interpolate a value inside of an <code>ngClass</code> expression but I can't get it to work.</p> <p>I tried these solution which are the only ones that makes sense to me, these two fails with the interpolation:</p> <pre><code>&lt;button [ngClass]="{'{{namespace}}-mybutton': type === 'mybutton'}"&gt;&lt;/button&gt; &lt;button [ngClass]="{namespace + '-mybutton': type === 'mybutton'}"&gt;&lt;/button&gt; </code></pre> <p>This one works with the interpolation but fails with the dynamically added class because the entire string gets added as a class:</p> <pre><code>&lt;button ngClass="{'{{namespace}}-mybutton': type === 'mybutton'}"&gt;&lt;/button&gt; </code></pre> <p>So my question is how do you use dynamic classnames in <code>ngClass</code> like this?</p>
0debug
Difference between ! and % in Jupyter Notebooks : <p>Both <code>!</code> and <code>%</code> allow you to run shell commands from a Jupyter notebook.</p> <p><code>%</code> is provided <a href="http://ipython.readthedocs.io/en/stable/interactive/magics.html" rel="noreferrer">by the IPython kernel</a> and allows you to run "magic commands", many of which include well-known shell commands. <code>!</code>, provided by Jupyter, allows shell commands to be run within cells. </p> <p>I haven't been able to find <a href="https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/" rel="noreferrer">much</a> comparing the two, and for simple shell commands like <code>cd</code>, etc. the main difference I see is that <code>%</code> is interactive and will actually change your location in the shell <em>while in the notebook</em>. </p> <p>Are there other points or rules of contrast when thinking about which symbol to use for shell commands in a Jupyter Notebook?</p>
0debug
static inline void scale_mv(AVSContext *h, int *d_x, int *d_y, cavs_vector *src, int distp) { int den = h->scale_den[src->ref]; *d_x = (src->x * distp * den + 256 + (src->x >> 31)) >> 9; *d_y = (src->y * distp * den + 256 + (src->y >> 31)) >> 9; }
1threat
Kotlin - Void vs. Unit vs. Nothing : <p>Kotlin has three types that are very similar in nature:</p> <ul> <li><code>Void</code></li> <li><code>Unit</code></li> <li><code>Nothing</code></li> </ul> <p>It almost seems like they're making the JavaScript mistake:</p> <ul> <li><code>null</code></li> <li><code>undefined</code></li> <li><code>void(0)</code></li> </ul> <p>Assuming that they <em>haven't</em> fallen into the same mistake, what are they all for, and how do they differ?</p>
0debug