problem
stringlengths
26
131k
labels
class label
2 classes
static KVMSlot *kvm_alloc_slot(KVMState *s) { int i; for (i = 0; i < ARRAY_SIZE(s->slots); i++) { if (i >= 8 && i < 12) continue; if (s->slots[i].memory_size == 0) return &s->slots[i]; } fprintf(stderr, "%s: no free slot available\n", __func__); abort(); }
1threat
Double vs Float - Java : <p>Well I have following program. It is given by my teacher for fun. I got surprise about the result. </p> <p><strong>Code:</strong></p> <pre><code>public class Testing { public static void main(String[] args) { float piF = 3.141592653589793f; // value assigned has float precision double piD = 3.141592653589793; // value assigned has double precision final double THRESHOLD = .0001; if( piF == piD) System.out.println( "piF and piD are equal" ); else System.out.println( "piF and piD are not equal" ); if( Math.abs( piF - (float) piD ) &lt; THRESHOLD ) System.out.println( "piF and piD are considered equal" ); else System.out.println( "piF and piD are not equal" ); } } </code></pre> <p><strong>Result:</strong></p> <pre><code>piF and piD are not equal piF and piD are considered equal </code></pre> <p>Well why piF and piD are not equal ? And what actually <code>Math.abs()</code> do that makes both same ?</p>
0debug
static int vty_getchars(VIOsPAPRDevice *sdev, uint8_t *buf, int max) { VIOsPAPRVTYDevice *dev = VIO_SPAPR_VTY_DEVICE(sdev); int n = 0; while ((n < max) && (dev->out != dev->in)) { buf[n++] = dev->buf[dev->out++ % VTERM_BUFSIZE]; qemu_chr_fe_accept_input(&dev->chardev); return n;
1threat
React-router: Using <Link> as clickable data table row : <p>I'm new to using ReactJS and react-router. I want a clickable table row and something like the following setup:</p> <pre><code>&lt;Link to=“#”&gt; &lt;tr&gt; &lt;td&gt;{this.props.whatever1}&lt;/td&gt; &lt;td&gt;{this.props.whatever2}&lt;/td&gt; &lt;td&gt;{this.props.whatever3}&lt;/td&gt; &lt;/tr&gt; &lt;/Link&gt; </code></pre> <p>but I know you can't put <code>&lt;a&gt;</code> tags between the <code>&lt;tbody&gt;</code> and <code>&lt;tr&gt;</code> tags. How else can I accomplish this?</p> <p>PS: I prefer not to use jQuery if possible.</p>
0debug
How to bind MVC checkboxes to model : <p>I have a view which outputs a list of questions. The user will select questions they want included in a report and then submit the form.</p> <p>My view looks like:</p> <pre><code>@using (Html.BeginForm("Step6", "Home", FormMethod.Post)) { @Html.HiddenFor(m =&gt; m.EventID) @Html.HiddenFor(m =&gt; m.CompanyID) foreach (var item in Model.Questions) { &lt;div class="checkbox"&gt; &lt;input type="checkbox" id="@item.QuestionID" name="QuestionIds" value="@item.Title" /&gt; &lt;label for="@item.QuestionID"&gt;@item.Title&lt;/label&gt; &lt;/div&gt; } &lt;p&gt;&lt;input type="submit" class="btn btn-primary" value="Submit" /&gt;&lt;/p&gt; } </code></pre> <p>Generated HTML looks like:</p> <pre><code>&lt;div class="checkbox"&gt; &lt;input type="checkbox" id="12" name="QuestionIds" value="Would you like an account manager to contact you?" /&gt; &lt;label for="12"&gt;Would you like an account manager to contact you?&lt;/label&gt; &lt;/div&gt; &lt;div class="checkbox"&gt; &lt;input type="checkbox" id="13" name="QuestionIds" value="Comments - please be as detailed as possible." /&gt; &lt;label for="13"&gt;Comments - please be as detailed as possible.&lt;/label&gt; &lt;/div&gt; </code></pre> <p>Question collection:</p> <pre><code>public class Question { public Guid QuestionID { get; set; } public string Title { get; set; } } </code></pre> <p>Controller action</p> <pre><code> [HttpPost] public ActionResult Step6(Models.EventCompanyQuestionnaireQuestions model) { return View(); } </code></pre> <p>The model:</p> <pre><code>public class EventCompanyQuestionnaireQuestions { public int EventID { get; set; } public int CompanyID { get; set; } public List&lt;Guid&gt; QuestionIds { get; set; } } </code></pre> <p>When the form is submitted the List is an empty, initialized list. The rendered form element is named QuestionIds which matches the model. I need QuestionIds to have the checked checkboxes.</p>
0debug
What does \p{P} mean? : <p>So, I was messing around with regex to convert sentences into pig latin, and decided to extend the assignment to allow for punctuation. I was looking for a regex that allowed for me to replace the punctuation with an empty string and found <code>myString.replaceAll("\\p{P}", "");</code> and was curious as to what the \p and {P} actually do here. Other similar questions have used <code>"\\p{Z}"</code> to replace whitespace, which leads me to think the \p is searching for whatever is inside of the brackets. Anyways any clarifications or directions to documentation would be much appreciated.</p>
0debug
document.write('<script src="evil.js"></script>');
1threat
Why is my token being rejected? What is a resource ID? "Invalid token does not contain resource id (oauth2-resource)" : <p>I'm trying to configure OAuth2 for a spring project. I'm using a shared UAA (<a href="https://docs.cloudfoundry.org/api/uaa/version/4.8.0" rel="noreferrer">oauth implementation from cloud foundry</a>) instance my work place provides (so I'm not trying to create an authorization server and the authorization server is separate from the resource server). The frontend is a single-page-application and it gets token directly from the authorization server using the implicit grant. I have the SPA setup where it adds the <code>Authorization: Bearer &lt;TOKEN&gt;</code> header on each web API call to microservices.</p> <p>My issue is now with the microservices.</p> <p>I'm trying to use this shared authorization server to authenticate the microservices. I might have a misunderstanding here, buy my current understanding is that these microservices play the role of the resource server because they host the endpoints the SPA uses to get data.</p> <p>So I tried to configure a microservice like so:</p> <pre><code>@Configuration @EnableResourceServer public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/api/**").authenticated(); } @Bean public TokenStore tokenStore() { return new JwtTokenStore(accessTokenConverter()); } @Bean public JwtAccessTokenConverter accessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setVerifierKey("-----BEGIN PUBLIC KEY-----&lt;key omitted&gt;-----END PUBLIC KEY-----"); return converter; } @Bean @Primary public DefaultTokenServices tokenServices() { DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); defaultTokenServices.setTokenStore(tokenStore()); return defaultTokenServices; } @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.tokenServices(tokenServices()); } } </code></pre> <p>Now whenever I hit a <code>/api/**</code> with the <code>Authorization: Bearer &lt;TOKEN&gt;</code>, I get a <code>403</code> with this error:</p> <pre><code>{ "error": "access_denied", "error_description": "Invalid token does not contain resource id (oauth2-resource)" } </code></pre> <hr> <h2>So here are my questions:</h2> <ul> <li><strong>How do I configure these microservices to validate the token and insert a <a href="https://docs.oracle.com/javase/8/docs/api/java/security/Principal.html" rel="noreferrer"><code>Principal</code></a> in controller methods?</strong> I currently have it setup where the SPA has and sends the token and I also have the public key used to verify the signature of the token. I have also used <a href="https://jwt.io/" rel="noreferrer">jwt.io</a> to test the token and it says "Signature Verified".</li> <li>What is a resource id? Why do I need it and why does it cause the error above? Is that a Spring only thing??</li> </ul> <p>Thanks!</p>
0debug
How can I make an Array of shapes and put them into my scene? : <p>I've been working on my personal JavaFX project and with it learning JavaFX, I wanted to know if there is a way I could make an array of Rectangles and add them to my scene?</p>
0debug
PHP Login System. Do not receive any values of the HTML : <p>I'm new to php and I'm trying to write a simple signup sytem. Now I have some issues. I've tried to debbug my code, but I've no clue what I did wrong.</p> <p>Problem: I didn't receive the values from the HTML input in PHP. When I do a @echo to the variables, I don't receive any input.</p> <p>HTML Code of the elemenets</p> <pre><code>&lt;input name="uid" type="text" placeholder="What's your username?" autofocus="autofocus" required="required" class="input pass"/&gt; &lt;input name="pwd" type="password" placeholder="Choose a password" required="required" class="input pass"/&gt; &lt;input name="pwd2" type="password" placeholder="Confirm password" required="required" class="input pass"/&gt; &lt;input name="email" type="text" placeholder="Email address" required="required" class="input pass"/&gt; &lt;input type="submit" name="submit" value="Sign me up!" class="inputButton" &gt; </code></pre> <p>Db Connection code, where I declared the $conn variable</p> <pre><code>&lt;?php $dbServername ="localhost"; $dbUsername ="root"; $dbPassword =""; $dbName ="test"; $conn = (mysqli_connect($dbServername,$dbUsername,$dbPassword,$dbName)); </code></pre> <p>PHP Code wher I'm trying to show the values of the html input</p> <pre><code>if(isset($_POST['submit'])) { include_once 'dbc.php'; $uid = $conn-&gt;escape_string($_POST['uid']); $pwd = $conn-&gt;escape_string($_POST['pwd']); $pwd2 = $conn-&gt;escape_string($_POST['pwd2']); $email = $conn-&gt;escape_string($_POST['email']); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } else{ if(empty($uid) || empty($pwd) || empty($pwd2) || empty($email)) { echo $uid, $pwd, $pwd2, $email; } else{} } </code></pre>
0debug
How to send a date values to a another class constructor through object and how to get that date values back? : How to send a date values to another class constructor through an object and how to get that date values back?
0debug
static int process_audio_header_eacs(AVFormatContext *s) { EaDemuxContext *ea = s->priv_data; AVIOContext *pb = s->pb; int compression_type; ea->sample_rate = ea->big_endian ? avio_rb32(pb) : avio_rl32(pb); ea->bytes = avio_r8(pb); ea->num_channels = avio_r8(pb); compression_type = avio_r8(pb); avio_skip(pb, 13); switch (compression_type) { case 0: switch (ea->bytes) { case 1: ea->audio_codec = CODEC_ID_PCM_S8; break; case 2: ea->audio_codec = CODEC_ID_PCM_S16LE; break; break; case 1: ea->audio_codec = CODEC_ID_PCM_MULAW; ea->bytes = 1; break; case 2: ea->audio_codec = CODEC_ID_ADPCM_IMA_EA_EACS; break; default: av_log (s, AV_LOG_ERROR, "unsupported stream type; audio compression_type=%i\n", compression_type); return 1;
1threat
static CharDriverState *qemu_chr_open_win_path(const char *filename, Error **errp) { CharDriverState *chr; WinCharState *s; chr = qemu_chr_alloc(); s = g_new0(WinCharState, 1); chr->opaque = s; chr->chr_write = win_chr_write; chr->chr_close = win_chr_close; if (win_chr_init(chr, filename, errp) < 0) { g_free(s); g_free(chr); return NULL; } return chr; }
1threat
I've installed pytorch, but cuda is not recognized : I installed pytorch using this command pip3 install torch===1.2.0 torchvision===0.4.0 -f https://download.pytorch.org/whl/torch_stable.html and it seemed to work. When importing torch, there is no error. My laptop has a geforce 1060 ti, which I assumed would work with cuda. [Here is the error in the ide (eclipse)][1] [1]: https://i.stack.imgur.com/ey7wU.png
0debug
Set ImageView from Real path : I have the real path of an image which I am retrieving from my Database. I want to set the imageView using the real path (/storage/emulated/0/DCIM/100MEDIA/image.jpg) How can this be done. public void getIMG(){ Cursor res = myDb.GetRow(id); if(res.moveToFirst()){ String path = res.getString(DatabaseHelper.ROWIMG); /*img.set'???'*/ } }
0debug
static int check_refcounts_l2(BlockDriverState *bs, uint16_t *refcount_table, int refcount_table_size, int64_t l2_offset, int check_copied) { BDRVQcowState *s = bs->opaque; uint64_t *l2_table, offset; int i, l2_size, nb_csectors, refcount; int errors = 0; l2_size = s->l2_size * sizeof(uint64_t); l2_table = qemu_malloc(l2_size); if (bdrv_pread(bs->file, l2_offset, l2_table, l2_size) != l2_size) goto fail; for(i = 0; i < s->l2_size; i++) { offset = be64_to_cpu(l2_table[i]); if (offset != 0) { if (offset & QCOW_OFLAG_COMPRESSED) { if (offset & QCOW_OFLAG_COPIED) { fprintf(stderr, "ERROR: cluster %" PRId64 ": " "copied flag must never be set for compressed " "clusters\n", offset >> s->cluster_bits); offset &= ~QCOW_OFLAG_COPIED; errors++; } nb_csectors = ((offset >> s->csize_shift) & s->csize_mask) + 1; offset &= s->cluster_offset_mask; errors += inc_refcounts(bs, refcount_table, refcount_table_size, offset & ~511, nb_csectors * 512); } else { if (check_copied) { uint64_t entry = offset; offset &= ~QCOW_OFLAG_COPIED; refcount = get_refcount(bs, offset >> s->cluster_bits); if (refcount < 0) { fprintf(stderr, "Can't get refcount for offset %" PRIx64 ": %s\n", entry, strerror(-refcount)); } if ((refcount == 1) != ((entry & QCOW_OFLAG_COPIED) != 0)) { fprintf(stderr, "ERROR OFLAG_COPIED: offset=%" PRIx64 " refcount=%d\n", entry, refcount); errors++; } } offset &= ~QCOW_OFLAG_COPIED; errors += inc_refcounts(bs, refcount_table, refcount_table_size, offset, s->cluster_size); if (offset & (s->cluster_size - 1)) { fprintf(stderr, "ERROR offset=%" PRIx64 ": Cluster is not " "properly aligned; L2 entry corrupted.\n", offset); errors++; } } } } qemu_free(l2_table); return errors; fail: fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n"); qemu_free(l2_table); return -EIO; }
1threat
static void pc_numa_cpu(const void *data) { char *cli; QDict *resp; QList *cpus; const QObject *e; cli = make_cli(data, "-cpu pentium -smp 8,sockets=2,cores=2,threads=2 " "-numa node,nodeid=0 -numa node,nodeid=1 " "-numa cpu,node-id=1,socket-id=0 " "-numa cpu,node-id=0,socket-id=1,core-id=0 " "-numa cpu,node-id=0,socket-id=1,core-id=1,thread-id=0 " "-numa cpu,node-id=1,socket-id=1,core-id=1,thread-id=1"); qtest_start(cli); cpus = get_cpus(&resp); g_assert(cpus); while ((e = qlist_pop(cpus))) { QDict *cpu, *props; int64_t socket, core, thread, node; cpu = qobject_to_qdict(e); g_assert(qdict_haskey(cpu, "props")); props = qdict_get_qdict(cpu, "props"); g_assert(qdict_haskey(props, "node-id")); node = qdict_get_int(props, "node-id"); g_assert(qdict_haskey(props, "socket-id")); socket = qdict_get_int(props, "socket-id"); g_assert(qdict_haskey(props, "core-id")); core = qdict_get_int(props, "core-id"); g_assert(qdict_haskey(props, "thread-id")); thread = qdict_get_int(props, "thread-id"); if (socket == 0) { g_assert_cmpint(node, ==, 1); } else if (socket == 1 && core == 0) { g_assert_cmpint(node, ==, 0); } else if (socket == 1 && core == 1 && thread == 0) { g_assert_cmpint(node, ==, 0); } else if (socket == 1 && core == 1 && thread == 1) { g_assert_cmpint(node, ==, 1); } else { g_assert(false); } } QDECREF(resp); qtest_end(); g_free(cli); }
1threat
static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; NuvContext *c = avctx->priv_data; AVFrame *picture = data; int orig_size = buf_size; int keyframe; int result; enum {NUV_UNCOMPRESSED = '0', NUV_RTJPEG = '1', NUV_RTJPEG_IN_LZO = '2', NUV_LZO = '3', NUV_BLACK = 'N', NUV_COPY_LAST = 'L'} comptype; if (buf_size < 12) { av_log(avctx, AV_LOG_ERROR, "coded frame too small\n"); return -1; } if (buf[0] == 'D' && buf[1] == 'R') { int ret; buf = &buf[12]; buf_size -= 12; ret = get_quant(avctx, c, buf, buf_size); if (ret < 0) return ret; ff_rtjpeg_decode_init(&c->rtj, &c->dsp, c->width, c->height, c->lq, c->cq); return orig_size; } if (buf[0] != 'V' || buf_size < 12) { av_log(avctx, AV_LOG_ERROR, "not a nuv video frame\n"); return -1; } comptype = buf[1]; switch (comptype) { case NUV_RTJPEG_IN_LZO: case NUV_RTJPEG: keyframe = !buf[2]; break; case NUV_COPY_LAST: keyframe = 0; break; default: keyframe = 1; break; } buf = &buf[12]; buf_size -= 12; if (comptype == NUV_RTJPEG_IN_LZO || comptype == NUV_LZO) { int outlen = c->decomp_size, inlen = buf_size; if (av_lzo1x_decode(c->decomp_buf, &outlen, buf, &inlen)) av_log(avctx, AV_LOG_ERROR, "error during lzo decompression\n"); buf = c->decomp_buf; buf_size = c->decomp_size; } if (c->codec_frameheader) { int w, h, q; if (buf_size < 12) { av_log(avctx, AV_LOG_ERROR, "invalid nuv video frame\n"); return -1; } w = AV_RL16(&buf[6]); h = AV_RL16(&buf[8]); q = buf[10]; if (!codec_reinit(avctx, w, h, q)) return -1; buf = &buf[12]; buf_size -= 12; } if (keyframe && c->pic.data[0]) avctx->release_buffer(avctx, &c->pic); c->pic.reference = 3; c->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_READABLE | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE; result = avctx->reget_buffer(avctx, &c->pic); if (result < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return -1; } c->pic.pict_type = keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P; c->pic.key_frame = keyframe; switch (comptype) { case NUV_LZO: case NUV_UNCOMPRESSED: { int height = c->height; if (buf_size < c->width * height * 3 / 2) { av_log(avctx, AV_LOG_ERROR, "uncompressed frame too short\n"); height = buf_size / c->width / 3 * 2; } copy_frame(&c->pic, buf, c->width, height); break; } case NUV_RTJPEG_IN_LZO: case NUV_RTJPEG: { ff_rtjpeg_decode_frame_yuv420(&c->rtj, &c->pic, buf, buf_size); break; } case NUV_BLACK: { memset(c->pic.data[0], 0, c->width * c->height); memset(c->pic.data[1], 128, c->width * c->height / 4); memset(c->pic.data[2], 128, c->width * c->height / 4); break; } case NUV_COPY_LAST: { break; } default: av_log(avctx, AV_LOG_ERROR, "unknown compression\n"); return -1; } *picture = c->pic; *data_size = sizeof(AVFrame); return orig_size; }
1threat
difference between android.support.v7.app.AlertController.RecycleListView and android.support.v7.widget.RecyclerView : <p>I recently update my Android Studio and also SDK. In new Android Studio, there is <code>android.support.v7.app.AlertController.RecycleListView</code>. I am familiar with <code>android.support.v7.RecyclerView</code>, so I am a little bit confused that what is the difference between these two. If anyone can guide then it would be thankful. </p>
0debug
static void vc1_loop_filter_iblk(MpegEncContext *s, int pq) { int i, j; if(!s->first_slice_line) s->dsp.vc1_loop_filter(s->dest[0], 1, s->linesize, 16, pq); s->dsp.vc1_loop_filter(s->dest[0] + 8*s->linesize, 1, s->linesize, 16, pq); for(i = !s->mb_x*8; i < 16; i += 8) s->dsp.vc1_loop_filter(s->dest[0] + i, s->linesize, 1, 16, pq); for(j = 0; j < 2; j++){ if(!s->first_slice_line) s->dsp.vc1_loop_filter(s->dest[j+1], 1, s->uvlinesize, 8, pq); if(s->mb_x) s->dsp.vc1_loop_filter(s->dest[j+1], s->uvlinesize, 1, 8, pq); } }
1threat
static int read_matrix_params(MLPDecodeContext *m, unsigned int substr, GetBitContext *gbp) { SubStream *s = &m->substream[substr]; unsigned int mat, ch; const int max_primitive_matrices = m->avctx->codec_id == AV_CODEC_ID_MLP ? MAX_MATRICES_MLP : MAX_MATRICES_TRUEHD; if (m->matrix_changed++ > 1) { av_log(m->avctx, AV_LOG_ERROR, "Matrices may change only once per access unit.\n"); return AVERROR_INVALIDDATA; } s->num_primitive_matrices = get_bits(gbp, 4); if (s->num_primitive_matrices > max_primitive_matrices) { av_log(m->avctx, AV_LOG_ERROR, "Number of primitive matrices cannot be greater than %d.\n", max_primitive_matrices); return AVERROR_INVALIDDATA; } for (mat = 0; mat < s->num_primitive_matrices; mat++) { int frac_bits, max_chan; s->matrix_out_ch[mat] = get_bits(gbp, 4); frac_bits = get_bits(gbp, 4); s->lsb_bypass [mat] = get_bits1(gbp); if (s->matrix_out_ch[mat] > s->max_matrix_channel) { av_log(m->avctx, AV_LOG_ERROR, "Invalid channel %d specified as output from matrix.\n", s->matrix_out_ch[mat]); return AVERROR_INVALIDDATA; } if (frac_bits > 14) { av_log(m->avctx, AV_LOG_ERROR, "Too many fractional bits specified.\n"); return AVERROR_INVALIDDATA; } max_chan = s->max_matrix_channel; if (!s->noise_type) max_chan+=2; for (ch = 0; ch <= max_chan; ch++) { int coeff_val = 0; if (get_bits1(gbp)) coeff_val = get_sbits(gbp, frac_bits + 2); s->matrix_coeff[mat][ch] = coeff_val * (1 << (14 - frac_bits)); } if (s->noise_type) s->matrix_noise_shift[mat] = get_bits(gbp, 4); else s->matrix_noise_shift[mat] = 0; } return 0; }
1threat
Stuck at ".android/repositories.cfg could not be loaded." : <pre><code> brew cask install android-sdk </code></pre> <blockquote> <p>==> Caveats We will install android-sdk-tools, platform-tools, and build-tools for you. You can control android sdk packages via the sdkmanager command. You may want to add to your profile: 'export ANDROID_HOME=/usr/local/share/android-sdk'</p> <p>This operation may take up to 10 minutes depending on your internet connection. Please, be patient.</p> <p>==> Downloading <a href="https://dl.google.com/android/repository/tools_r25.2.3-macosx.zip" rel="noreferrer">https://dl.google.com/android/repository/tools_r25.2.3-macosx.zip</a> Already downloaded: /Users/ishandutta2007/Library/Caches/Homebrew/Cask/android-sdk--25.2.3.zip ==> Verifying checksum for Cask android-sdk ==> Warning: File /Users/ishandutta2007/.android/repositories.cfg could not be loaded.</p> </blockquote>
0debug
Save an array of strings to a string : <p>I have access to one string variable named Storage. I would like to save an array of strings to the Storage variable along with other variables. Is this possible to save an array variable to a string? If it is how do i get the values out of the array? See code I have below.</p> <pre><code>// This Storage variable is just for code functionality. I do not create it. string Storage; // See above^ string Apple = "Red"; string Bannana = "Yellow"; Queue&lt;string&gt; myQ = new Queue&lt;string&gt;(); myQ.Enqueue("zero"); myQ.Enqueue("one"); myQ.Enqueue("two"); myQ.Enqueue("three"); string[] myQ_Array = myQ.ToArray(); Storage = Apple + ";" + Bannana + ";" + myQ_Array[0] + ";" + myQ_Array; var mySplitStorage = Storage.Split(';'); Console.WriteLine("mySplitStorage[0] = " + mySplitStorage[0]); Console.WriteLine("mySplitStorage[1] = " + mySplitStorage[1]); Console.WriteLine("mySplitStorage[2] = " + mySplitStorage[2]);//&lt;--This works Console.WriteLine("mySplitStorage[3] = " + mySplitStorage[3]);//&lt;--Cant get this to work Console.Read(); // This is the output //mySplitStorage[0] = Red //mySplitStorage[1] = Yellow //mySplitStorage[2] = zero //mySplitStorage[3] = System.String[] &lt;--- How do i get the values out of the array? </code></pre>
0debug
Can someone help me figure out why my mini-max tic-tac-toe AI does not work? : This is me trying to make a minimax tic-tac-toe game. The AI for some reason still goes in order in which the spot turns up on the list for the board. It looks like it is calculating the scores, but I do not think it is utilizing them for some reason. It is supposed to pick the spot with the highest score. It outputs many "You win", "TIE", and "You lose" strings because I wanted to make sure it was iterating through the spaces and combinations. Please help! ```` import random import math three = [0, 0, 0] game = True turnai = False result = "" b = [" ", " ", " ", " ", " ", " ", " ", " ", " "] x = "X" o = "O" ur = b[2] um = b[1] ul = b[0] ml = b[3] mm = b[4] mr = b[5] ll = b[6] lm = b[7] lr = b[8] cw = " " AI = "" player = "" def board(ul, um, ur, ml, mm, mr, ll, lm, lr): print("|" + " " + ul + " " + "|" + " " + um + " " + "|" + " " + ur + " " + "|") print("|" + " " + ml + " " + "|" + " " + mm + " " + "|" + " " + mr + " " + "|") print("|" + " " + ll + " " + "|" + " " + lm + " " + "|" + " " + lr + " " + "|") board(ul, um, ur, ml, mm, mr, ll, lm, lr) print("This is the game of tic-tac-toe") print("You will be playing against an AI") print("Type where you want to place your letter Ex: ur = upper right, mm = middle middle, and ll = lower right") first = "P" player = "X" AI = "O" def checkwinner(): ur = b[2] um = b[1] ul = b[0] ml = b[3] mm = b[4] mr = b[5] ll = b[6] lm = b[7] lr = b[8] row1 = [ul, ml, ll] row2 = [um, mm, lm] row3 = [ur, mr, lr] column1 = [ul, um, ur] column2 = [ml, mm, mr] column3 = [ll, lm, lr] diagonal1 = [ul, mm, lr] diagonal2 = [ur, mm, ll] if row1 == ["X", "X", "X"] or row2 == ["X", "X", "X"] or row3 == ["X", "X", "X"] or column1 == ["X", "X", "X"] or column2 == [ "X", "X", "X"] or column3 == ["X", "X", "X"] or diagonal1 == ["X", "X", "X"] or diagonal2 == ["X", "X", "X"]: if player == x: print("You win! (X)") return "X" if player != x: print("You lose!") return "O" if row1 == ["O", "O", "O"] or row2 == ["O", "O", "O"] or row3 == ["O", "O", "O"] or column1 == ["O", "O", "O"] or column2 == [ "O", "O", "O"] or column3 == ["O", "O", "O"] or diagonal1 == ["O", "O", "O"] or diagonal2 == ["O", "O", "O"]: if player == o: print("You win! (O)") return "X" if player != o: print("You lose") return "O" if b[0] != " " and b[1] != " " and b[2] != " " and b[3] != " " and b[4] != " " and b[5] != " " and b[ 6] != " " and b[7] != " " and b[8] != " ": print("TIE!") winner = True return "0" return "null" def minimax(b, depth, isMaximizing): result = checkwinner() if result != "null": return scores[result] if (isMaximizing): bestScore = -math.inf j = 0 for str in b: if str == " ": b[j] = AI score = minimax(b, depth + 1, False) b[j] = " " bestScore = max(score, bestScore) j += 1 return bestScore else: bestScore = math.inf k = 0 for str in b: if str == " ": b[k] = player score = minimax(b, depth + 1, True) b[k] = " " bestScore = min(score, bestScore) k += 1 return bestScore if (first == "P"): while (game == True): i = 0 scores = { 'O': 1, 'X': -1, '0': 0 } bestScore = -math.inf turnai = False i = 0 for str in b: if str == " ": b[i] = AI score = minimax(b, 0, True) b[i] = " " print(score) if score > bestScore and turnai == False: bestScore = score b[i] = AI turnai = True i += 1 turnai = False print("") # b = [ul, um, ur, ml, mm, mr, ll, lm, lr] ur = b[2] um = b[1] ul = b[0] ml = b[3] mm = b[4] mr = b[5] ll = b[6] lm = b[7] lr = b[8] board(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8]) cw = checkwinner() if cw == "X" or cw == "O" or cw == "0": game = False break print("Where do you want to place your letter?") turn = input(": ") if turn == "ur" and ur == " ": b[2] = player uru = True if turn == "um" and um == " ": b[1] = player umu = True if turn == "ul" and ul == " ": b[0] = player ulu = True if turn == "mr" and mr == " ": b[5] = player mru = True if turn == "mm" and mm == " ": b[4] = player mmu = True if turn == "ml" and ml == " ": b[3] = player mlu = True if turn == "lr" and lr == " ": b[8] = player lru = True if turn == "lm" and lm == " ": b[7] = player lmu = True if turn == "ll" and ll == " ": b[6] = player llu = True # b = [ul, um, ur, ml, mm, mr, ll, lm, lr] board(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8]) sw = checkwinner() if cw == "X" or cw == "O" or cw == "0": game = False break # MAKE SURE TO MOVE WHERE THE TIE MECH IS WHEN MAKING OTHER TURN SYSTEM AND SCORE LOOK UP TABLE ````
0debug
Angular2 and TypeScript: error TS2322: Type 'Response' is not assignable to type 'UserStatus' : <p>I'm playing with Angular2 and TypeScript and it's not going well (this would be so easy in AngularJS). I'm writing a little experiment app to get to grips with it all and I have the following component as my main / top level component...</p> <pre><code>import {Component, OnInit} from 'angular2/core'; import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router'; import {UserData} from './services/user-data/UserData'; import {Home} from './components/home/home'; import {UserStatus} from './types/types.ts'; import {Http, Headers, Response} from 'angular2/http'; @Component({ selector: 'app', // &lt;app&gt;&lt;/app&gt; providers: [...FORM_PROVIDERS], directives: [...ROUTER_DIRECTIVES], template: require('./app.html') }) @RouteConfig([ {path: '/', component: Home, name: 'Home'}, // more routes here.... ]) export class App { userStatus: UserStatus; constructor(public http: Http) { } ngOnInit() { // I want to obtain a user Profile as soon as the code is initialised var headers = new Headers(); headers.append('Content-Type', 'application/json'); this.http.get('/restservice/userstatus', {headers: headers}) .subscribe( (data: Response) =&gt; { data = JSON.parse(data['_body']); this.userStatus = data; }, err =&gt; console.log(err), // error () =&gt; console.log('getUserStatus Complete') // complete ); } } </code></pre> <p>Now when the top level component is bootstrapped / initialised I want to make a call to a phoney REST service (/restservice/userstatus) I set up that returns an object that I have made into a type like so (this is from <code>import {UserStatus} from './types/types.ts'</code>):</p> <pre><code>export class UserStatus { constructor ( public appOS?: any , // can be null public firstName: string, public formerName?: any, // can be null public fullPersId: number, public goldUser: boolean, public hasProfileImage: boolean, public hideMoblieNavigationAndFooter: boolean, public persId: string, public profileName: string, public profilePicture: string, public showAds: boolean, public siteId: number, public url: string, public verified: boolean ) { } } </code></pre> <p>Now the <code>appOS</code> and <code>formerName</code> properties could potentially be <code>null</code> and when serving up the response in my REST service they are, the JSON object looks like so:</p> <pre><code>{ appOS: null, firstName: "Max", formerName: null, fullPersId: 123456789, goldUser: true, hasProfileImage: true, hideMoblieNavigationAndFooter: false, persId: "4RUDIETMD", profileName: "Max Dietmountaindew", profilePicture: "http://myurl.com/images/maxdietmountaindew.jpg", showAds: true, siteId: 1, url: "/profile/maxdietmountaindew", verified: true } </code></pre> <p>So the data structure sent from my phoney service and the Type Object match however when I try to assign the data from the Rest Service to component in the class <code>'this.userStatus = data;'</code> I get the following error.... </p> <pre><code>"error TS2322: Type 'Response' is not assignable to type 'UserStatus'. Property 'appOS' is missing in type 'Response'." </code></pre> <p>I assume in my Type class I am doing something wrong with the definition where nulls are concerned can anyone see what I am doing wrong or explain why I am getting the error. Thanks in advance.</p>
0debug
How to Convert given text into the required date format in SqlServer : <p>I have an old database with a <a href="https://i.stack.imgur.com/bOLl4.png" rel="nofollow noreferrer">table with dateEntered(varchar datatype) column </a> which can take the dates in various formats like <br/> A> 'wk231216' which means (Week)23-(Date)12-(Year)2016<br/> B> '231216' which means (Week)23-(Date)12-(Year)2016<br/> C> 'wk132717' which means (week)13-(Date)27-(year)2017<br/><br/> Now I need to modify the above dates into this format as 'YYYY-MM-DD'<br/><br/> A> should become 2016-06-12(wk23 of 2016 is in June(06))<br/> B> should become 2016-06-12<br/> C> should become 2017-03-27<br/></p> <p>Can anyone suggest how to achieve this? Thank You!!</p>
0debug
static int qcow2_cache_entry_flush(BlockDriverState *bs, Qcow2Cache *c, int i) { BDRVQcowState *s = bs->opaque; int ret = 0; if (!c->entries[i].dirty || !c->entries[i].offset) { return 0; } trace_qcow2_cache_entry_flush(qemu_coroutine_self(), c == s->l2_table_cache, i); if (c->depends) { ret = qcow2_cache_flush_dependency(bs, c); } else if (c->depends_on_flush) { ret = bdrv_flush(bs->file); if (ret >= 0) { c->depends_on_flush = false; } } if (ret < 0) { return ret; } if (c == s->refcount_block_cache) { ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT & ~QCOW2_OL_REFCOUNT_BLOCK, c->entries[i].offset, s->cluster_size); } else if (c == s->l2_table_cache) { ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT & ~QCOW2_OL_ACTIVE_L2, c->entries[i].offset, s->cluster_size); } else { ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT, c->entries[i].offset, s->cluster_size); } if (ret < 0) { return ret; } if (c == s->refcount_block_cache) { BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_UPDATE_PART); } else if (c == s->l2_table_cache) { BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE); } ret = bdrv_pwrite(bs->file, c->entries[i].offset, c->entries[i].table, s->cluster_size); if (ret < 0) { return ret; } c->entries[i].dirty = false; return 0; }
1threat
How to check if a number is bigger than another number, by a certain amount? : <p>how would I go about producing the following if statement?</p> <pre><code>var a = 50; var b = 10; if(a &gt; b by 20){ console.log("a is too big"); } </code></pre>
0debug
GCS - Read a text file from Google Cloud Storage directly into python : <p>I feel kind of stupid right now. I have been reading numerous documentations and stackoverflow questions but I can't get it right.</p> <p>I have a file on Google Cloud Storage. It is in a bucket 'test_bucket'. Inside this bucket there is a folder, 'temp_files_folder', which contains two files, one .txt file named 'test.txt' and one .csv file named 'test.csv'. The two files are simply because I try using both but the result is the same either way.</p> <p>The content in the files is</p> <pre><code>hej san </code></pre> <p>and I am hoping to read it into python the same way I would do on a local with </p> <pre><code>textfile = open("/file_path/test.txt", 'r') times = textfile.read().splitlines() textfile.close() print(times) </code></pre> <p>which gives</p> <pre><code>['hej', 'san'] </code></pre> <p>I have tried using </p> <pre><code>from google.cloud import storage client = storage.Client() bucket = client.get_bucket('test_bucket') blob = bucket.get_blob('temp_files_folder/test.txt') print(blob.download_as_string) </code></pre> <p>but it gives the output</p> <pre><code>&lt;bound method Blob.download_as_string of &lt;Blob: test_bucket, temp_files_folder/test.txt&gt;&gt; </code></pre> <p>How can I get the actual string(s) in the file?</p>
0debug
How to save cookies and load it in another puppeteer session? : <p>I had to request the same webpage twice to get the cookies in the 1st request and use it in the 2nd request in the following example.</p> <p>Could anybody show me the code to save the cookies in one puppeteer session and load it in another session so that there is no need to request the same webpage twice in the 2nd session? Thanks.</p> <pre><code>const puppeteer = require('puppeteer'); (async () =&gt; { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.genecards.org/cgi-bin/carddisp.pl?gene=BSCL2'); await page.goto('https://www.genecards.org/cgi-bin/carddisp.pl?gene=BSCL2'); const linkHandlers = await page.$x("//div[@id='enhancers']//a[@data-track-event='Table See-All']"); if (linkHandlers.length &gt; 0) { const [response] = await Promise.all([ page.waitForResponse(response =&gt; response.url().includes('/gene/api/data/Enhancers')), linkHandlers[0].click() ]); const resp_text = await response.text(); console.log(resp_text); } else { throw new Error("Link not found"); } await browser.close(); })(); </code></pre>
0debug
Program to find whether an edge exists between two given vertices of a graph : I wrote the following code in C to find whether there exists an edge between two given vertices of a graph.Initially I ask user for inputs and then check whether there is a edge between two vertices using a BFS approach(queue). This code is working fine for some testcases but throwing a segmentation fault in few. please tell me where Iam going wrong #include <stdio.h> #include <stdlib.h> int main() { int v,e,e1,e2,t1,t2; printf("Enter num of vertices and edges: "); scanf("%d %d",&v,&e); int maze[v][v]; for(int i=0;i<v;i++) for(int j=0;j<v;j++) maze[i][j]=0; printf("Enter edges:\n") for(int i=0;i<e;i++) { scanf("%d %d",&e1,&e2); maze[e1-1][e2-1]=1; maze[e2-1][e1-1]=1; } printf("The maze looks like:\n"); for(int i=0;i<v;i++) { for(int j=0;j<v;j++) { printf("%d ",maze[i][j]); } printf("\n"); } printf("enter target edges: "); scanf("%d %d",&t1,&t2); //BFS starts from here. int queue[v*v]; int k = 1; queue[0] = t1-1; for(int i=0;i<v;i++) if(maze[t1-1][i]==1) { queue[k] = i; k++; } int bp,ep; bp = 0; ep = k; while(bp<=ep) { if(queue[bp]+1==t2) { printf("\nroute exists\n"); exit(0); } else { for(int i=0;i<v;i++) if(maze[queue[bp+1]][i]==1) { queue[k] = i; k++; } } bp=bp+1; ep=k; } printf("\nroute does'nt exist\n"); } Testcases for which this code is working: Testcase-1: 4 2 1 2 3 2 1 3 Testcase-2: 4 2 1 2 3 2 1 4 TestCase-3: 7 6 0 1 0 2 1 3 1 4 1 6 5 6 1 6 Testcases for which Iam getting a segmentation fault: TestCase-4: 7 6 0 1 0 2 1 3 1 4 1 6 5 6 0 6 TestCase-5: 7 6 0 1 0 2 1 3 1 4 1 6 5 6 2 4
0debug
Firebase Realtime Database, what is a read exactly? : <p>I am aware for Cloud Firestore a read is a document (whether the documents has 5 or 50 nodes). How does this compare to the RTDB? </p> <p>If I have a query that has a limit of 25, is this going to be 25 reads, or 25 times x amount of items in each node?</p> <p>Cheers.</p>
0debug
Tensorflow: Writing an Op in Python : <p>I would like to write an Op in Python. This tutorial only explains how to do it in c++ with a Python wrapper. <a href="https://www.tensorflow.org/versions/master/how_tos/adding_an_op/index.html#adding-a-new-op" rel="noreferrer">https://www.tensorflow.org/versions/master/how_tos/adding_an_op/index.html#adding-a-new-op</a></p> <p>How can I write it completely in Python?</p>
0debug
Maths function bug in NodeJS : I recently used the Math function in NodeJS for an API. When I try Math.log(114) for example the output is 4.7361 instead of 2.0569. /!\ I don't use any external library /!\
0debug
How to make custom validation for all datatype in c# using extension methods : <p>hi i am want to make custom conman validation using c# extension method for all datatype please give me some idea about it and some examples?</p> <p>Thanks</p>
0debug
Flutter - SingleChildScrollView interfering in columns : <p>I created a screen that works well with the columns, but I needed to scroll because of the keyboard.</p> <p>When you insert the <code>SingleChildScrollView</code> or the <code>ListView</code> attribute the <code>MainAxisAlignment.spaceBetween</code>, it no longer works.</p> <p>Was there any solution for that?</p> <p>Gif without the <code>SingleChildScrollView</code> the screen does not roll and the <code>FloatingActionButton</code> is at the bottom of the screen</p> <p><a href="https://i.stack.imgur.com/tHMRt.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/tHMRt.gif" alt="enter image description here"></a></p> <p>Gif with <code>SingleChildScrollView</code> the screen roll and he <code>FloatingActionButton</code> is not in bottom of the screen</p> <p><a href="https://i.stack.imgur.com/14T2I.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/14T2I.gif" alt="enter image description here"></a></p> <pre><code>import 'package:flutter/material.dart'; void main() { runApp(new MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( home: new MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() =&gt; new _MyHomePageState(); } class _MyHomePageState extends State&lt;MyHomePage&gt; { @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar(backgroundColor: new Color(0xFF26C6DA)), body: new SingleChildScrollView( child: new Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: &lt;Widget&gt;[ new Container( child: new Column( children: &lt;Widget&gt;[ new TextField( decoration: const InputDecoration( labelText: "Description", ), style: Theme.of(context).textTheme.title, ), new TextField( decoration: const InputDecoration( labelText: "Description", ), style: Theme.of(context).textTheme.title, ), new TextField( decoration: const InputDecoration( labelText: "Description", ), style: Theme.of(context).textTheme.title, ), ], ) ), new Container( margin: new EdgeInsets.only(bottom: 16.0), child: new FloatingActionButton( backgroundColor: new Color(0xFFE57373), child: new Icon(Icons.check), onPressed: (){} ), ) ], ), ) ); } } </code></pre>
0debug
void init_checksum(ByteIOContext *s, unsigned long (*update_checksum)(unsigned long c, const uint8_t *p, unsigned int len), unsigned long checksum){ s->update_checksum= update_checksum; s->checksum= s->update_checksum(checksum, NULL, 0); s->checksum_ptr= s->buf_ptr; }
1threat
Keep names of subfolders in a list : <p>In this a variable there is a folder called <code>main_folder</code>. This folder has two folders:</p> <p><code>111</code>,<code>222</code></p> <p>I need to get the names of these folders in a list.</p> <p>Tried this:</p> <pre><code>a = r'C:\Users\user\Desktop\main_folder' import os for root, dirs, files in os.walk(a): print(dirs) </code></pre> <p>gives:</p> <pre><code>['111', '222'] # &lt;--------------This only needed [] [] </code></pre> <p>How to keep only the first list and not the empty ones which I think describe the contents of these folders since they don't have folders.</p>
0debug
static int raw_reopen_prepare(BDRVReopenState *state, BlockReopenQueue *queue, Error **errp) { BDRVRawState *s; BDRVRawReopenState *raw_s; int ret = 0; Error *local_err = NULL; assert(state != NULL); assert(state->bs != NULL); s = state->bs->opaque; state->opaque = g_malloc0(sizeof(BDRVRawReopenState)); raw_s = state->opaque; #ifdef CONFIG_LINUX_AIO raw_s->use_aio = s->use_aio; if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) { error_setg(errp, "Could not set AIO state"); return -1; } #endif if (s->type == FTYPE_FD || s->type == FTYPE_CD) { raw_s->open_flags |= O_NONBLOCK; } raw_parse_flags(state->flags, &raw_s->open_flags); raw_s->fd = -1; int fcntl_flags = O_APPEND | O_NONBLOCK; #ifdef O_NOATIME fcntl_flags |= O_NOATIME; #endif #ifdef O_ASYNC assert((s->open_flags & O_ASYNC) == 0); #endif if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) { #ifdef F_DUPFD_CLOEXEC raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0); #else raw_s->fd = dup(s->fd); if (raw_s->fd != -1) { qemu_set_cloexec(raw_s->fd); } #endif if (raw_s->fd >= 0) { ret = fcntl_setfl(raw_s->fd, raw_s->open_flags); if (ret) { qemu_close(raw_s->fd); raw_s->fd = -1; } } } if (raw_s->fd == -1) { assert(!(raw_s->open_flags & O_CREAT)); raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags); if (raw_s->fd == -1) { error_setg_errno(errp, errno, "Could not reopen file"); ret = -1; } } if (raw_s->fd != -1) { raw_probe_alignment(state->bs, raw_s->fd, &local_err); if (local_err) { qemu_close(raw_s->fd); raw_s->fd = -1; error_propagate(errp, local_err); ret = -EINVAL; } } return ret; }
1threat
How to dockerize an ASP.NET Core 2.0 application? : <p>I have a simple ASP.NET Core 2.0 application with 2 projects in a solution. One project is a class library (WorldLibrary.dll), which is referenced by the web application (WeatherWeb.dll).</p> <p>I have tried to follow the steps here:</p> <p><a href="https://docs.docker.com/engine/examples/dotnetcore/" rel="noreferrer">https://docs.docker.com/engine/examples/dotnetcore/</a></p> <p>This is my Dockerfile:</p> <pre><code>FROM microsoft/aspnetcore-build:2.0 AS build-env WORKDIR /app # Copy csproj and restore as distinct layers COPY *.csproj ./ RUN dotnet restore # Copy everything else and build COPY . ./ RUN dotnet publish -c Release -o out # Build runtime image FROM microsoft/aspnetcore:2.0 WORKDIR /app COPY --from=build-env /app/out . ENTRYPOINT ["dotnet", "WeatherWeb.dll"] </code></pre> <p>But, there is a problem with the referenced .dll. I get the following output from the "docker build" command:</p> <pre><code>C:\Users\olavt\source\repos\Weather\WeatherWeb&gt;docker build -t weather . Sending build context to Docker daemon 6.398MB Step 1/10 : FROM microsoft/aspnetcore-build:2.0 AS build-env ---&gt; df4c9af52c86 Step 2/10 : WORKDIR /app ---&gt; Using cache ---&gt; ae9d1b099da7 Step 3/10 : COPY *.csproj ./ ---&gt; Using cache ---&gt; 2d9f3fba6470 Step 4/10 : RUN dotnet restore ---&gt; Using cache ---&gt; 19af5fb355a3 Step 5/10 : COPY . ./ ---&gt; 1704520a3ced Step 6/10 : RUN dotnet publish -c Release -o out ---&gt; Running in 7bcdf847e4dc /usr/share/dotnet/sdk/2.0.2/NuGet.targets(792,5): warning MSB3202: The project file "/WorldLibrary/WorldLibrary.csproj" was not found. [/app/WeatherWeb.csproj] Microsoft (R) Build Engine version 15.4.8.50001 for .NET Core Copyright (C) Microsoft Corporation. All rights reserved. /usr/share/dotnet/sdk/2.0.2/Microsoft.Common.CurrentVersion.targets(1768,5): warning : The referenced project '../WorldLibrary/WorldLibrary.csproj' does not exist. [/app/WeatherWeb.csproj] Controllers/Api/WeatherController.cs(6,7): error CS0246: The type or namespace name 'WorldLibrary' could not be found (are you missing a using directive or an assembly reference?) [/app/WeatherWeb.csproj] Controllers/WeatherController.cs(6,7): error CS0246: The type or namespace name 'WorldLibrary' could not be found (are you missing a using directive or an assembly reference?) [/app/WeatherWeb.csproj] Controllers/Api/WeatherController.cs(14,39): error CS0246: The type or namespace name 'Weather' could not be found (are you missing a using directive or an assembly reference?) [/app/WeatherWeb.csproj] The command '/bin/sh -c dotnet publish -c Release -o out' returned a non-zero code: 1 C:\Users\olavt\source\repos\Weather\WeatherWeb&gt; </code></pre> <p>How should I properly get the referenced .dll copied over correctly?</p>
0debug
Using webpack with an existing PHP and JS project : <p>I have an existing PHP project with jquery and bootstrap, not using any front-end framework.</p> <p>I am trying to use webpack module bundler in order to create a single entry point for my project resources, manage js dependencies with node js package manager, run tasks as minify js css, image re-size...etc. And improve the browser loading time required to load a single page.</p> <p>I came across the webpack tutorials and got to install it and install its dev-server, but the problem is that I am not able to understand how I will convert all my current js scripts and css links in the project (where I have a lot of jquery and CSS libraries used to provide multiple features in the project) to use webpack.</p> <p><strong>Do I have to rewrite all my JS and CSS files in a way that suits webpack? How do I make a successful migration?</strong></p> <p><strong>Besides, I am not able to run my current php application on the webpack dev-server, is it meant to run there in the first place? It is only listing the directories of the project in the meantime.</strong></p> <p>I have created a test <code>index.js</code> file and used the following webpack configuration:</p> <pre><code>var path = require('path'); var webpack = require('webpack'); module.exports = { entry: [ './public/js/index.js', 'webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:8080' ], plugins: [ new webpack.HotModuleReplacementPlugin() ], output: { path: path.join(__dirname, "public/dist/js"), publicPath : "http://localhost:8080/my_proj/public/dist/js", filename: "bundle.js" } }; </code></pre> <p>I added the <code>bundle.js</code> to my script loads just for testing as follows hoping that the application will run on the webpack dev-server:</p> <pre><code>&lt;script type="text/javascript" src="public/dist/js/bundle.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="public/js/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="public/js/jquery.migrate.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="public/js/jquery.bxslider.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="public/js/jquery.appear.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="public/js/jquery.countTo.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="public/js/bootstrap.js"&gt;&lt;/script&gt; </code></pre> <p><strong>Please help me understand the concept here and how can I make this migration successfully?</strong></p>
0debug
static int nbd_handle_reply_err(QIOChannel *ioc, nbd_opt_reply *reply, Error **errp) { char *msg = NULL; int result = -1; if (!(reply->type & (1 << 31))) { return 1; } if (reply->length) { if (reply->length > NBD_MAX_BUFFER_SIZE) { error_setg(errp, "server's error message is too long"); goto cleanup; } msg = g_malloc(reply->length + 1); if (read_sync(ioc, msg, reply->length, errp) < 0) { error_prepend(errp, "failed to read option error message"); goto cleanup; } msg[reply->length] = '\0'; } switch (reply->type) { case NBD_REP_ERR_UNSUP: TRACE("server doesn't understand request %" PRIx32 ", attempting fallback", reply->option); result = 0; goto cleanup; case NBD_REP_ERR_POLICY: error_setg(errp, "Denied by server for option %" PRIx32, reply->option); break; case NBD_REP_ERR_INVALID: error_setg(errp, "Invalid data length for option %" PRIx32, reply->option); break; case NBD_REP_ERR_PLATFORM: error_setg(errp, "Server lacks support for option %" PRIx32, reply->option); break; case NBD_REP_ERR_TLS_REQD: error_setg(errp, "TLS negotiation required before option %" PRIx32, reply->option); break; case NBD_REP_ERR_SHUTDOWN: error_setg(errp, "Server shutting down before option %" PRIx32, reply->option); break; default: error_setg(errp, "Unknown error code when asking for option %" PRIx32, reply->option); break; } if (msg) { error_append_hint(errp, "%s\n", msg); } cleanup: g_free(msg); if (result < 0) { nbd_send_opt_abort(ioc); } return result; }
1threat
Ubuntu c++: The easiest way to display a 3D mesh and a 2D image together? : <p>I've been fighting with several libraries (irrlicht, Ogre3D etc) and falling between either too complex libraries or too complex installation guides. I'd appreciate some pointers to how to achieve what the title suggests.</p> <p>Thanks</p>
0debug
Keras - Plot training, validation and test set accuracy : <p>I want to plot the output of this simple neural network: </p> <pre><code>model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) history = model.fit(x_test, y_test, nb_epoch=10, validation_split=0.2, shuffle=True) model.test_on_batch(x_test, y_test) model.metrics_names </code></pre> <p>I have plotted <em>accuracy</em> and <em>loss</em> of training and validation:</p> <pre><code>print(history.history.keys()) # "Accuracy" plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'validation'], loc='upper left') plt.show() # "Loss" plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'validation'], loc='upper left') plt.show() </code></pre> <p>Now I want to add and plot test set's accuracy from <code>model.test_on_batch(x_test, y_test)</code>, but from <code>model.metrics_names</code> I obtain the same value <em>'acc'</em> utilized for plotting accuracy on training data <code>plt.plot(history.history['acc'])</code>. How could I plot test set's accuracy?</p>
0debug
gen_intermediate_code_internal (CPUState *env, TranslationBlock *tb, int search_pc) { DisasContext ctx; target_ulong pc_start; uint16_t *gen_opc_end; int j, lj = -1; if (search_pc && loglevel) fprintf (logfile, "search pc %d\n", search_pc); pc_start = tb->pc; gen_opc_end = gen_opc_buf + OPC_MAX_SIZE; ctx.pc = pc_start; ctx.saved_pc = -1; ctx.tb = tb; ctx.bstate = BS_NONE; ctx.hflags = (uint32_t)tb->flags; restore_cpu_state(env, &ctx); #if defined(CONFIG_USER_ONLY) ctx.mem_idx = MIPS_HFLAG_UM; #else ctx.mem_idx = ctx.hflags & MIPS_HFLAG_KSU; #endif #ifdef DEBUG_DISAS if (loglevel & CPU_LOG_TB_CPU) { fprintf(logfile, "------------------------------------------------\n"); cpu_dump_state(env, logfile, fprintf, 0); } #endif #ifdef MIPS_DEBUG_DISAS if (loglevel & CPU_LOG_TB_IN_ASM) fprintf(logfile, "\ntb %p idx %d hflags %04x\n", tb, ctx.mem_idx, ctx.hflags); #endif while (ctx.bstate == BS_NONE && gen_opc_ptr < gen_opc_end) { if (env->nb_breakpoints > 0) { for(j = 0; j < env->nb_breakpoints; j++) { if (env->breakpoints[j] == ctx.pc) { save_cpu_state(&ctx, 1); ctx.bstate = BS_BRANCH; gen_op_debug(); ctx.pc += 4; goto done_generating; } } } if (search_pc) { j = gen_opc_ptr - gen_opc_buf; if (lj < j) { lj++; while (lj < j) gen_opc_instr_start[lj++] = 0; } gen_opc_pc[lj] = ctx.pc; gen_opc_hflags[lj] = ctx.hflags & MIPS_HFLAG_BMASK; gen_opc_instr_start[lj] = 1; } ctx.opcode = ldl_code(ctx.pc); decode_opc(env, &ctx); ctx.pc += 4; if (env->singlestep_enabled) break; if ((ctx.pc & (TARGET_PAGE_SIZE - 1)) == 0) break; #if defined (MIPS_SINGLE_STEP) break; #endif } if (env->singlestep_enabled) { save_cpu_state(&ctx, ctx.bstate == BS_NONE); gen_op_debug(); } else { switch (ctx.bstate) { case BS_STOP: tcg_gen_helper_0_0(do_interrupt_restart); gen_goto_tb(&ctx, 0, ctx.pc); break; case BS_NONE: save_cpu_state(&ctx, 0); gen_goto_tb(&ctx, 0, ctx.pc); break; case BS_EXCP: tcg_gen_helper_0_0(do_interrupt_restart); tcg_gen_exit_tb(0); break; case BS_BRANCH: default: break; } } done_generating: *gen_opc_ptr = INDEX_op_end; if (search_pc) { j = gen_opc_ptr - gen_opc_buf; lj++; while (lj <= j) gen_opc_instr_start[lj++] = 0; } else { tb->size = ctx.pc - pc_start; } #ifdef DEBUG_DISAS #if defined MIPS_DEBUG_DISAS if (loglevel & CPU_LOG_TB_IN_ASM) fprintf(logfile, "\n"); #endif if (loglevel & CPU_LOG_TB_IN_ASM) { fprintf(logfile, "IN: %s\n", lookup_symbol(pc_start)); target_disas(logfile, pc_start, ctx.pc - pc_start, 0); fprintf(logfile, "\n"); } if (loglevel & CPU_LOG_TB_CPU) { fprintf(logfile, "---------------- %d %08x\n", ctx.bstate, ctx.hflags); } #endif return 0; }
1threat
Particles.js as a background? : <p>I'm trying to use this example as a background but I can't seem to get it to work. </p> <p><a href="http://vincentgarreau.com/particles.js/#nasa" rel="noreferrer">http://vincentgarreau.com/particles.js/#nasa</a></p> <p>In order to get around this I'm forced to use a margin top of -1500px just to place my text over the top of it and it's causing major issues with responsiveness.</p> <p>Does anyone have any idea on how I can use it strictly as a background?</p> <p>The creator of the plugin has done it here on his website. </p> <p><a href="http://vincentgarreau.com/en" rel="noreferrer">http://vincentgarreau.com/en</a></p> <p>You can tell because when you inspect it, there is no "canvas" hovering over the top as there is on the CodePen example.</p>
0debug
If array item is empty : <p>I've this array : </p> <pre><code>Array ( [0] =&gt; test1 [1] =&gt; test2 [2] =&gt; test3 [3] =&gt; [4] =&gt; test4 ) </code></pre> <p>I want to check if any array item is empty or not, as you can see, there's en empty item into my array : <code>[3] =&gt; [4] =&gt; test4</code></p> <p>So I wrote this condition :</p> <pre><code> foreach ($array1 as $value) { if(!isset($value)) { echo "EMPTY"; } else { echo "Not empty"; } } </code></pre> <p>But it echo <code>Not empty</code> every time, there must have <code>empty</code> for one item</p> <p>Thanks for your help !</p>
0debug
static void decode_nal_sei_decoded_picture_hash(HEVCContext *s) { int cIdx, i; uint8_t hash_type; GetBitContext *gb = &s->HEVClc->gb; hash_type = get_bits(gb, 8); for (cIdx = 0; cIdx < 3; cIdx++) { if (hash_type == 0) { s->is_md5 = 1; for (i = 0; i < 16; i++) s->md5[cIdx][i] = get_bits(gb, 8); } else if (hash_type == 1) { skip_bits(gb, 16); } else if (hash_type == 2) { skip_bits(gb, 32); } } }
1threat
Java 6 André kotlin : I have some projects in Java 6, spring on app server. Because limitations in my infraestruture And governance planninng i cannot migrate to newer Java 7 And 8. I think i would add kotlin in projects to use features like functional programming. It is a good way? Thanks
0debug
python 3.5 ubuntu Deep neural Networks syntax error : <p>I am trying to run this code in Python version 3.5 in ubuntu using keras and tensorflow api in backend .But it shows syntax error in line 13.This is code taken from the link <a href="https://github.com/JostineHo/mememoji/tree/master/src.According" rel="nofollow noreferrer">https://github.com/JostineHo/mememoji/tree/master/src.According</a> to me there is no syntax error in the code.</p> <pre><code>enter code here from keras.preprocessing.image import ImageDataGenerator from keras.mo`enter code here`dels import Sequential from keras.layers import Convolution2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense from keras.callbacks import EarlyStopping from log import save_model, save_config, save_result from sklearn.cross_validation import train_test_split import numpy as np import time import sys def describe(X_shape, y_shape, batch_size, dropout, nb_epoch, conv_arch, dense): print ' X_train shape: ', X_shape # (n_sample, 1, 48, 48) print ' y_train shape: ', y_shape # (n_sample, n_categories) print ' img size: ', X_shape[2], X_shape[3] print ' batch size: ', batch_size print ' nb_epoch: ', nb_epoch print ' dropout: ', dropout print 'conv architect: ', conv_arch print 'neural network: ', dense def logging(model, starttime, batch_size, nb_epoch, conv_arch,dense, dropout, X_shape, y_shape, train_acc, val_acc, dirpath): now = time.ctime() model.save_weights('../data/weights/{}'.format(now)) save_model(model.to_json(), now, dirpath) save_config(model.get_config(), now, dirpath) save_result(starttime, batch_size, nb_epoch, conv_arch, dense, dropout, X_shape, y_shape, train_acc, val_acc, dirpath) def cnn_architecture(X_train, y_train, conv_arch=[(32,3),(64,3),(128,3)], dense=[64,2], dropout=0.5, batch_size=128, nb_epoch=100, validation_split=0.2, patience=5, dirpath='../data/results/'): starttime = time.time() X_train = X_train.astype('float32') X_shape = X_train.shape y_shape = y_train.shape describe(X_shape, y_shape, batch_size, dropout, nb_epoch, conv_arch, dense) # data augmentation: # X_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size=validation_split) # datagen = ImageDataGenerator(rescale=1./255, # rotation_range=10, # shear_range=0.2, # width_shift_range=0.2, # height_shift_range=0.2, # horizontal_flip=True) # datagen.fit(X_train) # model architecture: model = Sequential() model.add(Convolution2D(conv_arch[0][0], 3, 3, border_mode='same', activation='relu',input_shape=(1, X_train.shape[2], X_train.shape[3]))) if (conv_arch[0][1]-1) != 0: for i in range(conv_arch[0][1]-1): model.add(Convolution2D(conv_arch[0][0], 3, 3, border_mode='same', activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) if conv_arch[1][1] != 0: for i in range(conv_arch[1][1]): model.add(Convolution2D(conv_arch[1][0], 3, 3, border_mode='same', activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) if conv_arch[2][1] != 0: for i in range(conv_arch[2][1]): model.add(Convolution2D(conv_arch[2][0], 3, 3, border_mode='same', activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) # this converts 3D feature maps to 1D feature vectors if dense[1] != 0: for i in range(dense[1]): model.add(Dense(dense[0], activation='relu')) if dropout: model.add(Dropout(dropout)) prediction = model.add(Dense(y_train.shape[1], activation='softmax')) # optimizer: model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # set callback: callbacks = [] if patience != 0: early_stopping = EarlyStopping(monitor='val_loss', patience=patience, verbose=1) callbacks.append(early_stopping) print 'Training....' # fits the model on batches with real-time data augmentation: # hist = model.fit_generator(datagen.flow(X_train, y_train, batch_size=batch_size), # samples_per_epoch=len(X_train), nb_epoch=nb_epoch, validation_data=(X_test,y_test), callbacks=callbacks, verbose=1) '''without data augmentation''' hist = model.fit(X_train, y_train, nb_epoch=nb_epoch, batch_size=batch_size, validation_split=validation_split, callbacks=callbacks, shuffle=True, verbose=1) # model result: train_val_accuracy = hist.history train_acc = train_val_accuracy['acc'] val_acc = train_val_accuracy['val_acc'] print ' Done!' print ' Train acc: ', train_acc[-1] print 'Validation acc: ', val_acc[-1] print ' Overfit ratio: ', val_acc[-1]/train_acc[-1] logging(model, starttime, batch_size, nb_epoch, conv_arch, dense, dropout, X_shape, y_shape, train_acc, val_acc, dirpath) return model if __name__ == '__main__': # import dataset: X_fname = '../data/X_train6_5pct.npy' y_fname = '../data/y_train6_5pct.npy' X_train = np.load(X_fname) y_train = np.load(y_fname) print 'Loading data...' cnn_architecture(X_train, y_train, conv_arch=[(32,3),(64,3),(128,3)], dense=[64,2], batch_size=256, nb_epoch=5, dirpath = '../data/results/') </code></pre>
0debug
static int decode_block_refinement(MJpegDecodeContext *s, int16_t *block, uint8_t *last_nnz, int ac_index, int16_t *quant_matrix, int ss, int se, int Al, int *EOBRUN) { int code, i = ss, j, sign, val, run; int last = FFMIN(se, *last_nnz); OPEN_READER(re, &s->gb); if (*EOBRUN) { (*EOBRUN)--; } else { for (; ; i++) { UPDATE_CACHE(re, &s->gb); GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2); if (code & 0xF) { run = ((unsigned) code) >> 4; UPDATE_CACHE(re, &s->gb); val = SHOW_UBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); ZERO_RUN; j = s->scantable.permutated[i]; val--; block[j] = ((quant_matrix[j]^val) - val) << Al; if (i == se) { if (i > *last_nnz) *last_nnz = i; CLOSE_READER(re, &s->gb); return 0; } } else { run = ((unsigned) code) >> 4; if (run == 0xF) { ZERO_RUN; } else { val = run; run = (1 << run); if (val) { UPDATE_CACHE(re, &s->gb); run += SHOW_UBITS(re, &s->gb, val); LAST_SKIP_BITS(re, &s->gb, val); } *EOBRUN = run - 1; break; } } } if (i > *last_nnz) *last_nnz = i; } for (; i <= last; i++) { j = s->scantable.permutated[i]; if (block[j]) REFINE_BIT(j) } CLOSE_READER(re, &s->gb); return 0; }
1threat
C: Add numbers to filename : I want to store data in different files. Therefore I want to create files as follows: `data_1.log`, `data_2.log`, ..., `data_N.log`. The appendix `.log` is not necessary but would be nice. All my approaches failed so far. Here is one sample that is probably close to what I need: #include <stdio.h> #include <string.h> char get_file_name(int k){ int i, j; char s1[100] = "logs/data_"; char s2[100]; snprintf(s2, 100, "%d", k); for(i = 0; s1[i] != '\0'; ++i); for(j = 0; s2[j] != '\0'; ++j, ++i){ s1[i] = s2[j]; } s1[i] = '\0'; return s1; } int main(){ char file_name[100]; for(int k=0; k<10; k++){ // Get data // ... // Create filename strcpy(file_name, get_file_name(k)); printf("%s", file_name); fp = fopen(file_name, "w+"); // Write data to file print_results_to_file(); fclose(fp); } return 0; } At the moment I get the following errors which I don't understand: string.c: In function ‘get_file_name’: string.c:14:12: warning: returning ‘char *’ from a function with return type ‘char’ makes integer from pointer without a cast [-Wint-conversion] return s1; ^~ string.c:14:12: warning: function returns address of local variable [-Wreturn-local-addr] string.c: In function ‘main’: string.c:24:27: warning: passing argument 2 of ‘strcpy’ makes pointer from integer without a cast [-Wint-conversion] strcpy(file_name, get_file_name(k)); ^~~~~~~~~~~~~~~~ In file included from string.c:2: /usr/include/string.h:121:14: note: expected ‘const char * restrict’ but argument is of type ‘char’ extern char *strcpy (char *__restrict __dest, const char *__restrict __src) ^~~~~~ string.c:29:9: warning: implicit declaration of function ‘print_results_to_file’ [-Wimplicit-function-declaration] print_results_to_file(); ^~~~~~~~~~~~~~~~~~~~~ /usr/bin/ld: /tmp/ccZDRebi.o: in function `main': string.c:(.text+0x190): undefined reference to `print_results_to_file' collect2: error: ld returned 1 exit status Is there a more simpler way to create such filenames? I can't believe that there isn't one.
0debug
target_ulong helper_dvpe(target_ulong arg1) { arg1 = 0; return arg1; }
1threat
dbeaver: how can I export connection configuration? : <p>I recently got a new macbook pro for work and I'm in the process of migrating a lot of my settings from my old machine. I was hoping that there is a way to export the connection configuration/properties from my old machine rather than have to go through the process of recreating each one. </p> <p>Does anyone know how to do this? The dbeaver version on my old machine is 6.0.3 and the version on my new machine is 6.1.x</p> <p>thanks!</p>
0debug
Member equal is not available in type(library Assert) : <p>The problem arises when I want to test whether a string value is correct. Numbers are asserted correctly and don't return an error message when they are trying to be compiled. However, when I try to assert a string, it returns the following error message:</p> <pre><code>Error: Member "equal" is not available in type(library Assert) outside of storage. Assert.equal(token.symbol(), "$", "The symbol of the token should be $"); ^----------^ Compiliation failed. See above. </code></pre> <p><strong>Token.sol</strong></p> <pre><code>pragma solidity ^0.4.8; contract Token { /* The amount of tokens a person will get for 1 ETH */ uint256 public exchangeRate; /* The name of the token */ string public name; /* The address which controls the token */ address public owner; /* The symbol of the token */ string public symbol; /* The balances of all registered addresses */ mapping (address =&gt; uint256) balances; /* Token constructor */ function Token(uint256 _exchangeRate, string _name, string _symbol) { exchangeRate = _exchangeRate; name = _name; owner = msg.sender; symbol = _symbol; } function getBalance(address account) returns (uint256 balance) { return balances[account]; } } </code></pre> <p><strong>TestToken.sol</strong></p> <pre><code>pragma solidity ^0.4.8; // Framework libraries import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; // Custom libraries and contracts import "../contracts/Token.sol"; contract TestToken { function testExchangeRate() { Token token = new Token(500, "Dollar", "$"); uint256 expected = 500; Assert.equal(token.exchangeRate(), expected, "The exchange rate should be 500 tokens for 1 ETH"); } function testSymbol() { Token token = new Token(500, "Dollar", "$"); Assert.equal(token.symbol(), "$", "The symbol of the token should be $"); } } </code></pre> <p>Why does it happen and how do you solve it?</p>
0debug
window.open() doesn't open the website, what to do? : <p>I have this piece of code:</p> <pre><code> ((JavascriptExecutor)driver).executeScript("Object.assign(document.createElement('a'), { target: '_blank', href: 'https://facebook.com'}).click()"); ((JavascriptExecutor)driver).executeScript("window.open('https://google.com')'"); </code></pre> <p>First command is meant to create a new tab and open facebook.com and it does, first is meant to open google.com but nothing happens, am I doing anything wrong?</p> <p>Disclaimer:<br> 1.I am not familiar with Javascript at all, this is a Java Selenium project (hence why the <code>(JavascriptExecutor)driver).executeScript</code> part and I need to use Javascript for these few lines.<br> 2.I tried multiple simpler piece of codes instead of this one but nothing worked hence why I ended up with this which is not the simplest.</p>
0debug
How to install all required modules from gulpfile.js : <p>Is it possible install all required modules from gulpfile.js with command line?</p>
0debug
I would like to combine the file with the same name from multiple folders into a single file using windows cmd : I would like to combine the file with the same name from multiple folders into a single file using windows cmd i have a file named crudeoilm-f1.csv in multiple folders like 20160101 , 20160102 , i would to concatenate this crudeoilm-f1.csv file into a single file.
0debug
Сonditional fusion of two arrays : I have two arrays: $array1 = [1, 2, 3]; $array2 = ['a', 'b', 'c']; Please tell me how to get to the output I received: $array3 = [ 1 => 'a', 1 => 'b', 1 => 'c', 2 => 'a', 2 => 'b', 2 => 'c', 3 => 'a', 3 => 'b', 3 => 'c', ];
0debug
static void stop(DBDMA_channel *ch) { ch->regs[DBDMA_STATUS] &= cpu_to_be32(~(ACTIVE|DEAD|FLUSH)); }
1threat
static int dv_read_timecode(AVFormatContext *s) { int ret; char timecode[AV_TIMECODE_STR_SIZE]; int64_t pos = avio_tell(s->pb); int partial_frame_size = 3 * 80; uint8_t *partial_frame = av_mallocz(sizeof(*partial_frame) * partial_frame_size); RawDVContext *c = s->priv_data; ret = avio_read(s->pb, partial_frame, partial_frame_size); if (ret < 0) goto finish; if (ret < partial_frame_size) { ret = -1; goto finish; } ret = dv_extract_timecode(c->dv_demux, partial_frame, timecode); if (ret) av_dict_set(&s->metadata, "timecode", timecode, 0); else if (ret < 0) av_log(s, AV_LOG_ERROR, "Detected timecode is invalid\n"); finish: av_free(partial_frame); avio_seek(s->pb, pos, SEEK_SET); return ret; }
1threat
static void autocorrelate(const float x[40][2], float phi[3][2][2], int lag) { int i; float real_sum = 0.0f; float imag_sum = 0.0f; if (lag) { for (i = 1; i < 38; i++) { real_sum += x[i][0] * x[i+lag][0] + x[i][1] * x[i+lag][1]; imag_sum += x[i][0] * x[i+lag][1] - x[i][1] * x[i+lag][0]; } phi[2-lag][1][0] = real_sum + x[ 0][0] * x[lag][0] + x[ 0][1] * x[lag][1]; phi[2-lag][1][1] = imag_sum + x[ 0][0] * x[lag][1] - x[ 0][1] * x[lag][0]; if (lag == 1) { phi[0][0][0] = real_sum + x[38][0] * x[39][0] + x[38][1] * x[39][1]; phi[0][0][1] = imag_sum + x[38][0] * x[39][1] - x[38][1] * x[39][0]; } } else { for (i = 1; i < 38; i++) { real_sum += x[i][0] * x[i][0] + x[i][1] * x[i][1]; } phi[2][1][0] = real_sum + x[ 0][0] * x[ 0][0] + x[ 0][1] * x[ 0][1]; phi[1][0][0] = real_sum + x[38][0] * x[38][0] + x[38][1] * x[38][1]; } }
1threat
Loop through hosts with ansible : <p>I have a problem to find a working solution to loop over my inventory. I start my playbook with linking a intentory file:</p> <blockquote> <p>ansible-playbook -i inventory/dev.yml playbook.yml</p> </blockquote> <p>My playbook looks like this:</p> <pre><code>--- - hosts: localhost tasks: - name: Create VM if enviro == true include_role: name: local_vm_creator when: enviro == 'dev' </code></pre> <p>So when loading the playbook the variable enviro is read from host_vars and sets the when condition to dev. The inventory file dev.yml looks like this:</p> <pre><code>[local_vm] 192.168.99.100 192.168.99.101 192.168.99.102 [local_vm_manager_1] 192.168.99.103 [local_vm_manager_2] 192.168.99.104 [local-all:children] local_vm local_vm_manager_1 local_vm_manager_2 </code></pre> <p>My main.yml in my role local_vm_creator looks like this:</p> <pre><code>--- - name: Create test host local_action: shell docker-machine create -d virtualbox {{ item }} with_items: - node-1 - node-2 - node-3 - node-4 - node-5 - debug: msg="host is {{item}}" with_items: groups['local_vm'] </code></pre> <p>And the problem is that i can't get the listed servers from the dev.yml inventory file.</p> <p>it just returns: </p> <blockquote> <p>ok: [localhost] => (item=groups['local_vm']) => { "item": "groups['local_vm']", "msg": "host is groups['local_vm']" }</p> </blockquote>
0debug
static inline void RENAME(rgb16tobgr24)(const uint8_t *src, uint8_t *dst, long src_size) { const uint16_t *end; #if COMPILE_TEMPLATE_MMX const uint16_t *mm_end; #endif uint8_t *d = (uint8_t *)dst; const uint16_t *s = (const uint16_t *)src; end = s + src_size/2; #if COMPILE_TEMPLATE_MMX __asm__ volatile(PREFETCH" %0"::"m"(*s):"memory"); mm_end = end - 7; while (s < mm_end) { __asm__ volatile( PREFETCH" 32%1 \n\t" "movq %1, %%mm0 \n\t" "movq %1, %%mm1 \n\t" "movq %1, %%mm2 \n\t" "pand %2, %%mm0 \n\t" "pand %3, %%mm1 \n\t" "pand %4, %%mm2 \n\t" "psllq $3, %%mm0 \n\t" "psrlq $3, %%mm1 \n\t" "psrlq $8, %%mm2 \n\t" "movq %%mm0, %%mm3 \n\t" "movq %%mm1, %%mm4 \n\t" "movq %%mm2, %%mm5 \n\t" "punpcklwd %5, %%mm0 \n\t" "punpcklwd %5, %%mm1 \n\t" "punpcklwd %5, %%mm2 \n\t" "punpckhwd %5, %%mm3 \n\t" "punpckhwd %5, %%mm4 \n\t" "punpckhwd %5, %%mm5 \n\t" "psllq $8, %%mm1 \n\t" "psllq $16, %%mm2 \n\t" "por %%mm1, %%mm0 \n\t" "por %%mm2, %%mm0 \n\t" "psllq $8, %%mm4 \n\t" "psllq $16, %%mm5 \n\t" "por %%mm4, %%mm3 \n\t" "por %%mm5, %%mm3 \n\t" "movq %%mm0, %%mm6 \n\t" "movq %%mm3, %%mm7 \n\t" "movq 8%1, %%mm0 \n\t" "movq 8%1, %%mm1 \n\t" "movq 8%1, %%mm2 \n\t" "pand %2, %%mm0 \n\t" "pand %3, %%mm1 \n\t" "pand %4, %%mm2 \n\t" "psllq $3, %%mm0 \n\t" "psrlq $3, %%mm1 \n\t" "psrlq $8, %%mm2 \n\t" "movq %%mm0, %%mm3 \n\t" "movq %%mm1, %%mm4 \n\t" "movq %%mm2, %%mm5 \n\t" "punpcklwd %5, %%mm0 \n\t" "punpcklwd %5, %%mm1 \n\t" "punpcklwd %5, %%mm2 \n\t" "punpckhwd %5, %%mm3 \n\t" "punpckhwd %5, %%mm4 \n\t" "punpckhwd %5, %%mm5 \n\t" "psllq $8, %%mm1 \n\t" "psllq $16, %%mm2 \n\t" "por %%mm1, %%mm0 \n\t" "por %%mm2, %%mm0 \n\t" "psllq $8, %%mm4 \n\t" "psllq $16, %%mm5 \n\t" "por %%mm4, %%mm3 \n\t" "por %%mm5, %%mm3 \n\t" :"=m"(*d) :"m"(*s),"m"(mask16b),"m"(mask16g),"m"(mask16r),"m"(mmx_null) :"memory"); __asm__ volatile( "movq %%mm0, %%mm4 \n\t" "movq %%mm3, %%mm5 \n\t" "movq %%mm6, %%mm0 \n\t" "movq %%mm7, %%mm1 \n\t" "movq %%mm4, %%mm6 \n\t" "movq %%mm5, %%mm7 \n\t" "movq %%mm0, %%mm2 \n\t" "movq %%mm1, %%mm3 \n\t" STORE_BGR24_MMX :"=m"(*d) :"m"(*s) :"memory"); d += 24; s += 8; } __asm__ volatile(SFENCE:::"memory"); __asm__ volatile(EMMS:::"memory"); #endif while (s < end) { register uint16_t bgr; bgr = *s++; *d++ = (bgr&0x1F)<<3; *d++ = (bgr&0x7E0)>>3; *d++ = (bgr&0xF800)>>8; } }
1threat
static void isa_cirrus_vga_realizefn(DeviceState *dev, Error **errp) { ISADevice *isadev = ISA_DEVICE(dev); ISACirrusVGAState *d = ISA_CIRRUS_VGA(dev); VGACommonState *s = &d->cirrus_vga.vga; vga_common_init(s, OBJECT(dev), true); cirrus_init_common(&d->cirrus_vga, OBJECT(dev), CIRRUS_ID_CLGD5430, 0, isa_address_space(isadev), isa_address_space_io(isadev)); s->con = graphic_console_init(dev, 0, s->hw_ops, s); rom_add_vga(VGABIOS_CIRRUS_FILENAME);
1threat
changing color of radial gradient using javascript : How can i change the red circle created to green circle using a javascript? #redcircle{ background-image: radial-gradient( circle, red, red 40px, transparent 20px );
0debug
How to get certain amount of elements from a list iteratively in python : <p>Assume I have a list </p> <pre><code>l= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>I want to have a permutation, that after each run gives me a new list, which contains only three elements from the main list and those list should occurs only once. E.g.</p> <pre><code>l1= [1,2,3] l2= [1,2,4] l3= [1,2,5] ... l8= [1,2,10] l9= [1,3,4] l10= [1,3,5] l11= [1,3,6] ... ln= [8,9,10] </code></pre> <p>How can I do something like this in python? Thanks you!</p>
0debug
How do i convert survey results as a percentage of the total respondents in python pandas : Please a survey was conducted with 2,233 respondents and the following results came under the following columns, very interested, Somewhat interested and Not interested as seen below Very interested somewhat interested Not interested A. 1688, 444, 60, B 1629, 477, 74, C 1340, 734, 102, D 1332, 729, 127, E 1263, 770, 136, Please how can I convert these numbers into percentages of the total number of respondents which is 2,233 and round of the percentages to 2 decimal places
0debug
Change value of DOM element by Javascript loop : <p>Following code logs a value 0 to 100 in console with 1000ms delay in between. But it does not update DOM element div.innerHTML as intended. How to change DOM element value by JS loop with delay. Looks like setTimeout does not work in loop.</p> <p><strong>HTML file</strong></p> <pre><code>&lt;div id="output"&gt;&lt;/div&gt; &lt;script&gt; var obj=document.getElementById("output"); for(var i=0;i&lt;100;i++){ obj.innerHTML=i.toString(); (function(i){ setTimeout(function(){ console.log(i); }, 1000 * i) })(i); } &lt;/script&gt; </code></pre>
0debug
is possible to set a default value in java object? : class Person { private String name; private String sex="male"; public Person(String name) { this.name = name; } public String getSex(){return this.sex;} } In the above class, if I want to set the default value for sex. is it ok? then, if I want to create new Person, is the following code good? Person p = new Person("mike'); String sex = p.getSex();
0debug
country picker swift 4 : <p>I would like implement a native iOS country picker in swift 4. Currently I have a table which contain the countries code: </p> <pre><code>var countriesCodes = NSLocale.isoCountryCodes as [String] </code></pre> <p>I implement the delegate, and I have a problem in the data source. How to convert each country code in country name?</p>
0debug
Is it possible to change the order of list items using CSS3? : <p>Is it possible to change the order of list items using CSS3?</p> <p>For example, if a list is coded in HTML in 1,2,3,4,5 order, but I want it to show in 5,1,2,3,4 order.</p> <p>I'm using a CSS overlay to modify a Firefox extension, so I can't just change the HTML.</p> <p>HTML Code</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li&gt;1&lt;/li&gt; &lt;li&gt;2&lt;/li&gt; &lt;li&gt;3&lt;/li&gt; &lt;li&gt;4&lt;/li&gt; &lt;li&gt;5&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>
0debug
value of using React.forwardRef vs custom ref prop : <p>I see that React.forwardRef seems to be the sanctioned way of passing a ref to a child functional component, from the react docs:</p> <pre><code>const FancyButton = React.forwardRef((props, ref) =&gt; ( &lt;button ref={ref} className="FancyButton"&gt; {props.children} &lt;/button&gt; )); // You can now get a ref directly to the DOM button: const ref = React.createRef(); &lt;FancyButton ref={ref}&gt;Click me!&lt;/FancyButton&gt;; </code></pre> <p>However, what is the advantage of doing this over simply passing a custom prop?:</p> <pre><code>const FancyButton = ({ innerRef }) =&gt; ( &lt;button ref={innerRef} className="FancyButton"&gt; {props.children} &lt;/button&gt; )); const ref = React.createRef(); &lt;FancyButton innerRef={ref}&gt;Click me!&lt;/FancyButton&gt;; </code></pre> <p>The only advantage I can think of is maybe having a consistent api for refs, but is there any other advantage? Does passing a custom prop affect diffing when it comes to rendering and cause additional renders, surely not as the ref is stored as mutable state in the <code>current</code> field?</p> <p>Say for example you wanted to pass multiple refs (which tbh, might indicate code smell, but still), then the only solution I can see would be to use customRef props.</p> <p>I guess my question is what is the value of using <code>forwardRef</code> over a custom prop?</p>
0debug
Automating software installation process with autoit where window is rebooting multiple times : How I can automate software installation with autoit where window is rebooting multiple time.
0debug
Custom attribute gives parsing error when using with an angular 2.0.0-beta.0 : <p>I'm trying to use custom attribute with angular2 as following</p> <pre><code> &lt;a href="javascript:void(0)" title="{{inst.title}}" data-loc="{{inst.actionval}}"&gt; </code></pre> <p>which gives me following error</p> <blockquote> <p>EXCEPTION: Template parse errors: Can't bind to 'loc' since it isn't a known native property</p> </blockquote>
0debug
Sporadic error: The file has not been pre-compiled, and cannot be requested : <p>Symptoms: ASP.NET Web Forms website on Azure sporadically crashes and all .aspx page requests fail with this error. The problem seems random and only happens once in a great while. The site may run for months with no issues then out of the blue it will stop serving any .aspx pages and gives the error on every .aspx page request. A restart of the website is the only solution (or redeploy, which causes the same thing).</p> <p>This was a very difficult problem to debug since it was so sporadic and none of the other answers I found helped, they did not address the problem where the site would deploy and run for long periods of time then crash with this error seemingly randomly. In the end I got some help from Microsoft.</p>
0debug
C# Typo Generator Algorithm : <p>I have a requirement where i need to get all possible typos(if not all most) that can occur for a possible word. For example (word : user). User can type "usre" or "yser" something like that. </p> <p>Currently i don't have anything in mind as to where i start. If anybody has already faced the similar situation and came with the solution, it would be helpful if you can help get kick start</p> <p>Thanks in Advance.</p>
0debug
void qemu_bh_update_timeout(int *timeout) { QEMUBH *bh; for (bh = async_context->first_bh; bh; bh = bh->next) { if (!bh->deleted && bh->scheduled) { if (bh->idle) { *timeout = MIN(10, *timeout); } else { *timeout = 0; break; } } } }
1threat
How to enable CodeLens for Visual Studio 2017 Community : <p>I recently installed Visual Studio 2017 Community and noticed that there is no CodeLens. I had CodeLens enabled on Visual Studio 2015 Community so I'm hoping that its also available for VS 2017 Community. How can I do so? Or is it no longer available for VS 2017 Community edition?</p> <p><strong>Enabling CodeLens on Visual Studio 2015 Community</strong> <a href="https://i.stack.imgur.com/8aePX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8aePX.png" alt="CodeLens on Visual Studio 2015 Community"></a></p>
0debug
I coded in php for a login test but the data is not showing in the database : <p>I have attempted to make a login test using php but the data is not showing inside the database..What's the problem?Following are the lines of code for signup.</p> <p>` <pre><code> include 'databasehandler.php'; $first=$_POST['first']; $last=$_POST['last']; $uid=$_POST['uid']; $password=$_POST['password']; $sql="INSERT INTO profile(first, last, uid, password) VALUES('$first, $last, $uid, $password')"; $result=mysqli_query($conn,$sql); header("Location:main.php");` </code></pre>
0debug
Start and stop android app after specific sms text : I'm developing an android app with Android studio that should send via sms user location, but I don't know how to start the app only when i receive a specific text. Can anyone help? Thank you.
0debug
Testing an IF statement with respect to state with Jest doesn't work : I am trying to test this method which is responsible for editing but am able to the lines which replace the **old title** and the **old body** with the new title and body. This is located in the IF section. Below is the code which implements editing : onEditNote = (event) => { const { target: { value: id } } = event; const obj = { title: this.state.title, body: this.state.body, }; // clear the errors while submitting this.setState({ titleError: '', bodyError: '' }); if (obj.title === '') { this.setState({ titleError: 'Title empty, please add title' }); } else if (obj.body === '') { this.setState({ bodyError: 'Body empty, please add body' }); } else if (obj.title.length > 20) { this.setState({ titleError: 'Title is too long.' }); } else { this.setState((state) => { const list = state.notesArray.map((item) => { if (item.id === id) { // eslint-disable-next-line no-param-reassign item.title = obj.title; // eslint-disable-next-line no-param-reassign item.body = obj.body; } return item; }); localStorage.setItem('items', JSON.stringify(list)); // eslint-disable-next-line no-undef $('#editModal').modal('close'); this.onSuccessToast('Noted edited successfully.'); return { list, title: '', body: '', }; }); } }; These are the lines in the above code which are not covered by the test I implemented : > if (item.id === id) { > // eslint-disable-next-line no-param-reassign > item.title = obj.title; > // eslint-disable-next-line no-param-reassign > item.body = obj.body; > } And below is my test I am implementing which doesn't cover the IF statement, yet I see I have covered it : it('should edit a Note.', () => { wrapper = shallow(<App />); $.fn.modal = jest.fn(); wrapper.instance().onEditNote({ target: { value: '0' } }); wrapper.instance().setState({ title: 'huxy 12', body: 'hey huxy this is not great.', notesArray: [{ title: 'hey', body: 'its good', id: '0' }], }); wrapper.instance().setState((state) => { state.notesArray.map((item) => { if (item.id === '0') { // eslint-disable-next-line no-param-reassign item.title = state.title; // eslint-disable-next-line no-param-reassign item.body = state.body; } return item; }); }); }); What am I missing in my test?
0debug
I have it going in a complete loop and don't kn ow how to make it stop : my teacher asked us to create a magic 8 ball program in java 8. we have to use 3 methods, a main, a processing, and an output and we need to pass parameters between the methods. the output needs to use the switch statement, we need to have a while statement in there and the answers need to be randomly generated. I have everything required but when I try to run the program it is stuck in the while loop and I don't know what I did wrong. here is what I have: import java.util.*; public class Magic8Ball { public static void main(String[]args) { Scanner input = new Scanner(System.in); System.out.print("Would you like to ask a question? Y or N: "); char answer = input.next().charAt(0); char Y = Character.toUpperCase(answer); process(answer, Y); } public static void process(char a, char Yes) { if (a != Yes) { System.out.println("Thank you, goodbye."); } else { while(a==Yes) { System.out.print("Ask your question: "); Random random = new Random(); int ran = random.nextInt(8-1+1)+1; output(ran); } } } Public static int output(int r) { switch (r) { case 1: System.out.println("Out of memory, try again later); break; case 2: System.out.println("The probability matrix supports you."); break; case 3: System.out.println("That does not compute."); break; case 4: System.out.println("System error, try again later"); break; case 5: System.out.println("Siri says yes."); break; case 6: System.out.println("The asnwer could not be found on the internet."); break; case 7: System.out.println("Wikilinks claims it is true."); break; case 8: System.out.println("Siri says no."); break; default: System.out.println("The system is not responding, try again later"); break; } return r; } }
0debug
Cleaning of ImageView : <p>I need to clean ImageView. I have some figures there.</p> <pre><code>@IBOutlet weak var imageView: UIImageView! </code></pre> <p>I tried using</p> <pre><code>imageView.image = nil </code></pre> <p>but it doesn't work. How can I clean imageView?</p>
0debug
Scale just part of a curve - python sciPy : I need to scale a curve as shown on the picture underneath. The curve is a two-dimensional array consisting of many X and Y values. It is important that the curve stays continuous and there is no "leap" at the place where I want to cut. Do you have any ideas? Is there a function/functions in python that can do this? [![blue curve needed, red was the initial][1]][1] [1]: https://i.stack.imgur.com/pjYtW.png
0debug
static void decode_band_structure(GetBitContext *gbc, int blk, int eac3, int ecpl, int start_subband, int end_subband, const uint8_t *default_band_struct, int *num_bands, uint8_t *band_sizes) { int subbnd, bnd, n_subbands, n_bands=0; uint8_t bnd_sz[22]; uint8_t coded_band_struct[22]; const uint8_t *band_struct; n_subbands = end_subband - start_subband; if (!eac3 || get_bits1(gbc)) { for (subbnd = 0; subbnd < n_subbands - 1; subbnd++) { coded_band_struct[subbnd] = get_bits1(gbc); } band_struct = coded_band_struct; } else if (!blk) { band_struct = &default_band_struct[start_subband+1]; } else { return; } if (num_bands || band_sizes ) { n_bands = n_subbands; bnd_sz[0] = ecpl ? 6 : 12; for (bnd = 0, subbnd = 1; subbnd < n_subbands; subbnd++) { int subbnd_size = (ecpl && subbnd < 4) ? 6 : 12; if (band_struct[subbnd - 1]) { n_bands--; bnd_sz[bnd] += subbnd_size; } else { bnd_sz[++bnd] = subbnd_size; } } } if (num_bands) *num_bands = n_bands; if (band_sizes) memcpy(band_sizes, bnd_sz, n_bands); }
1threat
AVFilterBufferRef *avfilter_default_get_video_buffer(AVFilterLink *link, int perms, int w, int h) { AVFilterBuffer *pic = av_mallocz(sizeof(AVFilterBuffer)); AVFilterBufferRef *ref = av_mallocz(sizeof(AVFilterBufferRef)); int i, tempsize; char *buf; ref->buf = pic; ref->video = av_mallocz(sizeof(AVFilterBufferRefVideoProps)); ref->video->w = w; ref->video->h = h; ref->perms = perms | AV_PERM_READ; pic->refcount = 1; ref->format = link->format; pic->free = avfilter_default_free_buffer; av_fill_image_linesizes(pic->linesize, ref->format, ref->video->w); for (i=0; i<4;i++) pic->linesize[i] = FFALIGN(pic->linesize[i], 16); tempsize = av_fill_image_pointers(pic->data, ref->format, ref->video->h, NULL, pic->linesize); buf = av_malloc(tempsize + 16); av_fill_image_pointers(pic->data, ref->format, ref->video->h, buf, pic->linesize); memcpy(ref->data, pic->data, sizeof(ref->data)); memcpy(ref->linesize, pic->linesize, sizeof(ref->linesize)); return ref; }
1threat
UITextField secureTextEntry toggle set incorrect font : <p>I have an <code>UITextField</code> which I use as a password field. It has by default <code>secureTextEntry</code> set to <code>true</code>. I also have a <code>UIButton</code> to toggle the show/hide of the password.</p> <p>When I change the textfield from <code>secureTextEntry</code> set to <code>true</code> to <code>false</code>, the font gets weird. Seems it becomes Times New Roman or similar.</p> <p>I have tried re-setting the font to system with size 14, but it didn't change anything. </p> <p>Example of what happens (with initial <code>secureTextEntry</code> set to <code>true</code>): <a href="https://i.stack.imgur.com/ab5sy.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/ab5sy.gif" alt="Example"></a></p> <p>My code:</p> <pre><code>@IBAction func showHidePwd(sender: AnyObject) { textfieldPassword.secureTextEntry = !textfieldPassword.secureTextEntry // Workaround for dot+whitespace problem if !textfieldPassword.secureTextEntry { let tempString = textfieldPassword.text textfieldPassword.text = nil textfieldPassword.text = tempString } textfieldPassword.font = UIFont.systemFontOfSize(14) if textfieldPassword.secureTextEntry { showHideButton.setImage(UIImage(named: "EyeClosed"), forState: .Normal) } else { showHideButton.setImage(UIImage(named: "EyeOpen"), forState: .Normal) } textfieldPassword.becomeFirstResponder() } </code></pre>
0debug
Put a print in a class method? : here I have a stupid question, but can we put a print in a method of class? (PEP8) I know it is better to make a return. But I have to turn a big python file into a class ... class Test: def __init__(self,name): self.name = name self.r = str def tester(self): print('hello') print(self.name) r = Test('pascal') r.tester()
0debug
What are the pros and cons of using AWS CodePipeline vs Jenkins : <p>What are the pros and cons of using AWS CodePipeline vs Jenkins?</p> <p>I can't see a whole lot of info on the interwebs (apart from <a href="https://stackshare.io/stackups/jenkins-vs-aws-codepipeline" rel="noreferrer">https://stackshare.io/stackups/jenkins-vs-aws-codepipeline</a>). As far as I can see they are as follows:</p> <p>AWS CodePipeline Pros</p> <ul> <li>Web-based </li> <li>integrated with AWS</li> <li>simple to setup (as web-based)</li> </ul> <p>AWS CodePipeline Cons</p> <ul> <li>can't be used to set up code repos locally</li> </ul> <p>Jenkins Pros</p> <ul> <li>standalone software</li> <li>can be used for many systems (other than AWS)</li> <li>many options for setup (e.g. plugins)</li> <li>can be used to setup code repos locally </li> </ul> <p>Any other major differences that people can use to make an informed choice?</p>
0debug
Search in object array in Swift : <p>I have code:</p> <pre><code>func getDataToProductView(){ let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let path = documentsDir.appendingPathComponent((AppGlobalManager.sharedManager.loggedUser?.selectedLanguage)! + "/json/products.json") do { let data = try Data(contentsOf: path) let decoder = JSONDecoder() let productsTmpObjectArray = try decoder.decode([Products].self, from: data) productCount.text = String(productsObjectArray.count) } catch { print("ProductViewControler - Error 102: Problem with parse file. \(error)") } } struct ProductObject : Codable { let palletHeight : Double? let layerPallet : Int? let prepCombisteamer : String? let id : Int? let temporaryWorlds : [String]? let temporarySegments : [String]? let sunFlower : Bool? let inPieces : Bool? let noBox : Int? let prepFryingPan : String? let packageContents : Double? let carbohydrates : Double? let eanBox : String? // Int let kcal : Int? let markedAsFavourite1 : Bool? let temporaryPodSegmentyRynku : [String]? let prepPot : String? let prepMicrowave : String? let boxLayer : Int? let code : String? // Int let prepDeepFryer : String? let name : String? let temporaryConcepts : [String]? let active : Bool? let temporarySegmentyRynku : [String]? let shelfLifeTimeFrame : String? let changeTime : ChangeTime? let palletWeight : Double? let markedAsFavourite2 : Bool? let kj : Int? let langVersions : [LangVersions]? let proteins : Double? // Int let regions : [Int]? let containsGluten : Bool? let markedAsFavourite3 : Bool? let eanFoil : String? // Int let shelfLife : String? // Int let contentPerBox : Int? let prepOven : String? } </code></pre> <p>and sample object:</p> <pre><code>{ "palletHeight": 190, "layerPallet": 6, "prepCombisteamer": "10-15 min / 220C", "id": 152, "temporaryWorlds": [ "ALWAYS_EVERYWHERE" ], "temporarySegments": [ "FRIES" ], "sunFlower": false, "inPieces": false, "noBox": 54, "prepFryingPan": "", "packageContents": 2.5, "carbohydrates": 24.5, "fat": 4, "eanBox": "8710449999194", "kcal": 150, "markedAsFavourite1": false, "temporaryPodSegmentyRynku": [ "DANIE_GLOWNE", "BUFET" ], "prepPot": "", "prepMicrowave": "", "boxLayer": 9, "code": "302503", "prepDeepFryer": "3-3,5 min / 175C", "name": "CLASSIC Oven Fries 10 mm", "temporaryConcepts": [ "MIX_TO_GO", "SHARE_THE_FUN" ], "active": true, "temporarySegmentyRynku": [ "KANTYNA_CATERING", "HOTEL" ], "shelfLifeTimeFrame": "MONTHS", "changeTime": { "dayOfMonth": 6, "minute": 44, "second": 41, "year": 2017, "month": 3, "hourOfDay": 10 }, </code></pre> <p>I would like to search in my array productsTmpObjectArray objects all objects that:</p> <pre><code>a) temporaryPodSegmentyRynku == DANIE_GLOWNE b) temporaryConcepts = SHARE_THE_FUN c) temporarySegmentyRynku = HOTEL d) fat = 8 </code></pre> <p>Does anyone know how to do it?</p> <p>I thing about something like this:</p> <pre><code>func productsFilter1(array: [Products])-&gt; [Products]{ var tmpProductsArray = [Products]() for product in array{ if product.fat == 8 { tmpProductsArray.append(Products(id: product.id, active: product.active, regions:product.regions, code: product.code, eanFoil: product.eanFoil, eanBox: product.eanBox, noBox: product.noBox, layerPallet: product.layerPallet, boxLayer: product.boxLayer, palletWeight: product.palletWeight, palletHeight: product.palletHeight, packageContents: product.packageContents, contentPerBox: product.contentPerBox, name: product.name, inPieces: product.inPieces, prepDeepFryer: product.prepDeepFryer, prepOven: product.prepOven, prepCombisteamer: product.prepCombisteamer, prepFryingPan: product.prepFryingPan, prepPot: product.prepPot, prepMicrowave: product.prepMicrowave, shelfLife: product.shelfLife, shelfLifeTimeFrame: product.shelfLifeTimeFrame, kj: product.kj, kcal: product.kcal, proteins: product.proteins, carbohydrates: product.carbohydrates, fat: product.fat, sunFlower: product.sunFlower, containsGluten: product.containsGluten, pieceWeight: product.pieceWeight, numberOfPiecesInPackage: product.numberOfPiecesInPackage, temporaryWorlds: product.temporaryWorlds, temporaryConcepts: product.temporaryConcepts, temporarySegments: product.temporarySegments, temporaryPodSegmentyRynku: product.temporaryPodSegmentyRynku, temporarySegmentyRynku: product.temporarySegmentyRynku, langVersions: product.langVersions, changeTime: product.changeTime, markedAsFavourite1: product.markedAsFavourite1, markedAsFavourite2: product.markedAsFavourite2, markedAsFavourite3: product.markedAsFavourite3)) } } return tmpProductsArray } </code></pre> <p>Would this solution be ok? For points: a, b, c, it's best to do separate search functions? How do you do a search for points a, b and c?</p>
0debug
How to add Channel to my .NET Bot? : I have created a Microsoft Bot, a C# and Web API application. Added Intent in Luis, able to do unit test using Bot Framework Simulator. I want to add channel like Skype for Business, Skype to this, what should be my next step.
0debug
Expantion of alias “a“ failed;’version’ is not a git command : What’s problem..this on the Mac Input: “ git config —global alias.a version”,and then error occurs: Expantion of alias “a“ failed;’version’ is not a git command
0debug
What to do, If a variable inside an foreach loop in PHP : <p>This is my code:</p> <pre><code>$recommendations_name_list = explode(',',$result[$x]["recommendations_title"]); $recommendations_vote_average = explode(',',$result[$x]["recommendations_vote_average"]); foreach( $recommendations_name_list as $index =&gt; $recommendations_title ) { echo'&lt;p&gt;'.$recommendations_title.'&lt;/p&gt; &lt;p&gt;'.$recommendations_vote_average[$index].'&lt;/p&gt;'; } </code></pre> <p>Now, If in the 9th loop<code>$recommendations_title</code> have some value but <code>$recommendations_vote_average[$index]</code> do not have a value. Then I get this error:</p> <blockquote> <p>Notice: Undefined offset: 9</p> </blockquote>
0debug
Android app from phone to android studio? : Might be a stupid question, but if I made an app and installed it on my phone and it's working on my phone, can I get that app back into android studio? Formatted my hard drive and didn't backup the project. It's not a big project but it'd be nice if I could get it back easily.
0debug
How can I learn a large amount of java concepts in a short amount of time? : <p>So I recently learned about a scholarship that my school has set up with CISCO and in order for me to even be acknowledged for the scholarship I have to learn the following JAVA concepts:</p> <ul> <li>Mathematical Functions </li> <li>Characters</li> <li>Strings </li> <li>Loops</li> <li>Methods</li> </ul> <p>I'm still learning Java so this is sort of intimidating given the timeline that I have from today until next Wednesday (3-29-17.)</p> <p>Could someone give me insight to how you break down the learning of new material in a short amount of time? </p>
0debug
I dont know how to make mysqli query work and there are no errors showing : <p>I have this problem with my code. I have a database created in myphpadmin , the program connects to it, but when i try to use mysqli_query it keeps showing "not executed". Can you help me? Maybe i'm missing something</p> <pre><code>&lt;?php $mysqli_host='localhost'; $mysqli_user='root'; $mysqli_password=''; $conexiune=@mysqli_connect($mysqli_host,$mysqli_user,$mysqli_password); @mysqli_select_db('materiale',$conexiune); if(!$conexiune=@mysqli_connect($mysqli_host,$mysqli_user,$mysqli_password)) { die('cant connect'); } else { echo 'connection success&lt;br&gt;'; } if($is_query_run=@mysqli_query('SELECT * FROM `user`',$conexiune)) { echo 'query executed'; } else { echo 'not executed' ; } </code></pre> <p>?></p> <p>I need to fetch the information from the database bot it will not work if the query isn't working</p>
0debug
static int file_read(URLContext *h, unsigned char *buf, int size) { FileContext *c = h->priv_data; int r = read(c->fd, buf, size); return (-1 == r)?AVERROR(errno):r; }
1threat
Regex to Find email id from a long string : I have many thunderbird exported file. I need to collect the email id from each file. All emails are bounced email id, thats why we need to remove them from our system. The String :- Reporting-MTA: dsn; a27-19.smtp-out.us-west-2.amazonses.com Action: failed Final-Recipient: rfc822; mrinalkantighosh005@gmail.com Diagnostic-Code: smtp; 550-5.1.1 The email account that you tried to reach does not exist. Please try Every email id start with Final-Recipient: rfc822; mrinalkantighosh005@gmail.com So the format is:- Final-Recipient: rfc822; EMAIL_ID_HERE Can you guys please let me know the regex to extract the email id. Thanks in advance.
0debug
Why is std::less better than "<"? : <p>C++ primer, 5th, 14.8.2, Using a Library Function Object with the Algorithms:</p> <pre><code>vector&lt;string *&gt; nameTable; // vector of pointers // error: the pointers in nameTable are unrelated, so &lt; is undefined sort(nameTable.begin(), nameTable.end(), [](string *a, string *b) { return a &lt; b; }); // ok: library guarantees that less on pointer types is well defined sort(nameTable.begin(), nameTable.end(), less&lt;string*&gt;()); </code></pre> <p>Then I checked the std::less implementation:</p> <pre><code>template&lt;typename _Tp&gt; struct less : public binary_function&lt;_Tp, _Tp, bool&gt; { bool operator()(const _Tp&amp; __x, const _Tp&amp; __y) const { return __x &lt; __y; } }; </code></pre> <p>I found out that std::less also use operator &lt; to do the work, so why &lt; is undefined and library guarantees that less on pointer types is well defined, why is std:less recommended, and why is std::less better than &lt;.</p>
0debug