problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
Declare an array in TypeScript : <p>I'm having trouble either declaring or using a boolean array in Typescript, not sure which is wrong. I get an <code>undefined</code> error. Am I supposed to use JavaScript syntax or declare a new Array object? </p>
<p>Which one of these is the correct way to create the array?</p>
<pre><code>private columns = boolean[];
private columns = [];
private columns = new Array<boolean>();
</code></pre>
<p>How would I initialize all the values to be false?</p>
<p>How would I access the values, can I access them like, <code>columns[i] = true;</code>..?</p>
| 0debug |
VueJS props are undefined in component : <p>I am trying to integrate VueJS with my frontend for my Django applications. I have the following Vue code in a javascript file:</p>
<pre><code>window.onload = function() {
Vue.component('discuss-post', {
props: ['post'],
template: `<div class="card">
<div class="grid-x margin-x">
<div class="cell small-4">
<img class="avatar-img" :src="post.by.profile.img_url">
<p style="font-family: Abel;font-size: 24px">{{ post.by }}</p>
</<div>
</div>
<div class="grid-x margin-x">
<div class="cell small-4">
<p style="font-family: Abel;font-size: 18px">{{ post.content }}</p>
</div>
</div>
</div>`
})
var postDiv = new Vue({
el: "#post-div"
})
}
</code></pre>
<p>And the following code in an HTML file:</p>
<pre><code> <div class="card-section">
{% for feed in feeds %}
{% for post in feed %}
<div id="post-div">
<discuss-post post="{{ post }}"></discuss-post>
</div>
{% endfor %}
{% endfor %}
</div>
</code></pre>
<p>However, when I load my page I get these errors in my console:</p>
<p><a href="https://i.stack.imgur.com/ClIv0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ClIv0.png" alt="enter image description here"></a></p>
<p>What in my code could be causing these errors to be raised?</p>
| 0debug |
static int g2m_init_buffers(G2MContext *c)
{
int aligned_height;
if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {
c->framebuf_stride = FFALIGN(c->width * 3, 16);
aligned_height = FFALIGN(c->height, 16);
av_free(c->framebuf);
c->framebuf = av_mallocz(c->framebuf_stride * aligned_height);
if (!c->framebuf)
return AVERROR(ENOMEM);
}
if (!c->synth_tile || !c->jpeg_tile ||
c->old_tile_w < c->tile_width ||
c->old_tile_h < c->tile_height) {
c->tile_stride = FFALIGN(c->tile_width, 16) * 3;
aligned_height = FFALIGN(c->tile_height, 16);
av_free(c->synth_tile);
av_free(c->jpeg_tile);
av_free(c->kempf_buf);
av_free(c->kempf_flags);
c->synth_tile = av_mallocz(c->tile_stride * aligned_height);
c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height);
c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height
+ FF_INPUT_BUFFER_PADDING_SIZE);
c->kempf_flags = av_mallocz( c->tile_width * aligned_height);
if (!c->synth_tile || !c->jpeg_tile ||
!c->kempf_buf || !c->kempf_flags)
return AVERROR(ENOMEM);
}
return 0;
}
| 1threat |
How can I send message to specific users phone by using Phyton? : I have established relationship between Postgresql and Phyton. I provide that send e-mail to user with used Phyton. I want to send message to specific users phone. Can you help me, please? | 0debug |
Firestore security rules check if reference exists : <p>I'm wondering how I could check if a document value is a reference to another document and the document exists using firebase security rules.</p>
<p>What I tried:</p>
<pre><code>function validate(document) {
return exists(document.reference)
}
match /collection/{document} {
allow read: if request.auth != null;
allow create, update: if isAdmin(request.auth.uid) && validate(request.resource.data);
}
</code></pre>
<p>As this didn't work, I tried to figure out what type <code>document.ref</code> is.
Unfortunately, it doesn't seem to have any type of the listed ones here:
<a href="https://firebase.google.com/docs/firestore/reference/security/?authuser=0#data_types" rel="noreferrer">https://firebase.google.com/docs/firestore/reference/security/?authuser=0#data_types</a></p>
<p>I tried <code>path</code> as it's the most obvious one to work with exists.
I didn't expect it to work.
Another guess was maybe <code>map</code> or <code>string</code>.
Both were incorrect.</p>
<p>As I don't have a clue what this could be and there is nothing documented how I can convert the reference to a path, I now have to ask here.</p>
<p>Has anyone found a solution to this?</p>
<p>TL;DR:</p>
<p>I need to check using Firestore security rules whether a reference saved in a document is present and it exists in the database.</p>
<p>Thanks,
Dennis</p>
| 0debug |
How to use s3 with Apache spark 2.2 in the Spark shell : <p>I'm trying to load data from an Amazon AWS S3 bucket, while in the Spark shell.</p>
<p>I have consulted the following resources:</p>
<p><a href="https://stackoverflow.com/questions/43654319/parsing-files-from-amazon-s3-with-apache-spark">Parsing files from Amazon S3 with Apache Spark</a></p>
<p><a href="https://stackoverflow.com/questions/30385981/how-to-access-s3a-files-from-apache-spark">How to access s3a:// files from Apache Spark?</a></p>
<p><a href="https://community.hortonworks.com/articles/25523/hdp-240-and-spark-160-connecting-to-aws-s3-buckets.html" rel="noreferrer">Hortonworks Spark 1.6 and S3</a></p>
<p><a href="https://www.cloudera.com/documentation/enterprise/5-5-x/topics/spark_s3.html" rel="noreferrer">Cloudera</a></p>
<p><a href="https://gist.github.com/tobilg/e03dbc474ba976b9f235" rel="noreferrer">Custom s3 endpoints</a></p>
<p>I have downloaded and unzipped <a href="https://spark.apache.org/downloads.html" rel="noreferrer">Apache Spark 2.2.0</a>. In <code>conf/spark-defaults</code> I have the following (note I replaced <code>access-key</code> and <code>secret-key</code>):</p>
<pre><code>spark.hadoop.fs.s3a.impl=org.apache.hadoop.fs.s3a.S3AFileSystem
spark.hadoop.fs.s3a.access.key=access-key
spark.hadoop.fs.s3a.secret.key=secret-key
</code></pre>
<p>I have downloaded <code>hadoop-aws-2.8.1.jar</code> and <code>aws-java-sdk-1.11.179.jar</code> from <a href="https://mvnrepository.com" rel="noreferrer">mvnrepository</a>, and placed them in the <code>jars/</code> directory. I then start the Spark shell:</p>
<pre><code>bin/spark-shell --jars jars/hadoop-aws-2.8.1.jar,jars/aws-java-sdk-1.11.179.jar
</code></pre>
<p>In the shell, here is how I try to load data from the S3 bucket:</p>
<pre><code>val p = spark.read.textFile("s3a://sparkcookbook/person")
</code></pre>
<p>And here is the error that results:</p>
<pre><code>java.lang.NoClassDefFoundError: org/apache/hadoop/fs/GlobalStorageStatistics$StorageStatisticsProvider
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.apache.hadoop.conf.Configuration.getClassByNameOrNull(Configuration.java:2134)
at org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:2099)
at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2193)
at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2654)
at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2667)
at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:94)
at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2703)
at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2685)
at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:373)
at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
</code></pre>
<p>When I instead try to start the Spark shell as follows:</p>
<pre><code>bin/spark-shell --packages org.apache.hadoop:hadoop-aws:2.8.1
</code></pre>
<p>Then I get two errors: one when the interperter starts, and another when I try to load the data. Here is the first:</p>
<pre><code>:: problems summary ::
:::: ERRORS
unknown resolver null
unknown resolver null
unknown resolver null
unknown resolver null
unknown resolver null
unknown resolver null
:: USE VERBOSE OR DEBUG MESSAGE LEVEL FOR MORE DETAILS
</code></pre>
<p>And here is the second:</p>
<pre><code>val p = spark.read.textFile("s3a://sparkcookbook/person")
java.lang.IllegalAccessError: tried to access method org.apache.hadoop.metrics2.lib.MutableCounterLong.<init>(Lorg/apache/hadoop/metrics2/MetricsInfo;J)V from class org.apache.hadoop.fs.s3a.S3AInstrumentation
at org.apache.hadoop.fs.s3a.S3AInstrumentation.streamCounter(S3AInstrumentation.java:195)
at org.apache.hadoop.fs.s3a.S3AInstrumentation.streamCounter(S3AInstrumentation.java:216)
at org.apache.hadoop.fs.s3a.S3AInstrumentation.<init>(S3AInstrumentation.java:139)
at org.apache.hadoop.fs.s3a.S3AFileSystem.initialize(S3AFileSystem.java:174)
at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2669)
at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:94)
at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2703)
at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2685)
at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:373)
at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
at org.apache.spark.sql.execution.datasources.DataSource.hasMetadata(DataSource.scala:301)
at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:344)
at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:152)
at org.apache.spark.sql.DataFrameReader.text(DataFrameReader.scala:506)
at org.apache.spark.sql.DataFrameReader.textFile(DataFrameReader.scala:542)
at org.apache.spark.sql.DataFrameReader.textFile(DataFrameReader.scala:515)
</code></pre>
<p>Could someone suggest how to get this working? Thanks.</p>
| 0debug |
Normalizr - How to generate slug/id related to parent entity : <p>How can I assign id/slug related to the entity's parent using <a href="https://github.com/paularmstrong/normalizr" rel="noreferrer">normalizr</a>?</p>
<p>Example:</p>
<p>API Response for a user call:</p>
<pre><code>{
id: '12345',
firstName: 'John',
images: [
{
url: 'https://www.domain.com/image0',
name: 'image0'
},
{
url: 'https://www.domain.com/image1',
name: 'image1'
}
]
}
</code></pre>
<p>I could define my schemas in the following way:</p>
<pre><code>const image = new Schema('images');
const user = new Schema('users');
user.define({
images: arrayOf(image)
})
</code></pre>
<p>The problem is that images don't have an <code>id</code> property, so normalizr will not be able to distinguish them unless we provide an <code>id</code> property. Of course, we could do something like </p>
<pre><code>const image = new Schema('images', { idAttribute: uuid.v4() });
</code></pre>
<p>and generate unique identifiers.</p>
<p>Suppose we receive a user update and an image's name has been updated. Because we generate unique identifiers in every normalization, we are not able to identify and update the existing image.</p>
<p>I need a way to reference the parent entity (user) in the image entity (either in its id/slug like <code>12345-image0</code>, <code>12345-image1</code> or as a separate property.</p>
<p>What would be the optimal way to achieve this?</p>
| 0debug |
Interface for dynamic key in typescript : <p>I have an Object like this that is created by underscore's <code>_.groupBy()</code> method.</p>
<pre><code>myObject = {
"key" : [{Object},{Object2},{Object3}],
"key2" : [{Object4},{Object5},{Object6}],
...
}
</code></pre>
<p>How would I define that as an Interface with TypeScript?
i don't want to simply define it as <code>myObject:Object = { ...</code> but rather have an own type for it.</p>
| 0debug |
static int xan_decode_frame_type1(AVCodecContext *avctx, AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
XanContext *s = avctx->priv_data;
uint8_t *ybuf, *src = s->scratch_buffer;
int cur, last;
int i, j;
int ret;
if ((ret = xan_decode_chroma(avctx, avpkt)) != 0)
return ret;
ret = xan_unpack_luma(buf + 16, avpkt->size - 16, src,
s->buffer_size >> 1);
if (ret) {
av_log(avctx, AV_LOG_ERROR, "Luma decoding failed\n");
return ret;
}
ybuf = s->y_buffer;
for (i = 0; i < avctx->height; i++) {
last = (ybuf[0] + (*src++ << 1)) & 0x3F;
ybuf[0] = last;
for (j = 1; j < avctx->width - 1; j += 2) {
cur = (ybuf[j + 1] + (*src++ << 1)) & 0x3F;
ybuf[j] = (last + cur) >> 1;
ybuf[j+1] = cur;
last = cur;
}
ybuf[j] = last;
ybuf += avctx->width;
}
src = s->y_buffer;
ybuf = s->pic.data[0];
for (j = 0; j < avctx->height; j++) {
for (i = 0; i < avctx->width; i++)
ybuf[i] = (src[i] << 2) | (src[i] >> 3);
src += avctx->width;
ybuf += s->pic.linesize[0];
}
return 0;
}
| 1threat |
Is there a way to write an `if case` statement as an expression? : <p>Consider this code:</p>
<pre><code>enum Type {
case Foo(Int)
case Bar(Int)
var isBar: Bool {
if case .Bar = self {
return true
} else {
return false
}
}
}
</code></pre>
<p>That's gross. I would like to write something like this instead:</p>
<pre><code>enum Type {
case Foo(Int)
case Bar(Int)
var isBar: Bool {
return case .Bar = self
}
}
</code></pre>
<p>But such a construct does not seem to exist in Swift, or I cannot find it.</p>
<p>Since there's data associated with each case, I don't think it's possible to implement the <code>~=</code> operator (or any other helper) in a way that's equivalent to the above expression. And in any case, <code>if case</code> statements exist for free for all enums, and don't need to be manually implemented.</p>
<p>Thus my question: is there any more concise/declarative/clean/idiomatic way to implement <code>isBar</code> than what I have above? Or, more directly, is there any way to express <code>if case</code> <em>statements</em> as Swift <em>expressions</em>?</p>
| 0debug |
com.android.volley.NoConnectionError - Android emulator with Charles Proxy : <p>I want to proxy network traffic for an Android emulator. </p>
<p>I can't seem to get it to work. </p>
<p>My emulator is booted up using this: </p>
<pre><code>emulator @Nexus_5X_API_23 -http-proxy 10.0.1.17:8888
</code></pre>
<p>The IP and port points to what Charles reports in the Help menu. </p>
<p>The SSL certificate is installed. I can open the emulator browser and Charles shows me all traffic. The browser updates as usual. </p>
<p>All seems good so far. </p>
<p>Now I attempt to run my app. My first network call goes out successfully through Charles. The response returns and Charles displays it. However the response isn't passed to the app successfully. </p>
<p>I've set a breakpoint in the error callback and I can see a <code>com.android.volley.NoConnectionError</code> which is caused by <code>java.io.IOException: unexpected end of stream on Connection</code>. </p>
<p>Why doesn't Charles pass the result back back properly to the app? </p>
<p>Do I need to do what's defined at <a href="https://www.charlesproxy.com/documentation/configuration/browser-and-system-configuration">the end of the configuration page on Charles</a>? </p>
<pre><code>HttpHost httpproxy = new HttpHost("192.168.0.101", 8888, "http");
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,httpproxy);
</code></pre>
<p>This doesn't seem correct - what am I missing? </p>
| 0debug |
static void set_guest_connected(VirtIOSerialPort *port, int guest_connected)
{
VirtConsole *vcon = VIRTIO_CONSOLE(port);
DeviceState *dev = DEVICE(port);
if (vcon->chr) {
qemu_chr_fe_set_open(vcon->chr, guest_connected);
}
if (dev->id) {
qapi_event_send_vserport_change(dev->id, guest_connected,
&error_abort);
}
}
| 1threat |
static void release_keys(void *opaque)
{
int i;
for (i = 0; i < keycodes_size; i++) {
if (keycodes[i] & 0x80) {
kbd_put_keycode(0xe0);
}
kbd_put_keycode(keycodes[i]| 0x80);
}
free_keycodes();
}
| 1threat |
static int pcm_bluray_parse_header(AVCodecContext *avctx,
const uint8_t *header)
{
static const uint8_t bits_per_samples[4] = { 0, 16, 20, 24 };
static const uint32_t channel_layouts[16] = {
0, AV_CH_LAYOUT_MONO, 0, AV_CH_LAYOUT_STEREO, AV_CH_LAYOUT_SURROUND,
AV_CH_LAYOUT_2_1, AV_CH_LAYOUT_4POINT0, AV_CH_LAYOUT_2_2, AV_CH_LAYOUT_5POINT0,
AV_CH_LAYOUT_5POINT1, AV_CH_LAYOUT_7POINT0, AV_CH_LAYOUT_7POINT1, 0, 0, 0, 0
};
static const uint8_t channels[16] = {
0, 1, 0, 2, 3, 3, 4, 4, 5, 6, 7, 8, 0, 0, 0, 0
};
uint8_t channel_layout = header[2] >> 4;
if (avctx->debug & FF_DEBUG_PICT_INFO)
av_dlog(avctx, "pcm_bluray_parse_header: header = %02x%02x%02x%02x\n",
header[0], header[1], header[2], header[3]);
avctx->bits_per_coded_sample = bits_per_samples[header[3] >> 6];
if (!avctx->bits_per_coded_sample) {
av_log(avctx, AV_LOG_ERROR, "unsupported sample depth (0)\n");
return -1;
}
avctx->sample_fmt = avctx->bits_per_coded_sample == 16 ? AV_SAMPLE_FMT_S16 :
AV_SAMPLE_FMT_S32;
if (avctx->sample_fmt == AV_SAMPLE_FMT_S32)
avctx->bits_per_raw_sample = avctx->bits_per_coded_sample;
switch (header[2] & 0x0f) {
case 1:
avctx->sample_rate = 48000;
break;
case 4:
avctx->sample_rate = 96000;
break;
case 5:
avctx->sample_rate = 192000;
break;
default:
avctx->sample_rate = 0;
av_log(avctx, AV_LOG_ERROR, "unsupported sample rate (%d)\n",
header[2] & 0x0f);
return -1;
}
avctx->channel_layout = channel_layouts[channel_layout];
avctx->channels = channels[channel_layout];
if (!avctx->channels) {
av_log(avctx, AV_LOG_ERROR, "unsupported channel configuration (%d)\n",
channel_layout);
return -1;
}
avctx->bit_rate = avctx->channels * avctx->sample_rate *
avctx->bits_per_coded_sample;
if (avctx->debug & FF_DEBUG_PICT_INFO)
av_dlog(avctx,
"pcm_bluray_parse_header: %d channels, %d bits per sample, %d kHz, %d kbit\n",
avctx->channels, avctx->bits_per_coded_sample,
avctx->sample_rate, avctx->bit_rate);
return 0;
}
| 1threat |
def first_Repeated_Char(str):
h = {}
for ch in str:
if ch in h:
return ch;
else:
h[ch] = 0
return '\0' | 0debug |
Move view when keyboard displayed over uitextfield : I have looked around and found [this][1] post about moving a view when a keyboard appears. It works great, and moves the keyboard anytime I click in a UItextfield. The issue is that I Have three UITextfields, and the keyboard should only move when it is going to present over a uitextfield. I looked at the apple [documentation][2] on this as well, and found some useful but I am still not getting the desired functionality.
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
var aRect = self.view.frame;
aRect.size.height -= keyboardSize.size.height
if self.view.frame.origin.y == 0{
if aRect.contains(activeField.frame.origin){
self.view.frame.origin.y -= keyboardSize.height
}
}
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
activeField = textField
}
func textFieldDidEndEditing(_ textField: UITextField) {
activeField = nil
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
}
From the apple documentation I just took the piece where I create the `aRect`, and then check if the points intersect with the `contains` function. I would expect this to then make the view move only when the keyboard were to overlap with a textfield, and keep the view in place otherwise. For some reason that I don't fully understand, this is not the case. The keyboard will move the view in the case where any textfield is clicked (even though for some it shouldn't). I have played around with it a bit now and tried debugging but have been unsuccessful. Any ideas?
[1]: http://stackoverflow.com/questions/26070242/move-view-with-keyboard-using-swift?rq=1
[2]: https://developer.apple.com/library/content/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
| 0debug |
Importing and changing variables from another file : <p>Okay...</p>
<p>I have searched and searched looking for an answer that directly answers my question, but have had no success. My problem is pretty straight forward and I honestly thought there would have been a more direct answer out there. Please keep in mind I am still relatively new to the language, and am still learning.</p>
<p><em>So I will use <code>fileA</code> and <code>fileB</code> as my two files, and <code>x</code> as my example variable.</em> Variable <code>x</code> is contained in <code>fileB</code>. How do I go about importing variable <code>x</code> into <code>fileA</code>, <strong>then</strong> change <code>x</code> to another value via <code>raw_input</code>, <strong>and then</strong> have the variable <code>x</code> update in <code>fileB</code> with the new value?</p>
<p>I'm not sure if this is even possible, but I would sure like to think so. I am using python 2.7.11, thank you in advanced.</p>
| 0debug |
How to detect Internet Explorer 11 and below versions? : <p>I'm wondering how I could detect if the user viewing my website is using Internet Explorer 11 or below versions with Javascript.</p>
<p><strong>It should be compatible and works with all these versions.</strong></p>
<p>How to achieve that ?</p>
| 0debug |
static int mpeg_decode_slice(AVCodecContext *avctx,
AVFrame *pict,
int start_code,
UINT8 *buf, int buf_size)
{
Mpeg1Context *s1 = avctx->priv_data;
MpegEncContext *s = &s1->mpeg_enc_ctx;
int ret;
start_code = (start_code - 1) & 0xff;
if (start_code >= s->mb_height){
fprintf(stderr, "slice below image (%d >= %d)\n", start_code, s->mb_height);
return DECODE_SLICE_ERROR;
}
s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
s->last_dc[1] = s->last_dc[0];
s->last_dc[2] = s->last_dc[0];
memset(s->last_mv, 0, sizeof(s->last_mv));
if (s->first_slice) {
s->first_slice = 0;
if(MPV_frame_start(s, avctx) < 0)
return DECODE_SLICE_FATAL_ERROR;
if(s->avctx->debug&FF_DEBUG_PICT_INFO){
printf("qp:%d fc:%2d%2d%2d%2d %s %s %s %s dc:%d pstruct:%d fdct:%d cmv:%d qtype:%d ivlc:%d rff:%d %s\n",
s->qscale, s->mpeg_f_code[0][0],s->mpeg_f_code[0][1],s->mpeg_f_code[1][0],s->mpeg_f_code[1][1],
s->pict_type == I_TYPE ? "I" : (s->pict_type == P_TYPE ? "P" : (s->pict_type == B_TYPE ? "B" : "S")),
s->progressive_sequence ? "pro" :"", s->alternate_scan ? "alt" :"", s->top_field_first ? "top" :"",
s->intra_dc_precision, s->picture_structure, s->frame_pred_frame_dct, s->concealment_motion_vectors,
s->q_scale_type, s->intra_vlc_format, s->repeat_first_field, s->chroma_420_type ? "420" :"");
}
}
init_get_bits(&s->gb, buf, buf_size);
s->qscale = get_qscale(s);
while (get_bits1(&s->gb) != 0) {
skip_bits(&s->gb, 8);
}
s->mb_x=0;
for(;;) {
int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
if (code < 0)
return -1;
if (code >= 33) {
if (code == 33) {
s->mb_x += 33;
}
} else {
s->mb_x += code;
break;
}
}
s->mb_y = start_code;
s->mb_incr= 1;
for(;;) {
s->dsp.clear_blocks(s->block[0]);
ret = mpeg_decode_mb(s, s->block);
dprintf("ret=%d\n", ret);
if (ret < 0)
return -1;
MPV_decode_mb(s, s->block);
if (++s->mb_x >= s->mb_width) {
ff_draw_horiz_band(s);
s->mb_x = 0;
s->mb_y++;
PRINT_QP("%s", "\n");
}
PRINT_QP("%2d", s->qscale);
if (s->mb_incr == 0) {
s->mb_incr = 1;
for(;;) {
int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
if (code < 0)
goto eos;
if (code >= 33) {
if (code == 33) {
s->mb_incr += 33;
}
} else {
s->mb_incr += code;
break;
}
}
}
if(s->mb_y >= s->mb_height){
fprintf(stderr, "slice too long\n");
return DECODE_SLICE_ERROR;
}
}
eos:
emms_c();
if (
s->mb_y == s->mb_height) {
if(s->mpeg2)
s->qscale >>=1;
MPV_frame_end(s);
if (s->pict_type == B_TYPE || s->low_delay) {
*pict= *(AVFrame*)&s->current_picture;
} else {
s->picture_number++;
if (s->last_picture.data[0] == NULL) {
return DECODE_SLICE_OK;
} else {
*pict= *(AVFrame*)&s->last_picture;
}
}
return DECODE_SLICE_EOP;
} else {
return DECODE_SLICE_OK;
}
}
| 1threat |
static void RENAME(lumRangeToJpeg)(int16_t *dst, int width)
{
int i;
for (i = 0; i < width; i++)
dst[i] = (FFMIN(dst[i],30189)*19077 - 39057361)>>14;
}
| 1threat |
connection.query('SELECT * FROM users WHERE username = ' + input_string) | 1threat |
how to insert javascript as parameter into php function? : <p>i want to call php function inside javascript like this. i want value inside array r can be added to my_func() as parameter. but i get an error when do this.</p>
<pre><code>for(i=0;i<r.length;i++){
var distance = <?php echo my_func(+r[i].coordinate+);?>;
}
</code></pre>
<p>or</p>
<pre><code>for(i=0;i<r.length;i++){
var distance = <?php echo my_func(?>r[i].coordinate<?php );?>;
}
</code></pre>
<p>If any one have an idea to help I really appreciate it because I need it so much, and thanks to all.</p>
| 0debug |
Update/change roles claim (or any other claim) in JWT : <p>I'm storing user roles inside a JWT (to restrict API endpoints). The roles can be changed by an administrator.</p>
<p>If a role is changed. How am I supposed to reflect this inside all tokens? I've thought about a couple of solutions:</p>
<ul>
<li><p>If I'd use refresh tokens, the user would have to wait until the expiration date of the access token is expired.</p></li>
<li><p>I could keep a record of changed user IDs and check every request, and then return a new token if the user has been changed.</p></li>
</ul>
<p>Is there a standard way to do this?</p>
| 0debug |
Mutating nested object/arrays as states in React : <p>I am using React components which look like this (a simplified version of the components I used, below).</p>
<p>My question is: how to make the same but using this.setState?
The below code works, but I am mutating the state directly, and I am receiving the following warning:</p>
<blockquote>
<p>Do not mutate state directly. Use setState()</p>
</blockquote>
<pre><code>class App extends Component {
constructor(props) {
super(props);
this.state = {
playerState: [
{
name: 'Jack',
hp: 30
},{
name: 'Alan',
hp: 28
}
],
};
}
lowerPlayerHealth = (index) => () => {
this.state.playerState[index].hp = this.state.playerState[index].hp - 1
this.forceUpdate();
}
render() {
return (
<div className="App">
<p>Player 1: {this.state.playerState[0].name}</p>
<p>Health: {this.state.playerState[0].hp}</p>
<button onClick={this.lowerPlayerHealth(0)}>Hit player 1</button>
<p>Player 2: {this.state.playerState[1].name}</p>
<p>Health: {this.state.playerState[1].hp}</p>
<button onClick={this.lowerPlayerHealth(1)}>Hit player 2</button>
</div>
);
}
}
</code></pre>
<p>When rendered, it looks like this:</p>
<p><a href="https://i.stack.imgur.com/3aRXA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3aRXA.jpg" alt="enter image description here"></a></p>
| 0debug |
static void ps2_mouse_event(DeviceState *dev, QemuConsole *src,
InputEvent *evt)
{
static const int bmap[INPUT_BUTTON__MAX] = {
[INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
[INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
[INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
};
PS2MouseState *s = (PS2MouseState *)dev;
InputMoveEvent *move;
InputBtnEvent *btn;
if (!(s->mouse_status & MOUSE_STATUS_ENABLED))
return;
switch (evt->type) {
case INPUT_EVENT_KIND_REL:
move = evt->u.rel;
if (move->axis == INPUT_AXIS_X) {
s->mouse_dx += move->value;
} else if (move->axis == INPUT_AXIS_Y) {
s->mouse_dy -= move->value;
}
break;
case INPUT_EVENT_KIND_BTN:
btn = evt->u.btn;
if (btn->down) {
s->mouse_buttons |= bmap[btn->button];
if (btn->button == INPUT_BUTTON_WHEEL_UP) {
s->mouse_dz--;
} else if (btn->button == INPUT_BUTTON_WHEEL_DOWN) {
s->mouse_dz++;
}
} else {
s->mouse_buttons &= ~bmap[btn->button];
}
break;
default:
break;
}
}
| 1threat |
static void x86_cpu_apic_create(X86CPU *cpu, Error **errp)
{
APICCommonState *apic;
const char *apic_type = "apic";
if (kvm_apic_in_kernel()) {
apic_type = "kvm-apic";
} else if (xen_enabled()) {
apic_type = "xen-apic";
}
cpu->apic_state = DEVICE(object_new(apic_type));
object_property_add_child(OBJECT(cpu), "lapic",
OBJECT(cpu->apic_state), &error_abort);
qdev_prop_set_uint8(cpu->apic_state, "id", cpu->apic_id);
apic = APIC_COMMON(cpu->apic_state);
apic->cpu = cpu;
apic->apicbase = APIC_DEFAULT_ADDRESS | MSR_IA32_APICBASE_ENABLE;
} | 1threat |
Css for my site : [![Site][1]][1]
[1]: https://i.stack.imgur.com/EBDC3.png
In blue there are my div,
I would like with css make sure that the space between the div and the image there is and the button over the black top bar but I do not know how to do, any ideas?
my css
.login_reg{
float: right;
color: #e0e0ba;
width: 200px;
height: 200px;
}
.login_reg button{
color: #FFF;
font-weight: bold;
background-color: Transparent;
background-repeat:no-repeat;
border: none;
cursor:pointer;
overflow: hidden;
outline:none;
} | 0debug |
My lifecycle codes on android studio not compiling : For each callback events (onCreate(), onStart()... ), record what callback event was triggered in the log(use Log.d); the message that is written to log should be defined in “strings.xml” and getResources.getString() should be used to retrieve the message
Implement onSaveInstanceState and onRestoreInstanceState – to track the number of times onSaveInstanceState is being called, in onRestoreInstanceState, print the value to the log file
Tag for “Log” statement should also be defined in strings.xml and set using getResources.getString()
package com.csci235labs.rob_lifecycles;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
String TAG = getResources().getString(R.string.app_name); //Logcat tag
String ActivityState;
int instanceTimes; //number of times instance is called
String Act_keys;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//recover instance state
if(savedInstanceState!=null)
{
ActivityState = savedInstanceState.getString(Act_keys);
}
else
{
instanceTimes=0;
Act_keys="";
}
setContentView(R.layout.activity_main);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
instanceTimes++;
ActivityState=String.valueOf(instanceTimes);
outState.putString(Act_keys,ActivityState);
super.onSaveInstanceState(outState);
}
@Override
protected void onStart() {
super.onStart();
//logs event message
String eventMessage=getResources().getString(R.string.on_start_str);
Log.d(TAG,eventMessage);
}
@Override
protected void onResume() {
super.onResume();
//logs event message
String eventMessage=getResources().getString(R.string.on_resume_str);
Log.d(TAG,eventMessage);
}
@Override
protected void onPause() {
super.onPause();
//logs event message
String eventMessage=getResources().getString(R.string.on_pause_str);
Log.d(TAG,eventMessage);
}
@Override
protected void onStop() {
super.onStop();
//logs event message
String eventMessage=getResources().getString(R.string.on_stop_str);
Log.d(TAG,eventMessage);
}
@Override
protected void onDestroy() {
super.onDestroy();
//logs event message
String eventMessage=getResources().getString(R.string.on_destroy_str);
Log.d(TAG,eventMessage);
}
}
-----------------------------------------------------------
XML Files
| 0debug |
def Check_Solution(a,b,c):
if (a == c):
return ("Yes");
else:
return ("No"); | 0debug |
printing multiple columns of a table using R program : <p>I want to load an excel into r and print multiple columns of the table.</p>
<p>i was able to load the excel file and print the entire table or a single column but unable to print 2 or more columns of the table.</p>
| 0debug |
static int matroska_read_seek(AVFormatContext *s, int stream_index,
int64_t timestamp, int flags)
{
MatroskaDemuxContext *matroska = s->priv_data;
MatroskaTrack *tracks = matroska->tracks.elem;
AVStream *st = s->streams[stream_index];
int i, index, index_sub, index_min;
if (matroska->cues_parsing_deferred) {
matroska_parse_cues(matroska);
matroska->cues_parsing_deferred = 0;
}
if (!st->nb_index_entries)
return 0;
timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
matroska->current_id = 0;
while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
matroska_clear_queue(matroska);
if (matroska_parse_cluster(matroska) < 0)
break;
}
}
matroska_clear_queue(matroska);
if (index < 0)
return 0;
index_min = index;
for (i=0; i < matroska->tracks.nb_elem; i++) {
tracks[i].audio.pkt_cnt = 0;
tracks[i].audio.sub_packet_cnt = 0;
tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
tracks[i].end_timecode = 0;
if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
&& !tracks[i].stream->discard != AVDISCARD_ALL) {
index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
if (index_sub >= 0
&& st->index_entries[index_sub].pos < st->index_entries[index_min].pos
&& st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
index_min = index_sub;
}
}
avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
matroska->current_id = 0;
matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
matroska->skip_to_timecode = st->index_entries[index].timestamp;
matroska->done = 0;
ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
return 0;
} | 1threat |
Backpropagation Optimization: How do I use the derivatives for optimizing the weights and biases? : <p>Given the derivative of the cost function with respect to the weights or biases of the neurons of a neural network, how do I adjust these neurons to minimize the cost function?
Do I just subtract the derivative multiplied by a constant off of the individual weight and bias? If constants are involved how do I know what is reasonable to pick?</p>
| 0debug |
Display dynamic text instead of 3D object in vuforia android sample after image recognition ? : What I want to do is display text instead of 3D object in vuforia sample after image recognition. Like if I scan a shoe image, it should display the name of the shoe, brand and shoe details in real time.
I have browsed a lot but havent been able to find solution to it.A code sample to do it would really help. | 0debug |
static int get_int32_le(QEMUFile *f, void *pv, size_t size)
{
int32_t *cur = pv;
int32_t loaded;
qemu_get_sbe32s(f, &loaded);
if (loaded >= 0 && loaded <= *cur) {
*cur = loaded;
return 0;
}
return -EINVAL;
}
| 1threat |
static inline uint32_t efsctuf(uint32_t val)
{
CPU_FloatU u;
float32 tmp;
u.l = val;
if (unlikely(float32_is_nan(u.f)))
return 0;
tmp = uint64_to_float32(1ULL << 32, &env->vec_status);
u.f = float32_mul(u.f, tmp, &env->vec_status);
return float32_to_uint32(u.f, &env->vec_status);
}
| 1threat |
Which machine learning algorithim should i implement for detecting document type? : <p>We have requirement that we get different type of documents from client like student admission document, marksheet etc. So we want to create an algorithm which identify which document it is. So for this we choose some specific keyword to identify the document type like if admission documents have keywords like <code>fee</code>, <code>admission</code> etc . And <code>marksheet</code> documents keyword like <code>marks</code>, <code>grade</code> etc. So Here we can predict document type by comparing keywords frequency. </p>
<p>For this above requirement which algorithm should implement? I was planning to implement multinomial naive base algorithm. But I can not fit my data in to it. </p>
<p>FYI.. I am using python sklearn module.</p>
<p>Can you please anyone tell me which algorithm should suitable for above requirement. If possible can you also please provide an example with code so that i can easily figure out the solution?</p>
| 0debug |
Combining multiple bash parameter substitutions within same variable set line without using any other commands : <p>Example of what I want to combine:</p>
<pre><code>sVar=$(whoami)
sVar=${sVar^}
sVar=${sVar::1}
</code></pre>
<p>Output:</p>
<ul>
<li>Uppercase first character of username</li>
</ul>
<p>Requirements:</p>
<ul>
<li>One-liner</li>
<li>Do the rest of the processing with parameter substitutions except for the initial command substitution above $(whoami)</li>
</ul>
<p>I realize this can be done with tr, sed, awk, printf, cut, etc.; but that is not the point of the question.</p>
<p>Any help is appreciate!</p>
<p>This isn't the real code or anything indicative of what I am wanting to actually do. I will often default (or try to) to using just one command over concatenating multiple commands.</p>
<p>I've seen other posts state that concatenating within the braces are not possible, but I know that everything is possible.</p>
<p>Please don't:</p>
<ul>
<li>Reference other posts as duplicate that say it's impossible</li>
</ul>
| 0debug |
Android Studio App : Im creating a basic application, in android studio. The code seems to be okay. However, when I run it in Emulator the app doesn't work. Please help me determine what I am missing.
CODE :package com.example.claudia.myapplication;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
@Override// Calculating Body mass index
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button_Calc = (Button) findViewById(R.id.button_Calc);
final EditText Field_Weight = (EditText) findViewById(R.id.Field_Weight);
final EditText Field_Height = (EditText) findViewById(R.id.Field_Height);
final TextView View_Result = (TextView) findViewById(R.id.View_Results);
final TextView View_Msg = (TextView) findViewById(R.id.View_Msg);
button_Calc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double weight;
double height;
double bmi;
String msg = "";
if (Field_Height.getText().toString().equals("") || Field_Weight.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "No Valid Values!", Toast.LENGTH_LONG).show();
weight = Double.parseDouble(Field_Weight.getText().toString());
height = Double.parseDouble(Field_Height.getText().toString());
bmi = height * height;
bmi = weight / bmi;
View_Result.setText(String.valueOf(bmi));
if (bmi < 18.5) {
msg = "Client is Under Weight :(";
} else if (bmi > 18.5 && bmi < 25) {
msg = "Normal :)";
} else if (bmi > 25) {
msg = "Client is Overweight";
}
View_Msg.setText(msg);
}
}
});
// Calculating Calories in and out
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button Cal_calc = (Button) findViewById(R.id.Cal_calc);
final EditText field_cal = (EditText) findViewById(R.id.field_Cal);
final EditText field_burn = (EditText) findViewById(R.id.field_burn);
final TextView View_calRes = (TextView) findViewById(R.id.View_calRes);
final TextView View_calMsg = (TextView) findViewById(R.id.view_calMsg);
Cal_calc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double calories;
double burn;
double CaloricTotal;
String calMsg = "";
if (field_cal.getText().toString().equals("") || field_burn.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "No Valid Values!", Toast.LENGTH_LONG).show();
calories = Double.parseDouble(field_cal.getText().toString());
burn = Double.parseDouble(field_burn.getText().toString());
CaloricTotal = calories * calories;
CaloricTotal = burn / CaloricTotal;
View_calRes.setText(String.valueOf(CaloricTotal));
if (CaloricTotal < 1500) {
calMsg = "Client Needs to consume more Calories :(";
} else if (CaloricTotal > 1500 && CaloricTotal < 2000) {
calMsg = "Client is Normal :)";
} else if (CaloricTotal > 2000) {
calMsg = "Client Needs to consume less calories";
}
View_calMsg.setText(calMsg);
}
}
});
}
}}
RUN Error::
11/01 22:57:40: Launching app
$ adb shell am start -n "com.example.claudia.myapplication/com.example.claudia.myapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 3591 on device emulator-5554
I/art: Not late-enabling -Xcheck:jni (already on)
W/art: Unexpected CPU variant for X86 using defaults: x86
W/System: ClassLoader referenced unknown path: /data/app/com.example.claudia.myapplication-2/lib/x86
I/InstantRun: Instant Run Runtime started. Android package is com.example.claudia.myapplication, real application class is null.
[ 11-01 22:53:09.592 1515: 1538 D/ ]
HostConnection::get() New Host Connection established 0x95618500, tid 1538
W/System: ClassLoader referenced unknown path: /data/app/com.example.claudia.myapplication-2/lib/x86
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.claudia.myapplication, PID: 3591
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.claudia.myapplication/com.example.claudia.myapplication.MainActivity}: java.lang.IllegalStateException: Already attached
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.IllegalStateException: Already attached
at android.support.v4.app.FragmentManagerImpl.attachController(FragmentManager.java:2132)
at android.support.v4.app.FragmentController.attachHost(FragmentController.java:104)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:315)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
at com.example.claudia.myapplication.MainActivity.onCreate(MainActivity.java:63)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Application terminated. | 0debug |
void helper_wrpil(CPUSPARCState *env, target_ulong new_pil)
{
#if !defined(CONFIG_USER_ONLY)
trace_win_helper_wrpil(env->psrpil, (uint32_t)new_pil);
env->psrpil = new_pil;
if (cpu_interrupts_enabled(env)) {
cpu_check_irqs(env);
}
#endif
} | 1threat |
How can I ensure that an overloaded method calls another method at the end in Java? : I have an abstract class `Foo` with two methods `bar()` and `qux()` as the following:
```java
abstract class Foo {
abstract void bar();
private void qux() {
// Do something...
}
}
```
How can I force that the overloaded method `bar()` in subclasses of `Foo` calls `qux()` as the last statement? | 0debug |
How to disable li object in mozilla : I am new to JS and trying to modify code to make it browser compatible. Using below code I am trying to create tabs (link) and by default menu_item3 & 4 will be disable. This code is not working on mozilla & chrome whereas working in IE.
<ul>
<li id="menu_item1" class="selectedtab"><a href="javascript:;" onclick="showTab(this)"><span style="color:black; font-weight: bold;">Report Options</span>
</a></li>
<li id="menu_item2"><a href="javascript:;" onclick="showTab(this)"><span style="color:black; font-weight: bold;">Required Filters</span></a></li>
<li id="menu_item3" class="disabled-state"><a href="javascript:;" onclick="showTab(this)" disabled='disabled'><span style="color:black; font-weight: bold;">Optional Filters</span></a></li>
<li id="menu_item4" class="disabled-state"><a href="javascript:;" onclick="showTab(this)" disabled='disabled'><span style="color:black; font-weight: bold;">Confirmation</span></a></li>
Thanks,
AS
</ul> | 0debug |
static void decode_scaling_matrices(H264Context *h, SPS *sps,
PPS *pps, int is_sps,
uint8_t(*scaling_matrix4)[16],
uint8_t(*scaling_matrix8)[64])
{
int fallback_sps = !is_sps && sps->scaling_matrix_present;
const uint8_t *fallback[4] = {
fallback_sps ? sps->scaling_matrix4[0] : default_scaling4[0],
fallback_sps ? sps->scaling_matrix4[3] : default_scaling4[1],
fallback_sps ? sps->scaling_matrix8[0] : default_scaling8[0],
fallback_sps ? sps->scaling_matrix8[3] : default_scaling8[1]
};
if (get_bits1(&h->gb)) {
sps->scaling_matrix_present |= is_sps;
decode_scaling_list(h, scaling_matrix4[0], 16, default_scaling4[0], fallback[0]);
decode_scaling_list(h, scaling_matrix4[1], 16, default_scaling4[0], scaling_matrix4[0]);
decode_scaling_list(h, scaling_matrix4[2], 16, default_scaling4[0], scaling_matrix4[1]);
decode_scaling_list(h, scaling_matrix4[3], 16, default_scaling4[1], fallback[1]);
decode_scaling_list(h, scaling_matrix4[4], 16, default_scaling4[1], scaling_matrix4[3]);
decode_scaling_list(h, scaling_matrix4[5], 16, default_scaling4[1], scaling_matrix4[4]);
if (is_sps || pps->transform_8x8_mode) {
decode_scaling_list(h, scaling_matrix8[0], 64, default_scaling8[0], fallback[2]);
if (sps->chroma_format_idc == 3) {
decode_scaling_list(h, scaling_matrix8[1], 64, default_scaling8[0], scaling_matrix8[0]);
decode_scaling_list(h, scaling_matrix8[2], 64, default_scaling8[0], scaling_matrix8[1]);
}
decode_scaling_list(h, scaling_matrix8[3], 64, default_scaling8[1], fallback[3]);
if (sps->chroma_format_idc == 3) {
decode_scaling_list(h, scaling_matrix8[4], 64, default_scaling8[1], scaling_matrix8[3]);
decode_scaling_list(h, scaling_matrix8[5], 64, default_scaling8[1], scaling_matrix8[4]);
}
}
}
}
| 1threat |
Converting time into Hours, minutes, and seconds : <p>I was writing a c++ program that converts time into: hours, minutes, and seconds. <br>
What I need to do is to convert time into the form of: HH:MM:SS, anyways <br> here is my code: <br></p>
<pre><code>#include <iostream>
using namespace std;
int main() {
long time, hour, min, sec;
cout<<"Enter elapsed time: ";
cin>>time;
cout<<time;
hour = time/3600;
min = (time%3600) / 60;
sec = (time%3600) % 60;
cout<<"\nIn HH:MM:SS -> ";
cout<<hour<<":"<<min<<":"<<sec;
return 0;
}
</code></pre>
<p><br> When I enter time in example: 3600, it displays 1:0:0 unlike the form I'm looking forward, so I need it to be displayed as "01:00:00" in this form. What should I do?</p>
| 0debug |
Updating a single cell in CollectionView using Swift : I am new to Swift.
I have a problem with updating a single cell when using CollectionView.
When I click on a label, I want the label will change the value to a different number which I can assign manually.
I appreciate any help
Code:
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//return nameArray.count;
return 81;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell=collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell;
switch(flattened[indexPath.item]){
case 1:
cell.labelText.text="1";
case 2:
cell.labelText.text="2";
case 3:
cell.labelText.text="3";
case 4:
cell.labelText.text="4";
case 5:
cell.labelText.text="5";
case 6:
cell.labelText.text="6";
case 7:
cell.labelText.text="7";
case 8:
cell.labelText.text="8";
case 9:
cell.labelText.text="9";
default:
cell.labelText.text="0";
//print(indexPath.item)
}
return cell;
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
Picture
[When I run my code][1]
[1]: https://i.stack.imgur.com/4bOS5.jpg | 0debug |
Check for existence in list : <p>I have a somewhat stupid question which drives me nuts for a couple of days now. Heavy web search did not help either.</p>
<p>Within some larger SQLAlchemy application I want to check whether some value exists inside a list or not (before the SQL is executed). Therefore I have defined two functions: one which checks the existence of a value inside a list, and gives back True or False. Plus a second one which loops as long as the value is not in the list:</p>
<pre><code>def check_value(itemlist, value_check):
print(itemlist) #only for debugging reasons
if value_check in itemlist:
print('Item is already in list') #only for debugging reasons
return False
else:
print('Item is not in list') #only for debugging reasons
return True
def check_input(itemlist, value_check):
while check_value(itemlist ,value_check)==False:
value_check = input('Please input valid value')
return value_check
</code></pre>
<p>now if I run this code lets say:</p>
<pre><code>def check_value(itemlist, value_check):
print(itemlist) #only for debugging reasons
if value_check in itemlist:
print('Item is already in list') #only for debugging reasons
return False
else:
print('Item is not in list') #only for debugging reasons
return True
def check_input(itemlist, value_check):
while check_value(itemlist ,value_check)==False:
value_check = input('Please input valid value')
return value_check
if __name__ == "__main__":
items = [1, 18272, 18279, 12, 298]
value_check = 18272
check_input(items, value_check)
</code></pre>
<p>IDLE gives me the correct answer at first:</p>
<pre><code>[1, 18272, 18279, 12, 298]
Item is already in list
Please input valid value
</code></pre>
<p>Then I give it a number that is also in the list let's say "1" but it still tells me the value is not in the list:</p>
<pre><code>[1, 18272, 18279, 12, 298]
Item is not in list
>>>
</code></pre>
<p>Its clear that this has been asked several times and I have found some help here already:<a href="https://stackoverflow.com/questions/14608015/how-to-check-if-a-specific-integer-is-in-a-list">How to check if a specific integer is in a list</a> I tried this method x is in (see code above).</p>
<p>Also I found this thread: <a href="https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-given-a-list-containing-it-in-python">Finding the index of an item given a list containing it in Python</a> which would be my workaround to check for index of a given value and write some try/except around it. Nevertheless I do not understand why x is y is not working here.</p>
<p>I have the feeling I am missing something very basic here but I am not able to grasp what.</p>
| 0debug |
Is it possible to change the parameters of onCreate() in a fragment : <p>Is it possible to change the parameters of onCreate() in a fragment (If We can Then will it be called in the beginning similar to a normal onCreate() Method.</p>
| 0debug |
static int execute_command(BlockDriverState *bdrv,
SCSIGenericReq *r, int direction,
BlockCompletionFunc *complete)
{
r->io_header.interface_id = 'S';
r->io_header.dxfer_direction = direction;
r->io_header.dxferp = r->buf;
r->io_header.dxfer_len = r->buflen;
r->io_header.cmdp = r->req.cmd.buf;
r->io_header.cmd_len = r->req.cmd.len;
r->io_header.mx_sb_len = sizeof(r->req.sense);
r->io_header.sbp = r->req.sense;
r->io_header.timeout = MAX_UINT;
r->io_header.usr_ptr = r;
r->io_header.flags |= SG_FLAG_DIRECT_IO;
r->req.aiocb = bdrv_aio_ioctl(bdrv, SG_IO, &r->io_header, complete, r);
if (r->req.aiocb == NULL) {
return -EIO;
}
return 0;
}
| 1threat |
Browser: Identifier X has already been declared : <p>I am using ES6 with Babel in my project and I am getting an error when I declare one of my <code>const</code></p>
<pre><code>'use strict';
const APP = window.APP = window.APP || {};
const _ = window._;
APP.personalCard = (function () {
...
}());
</code></pre>
<p>the error</p>
<blockquote>
<p>Uncaught TypeError: Identifier 'APP' has already been declared</p>
</blockquote>
<p>and that is the whole file, I don't have that declare anywhere else in that file. But I have declared that var in the top of the other files.</p>
<p>What do you think it should be ?</p>
| 0debug |
Using substring after like "%value%" in SQL : I've run into a problem where I cannot go any longer on my own.
I currently have a database which basically lists my cellphone with different applications on it.
The applications are listed with the status within the same database column which means that i separate the application from the status with a ";" and i separate the different applications with a ",".
Example :
ipboard,4.83->6.3,Running;testAcap,6.9-0,Stopped;
ipboard,2.3333->5.366,Stopped;Videostream,1.2,Stopped;
Now, how would i go about finding all the ipboards that currently as an app is stopped? As you see, the string before the status can vary in lenght due to the different versions. And I do not want a list of everything that is stopped, just the ipboard in this case.
My crappy query so far that selects all strings with ipboard in them at all(All of them doesnt have it) :
select *
from acaps
where acaps like '%ipb%'
For me the next logical thing to do would be something like :
select *
from acaps
where acaps like '%ipb%'
and subshitblabla where "Stopped" after the "," after the ipboard string.
Anyone knows how to get this working? | 0debug |
int decode_splitmvs(VP8Context *s, VP56RangeCoder *c, VP8Macroblock *mb, int layout)
{
int part_idx;
int n, num;
VP8Macroblock *top_mb;
VP8Macroblock *left_mb = &mb[-1];
const uint8_t *mbsplits_left = vp8_mbsplits[left_mb->partitioning];
const uint8_t *mbsplits_top, *mbsplits_cur, *firstidx;
VP56mv *top_mv;
VP56mv *left_mv = left_mb->bmv;
VP56mv *cur_mv = mb->bmv;
if (!layout)
top_mb = &mb[2];
else
top_mb = &mb[-s->mb_width - 1];
mbsplits_top = vp8_mbsplits[top_mb->partitioning];
top_mv = top_mb->bmv;
if (vp56_rac_get_prob_branchy(c, vp8_mbsplit_prob[0])) {
if (vp56_rac_get_prob_branchy(c, vp8_mbsplit_prob[1]))
part_idx = VP8_SPLITMVMODE_16x8 + vp56_rac_get_prob(c, vp8_mbsplit_prob[2]);
else
part_idx = VP8_SPLITMVMODE_8x8;
} else {
part_idx = VP8_SPLITMVMODE_4x4;
}
num = vp8_mbsplit_count[part_idx];
mbsplits_cur = vp8_mbsplits[part_idx],
firstidx = vp8_mbfirstidx[part_idx];
mb->partitioning = part_idx;
for (n = 0; n < num; n++) {
int k = firstidx[n];
uint32_t left, above;
const uint8_t *submv_prob;
if (!(k & 3))
left = AV_RN32A(&left_mv[mbsplits_left[k + 3]]);
else
left = AV_RN32A(&cur_mv[mbsplits_cur[k - 1]]);
if (k <= 3)
above = AV_RN32A(&top_mv[mbsplits_top[k + 12]]);
else
above = AV_RN32A(&cur_mv[mbsplits_cur[k - 4]]);
submv_prob = get_submv_prob(left, above);
if (vp56_rac_get_prob_branchy(c, submv_prob[0])) {
if (vp56_rac_get_prob_branchy(c, submv_prob[1])) {
if (vp56_rac_get_prob_branchy(c, submv_prob[2])) {
mb->bmv[n].y = mb->mv.y + read_mv_component(c, s->prob->mvc[0]);
mb->bmv[n].x = mb->mv.x + read_mv_component(c, s->prob->mvc[1]);
} else {
AV_ZERO32(&mb->bmv[n]);
}
} else {
AV_WN32A(&mb->bmv[n], above);
}
} else {
AV_WN32A(&mb->bmv[n], left);
}
}
return num;
}
| 1threat |
how to start an activity from the marker on Google map api? : <p>i ve tried to search on Google but i coulnt find the exact solution. how can i start another activity from the marker on map ? i want to click the marker and move to another activity. </p>
<p>here is my code ,</p>
<pre><code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapLongClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hava_durumu, menu);
return true;
}
@Override
public void onMapLongClick(LatLng point) {
mMap.addMarker(new MarkerOptions()
.position(point)
.title("You are here")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
}
</code></pre>
| 0debug |
help understanding recursion and exponents - JavaScript : <p>I'm new and have been working to try and rationalize this in my brain but can't seem to understand it. First the way that many will recognize using a simple "for" loop:</p>
<pre><code>function power(base, exponent){
var result = 1;
for(var i = 0; i < exponent; i++){
if(exponent == 0)
return 1;
else
result *= base;
};
return result;
}
</code></pre>
<p>In this section I am reading about recursion and talking about how a function can call itself as long as it doesn't cause a stack overflow. The code is as follows:</p>
<pre><code>function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
console.log(power(2, 3));
</code></pre>
<p>What I'm having an issue is understanding how it actually works, this what I think is happening: </p>
<p>After it moves on past the first "if" statement it moves to the "else" and calls itself to return to the top of the if statement, minus 1, each time till it reaches 0 when it will just return the "result". Is that right? Or am I missing something entirely?</p>
| 0debug |
static int decode_tsw1(GetByteContext *gb, uint8_t *frame, int width, int height)
{
const uint8_t *frame_start = frame;
const uint8_t *frame_end = frame + width * height;
int mask = 0x10000, bitbuf = 0;
int v, count, segments;
unsigned offset;
segments = bytestream2_get_le32(gb);
offset = bytestream2_get_le32(gb);
if (segments == 0 && offset == frame_end - frame)
return 0;
if (frame_end - frame <= offset)
return AVERROR_INVALIDDATA;
frame += offset;
while (segments--) {
if (bytestream2_get_bytes_left(gb) < 2)
return AVERROR_INVALIDDATA;
if (mask == 0x10000) {
bitbuf = bytestream2_get_le16u(gb);
mask = 1;
}
if (frame_end - frame < 2)
return AVERROR_INVALIDDATA;
if (bitbuf & mask) {
v = bytestream2_get_le16(gb);
offset = (v & 0x1FFF) << 1;
count = ((v >> 13) + 2) << 1;
if (frame - frame_start < offset || frame_end - frame < count)
return AVERROR_INVALIDDATA;
av_memcpy_backptr(frame, offset, count);
frame += count;
} else {
*frame++ = bytestream2_get_byte(gb);
*frame++ = bytestream2_get_byte(gb);
}
mask <<= 1;
}
return 0;
}
| 1threat |
def find_Min_Diff(arr,n):
arr = sorted(arr)
diff = 10**20
for i in range(n-1):
if arr[i+1] - arr[i] < diff:
diff = arr[i+1] - arr[i]
return diff | 0debug |
Selenium: Find any link related to a specific website : <p>I was wondering if the 'find link' function in selenium can choose a link which is not specifically a partial or exact string match but 'a branch to a main website'.</p>
<p>For example, say I wanted to find "cats.com" I type into the google "dogs are the best". And selenium will click on the first link whether it be:</p>
<p>'<a href="https://www.cats.com/dogs1" rel="nofollow noreferrer">https://www.cats.com/dogs1</a>'</p>
<p>or</p>
<p>'<a href="https://www.cats.com/page24" rel="nofollow noreferrer">https://www.cats.com/page24</a>'</p>
<p>becuse they are all located within the main website, cats.com
Is there such a thing? </p>
| 0debug |
Converting Between Symbols and Strings (Lesson 9) : Hey don't ban me from this. I just started learning to code and its some bullshit to have people freely cut you off from using this site like they own it. Act the way you'd act in front of people and show some respect'
Anyways I'm learning bout gsub and symbols atm and I got asked the question to replace the s's in an array with to_sym to make them symbols and this is how its asked
https://i.stack.imgur.com/9K2ES.png
We have an array of strings we'd like to later use as hash keys, but we'd rather they be symbols.
1. Create a new variable, symbols, and store an empty array in it
2. For each s in strings, use .to_sym to convert s to a symbol and
use .push to add that new symbol to symbols.
3. Print the symbols array.
I ended up writing it like this '
strings.each do |string|
if strings.include? "s"
strings.gsub! (/s/, .to_sym)
end
symbols.push (string)
end
print symbols
_______________________________________________________________________
The code didn't even end up working so I'm trying to get help in that regards. For reference here was the answer that they wanted
______________________________________________________________________
strings.each do |s|
symbols.push(s.to_sym)
end
print symbols
| 0debug |
Constraint Layout Vertical Align Center : <p>How to vertically align and center objects in constraint layout? It is possible to align vertically or horizontally but I have not found a way to center at the same time beside constraining the views between two gridlines. </p>
<p>Vertical Align Center:
<a href="https://i.stack.imgur.com/lBO3P.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lBO3P.png" alt="enter image description here"></a></p>
<p>It seems like centering is a huge problem with constraint layout which forces me to go back to relative layout for "centerInParent", "centerVertical", and "centerHorizontal". </p>
<p>I would like to create the layout boxed in red using constraint layout:
<a href="https://i.stack.imgur.com/H6pvq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/H6pvq.png" alt="enter image description here"></a></p>
<p>Unfortunately, the only way I found without using two gridlines is with nested Relative and LinearLayouts (which Constraint Layout was supposed to solve this exact scenario!).</p>
<p>Layout using Relative and Linear Layout:</p>
<pre><code><RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
app:layout_constraintTop_toBottomOf="@id/user_points"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
<LinearLayout
android:id="@+id/stat_1_layout"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_centerVertical="true"
android:layout_toLeftOf="@+id/divider_1"
android:orientation="vertical">
<TextView
android:id="@+id/stat_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:text="10"
android:textSize="16dp"
android:textColor="@color/textSecondaryDark"
android:maxLines="1"/>
<TextView
android:id="@+id/stat_detail_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="Streak"
android:textSize="8sp"
android:textColor="@color/textSecondary"
android:maxLines="1"/>
</LinearLayout>
<View
android:id="@+id/divider_1"
android:layout_width="1dp"
android:layout_height="38dp"
android:layout_toLeftOf="@+id/stat_2_layout"
android:background="@drawable/linedivider"/>
<LinearLayout
android:id="@+id/stat_2_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="18dp"
android:layout_marginRight="18dp"
android:layout_centerInParent="true"
android:orientation="vertical">
<TextView
android:id="@+id/stat_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:text="243"
android:textSize="16dp"
android:textColor="@color/textSecondaryDark"
android:maxLines="1"/>
<TextView
android:id="@+id/stat_detail_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="Calories Burned"
android:textSize="8sp"
android:textColor="@color/textSecondary"
android:maxLines="1"/>
</LinearLayout>
<View
android:id="@+id/divider_2"
android:layout_width="1dp"
android:layout_height="38dp"
android:layout_toRightOf="@+id/stat_2_layout"
android:background="@drawable/linedivider"/>
<LinearLayout
android:id="@+id/stat_3_layout"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_toRightOf="@+id/divider_2"
android:layout_centerVertical="true"
android:orientation="vertical">
<TextView
android:id="@+id/stat_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:text="3200"
android:textSize="16dp"
android:textColor="@color/textSecondaryDark"
android:maxLines="1"/>
<TextView
android:id="@+id/stat_detail_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="Steps"
android:textSize="8sp"
android:textColor="@color/textSecondary"
android:maxLines="1"/>
</LinearLayout>
</RelativeLayout>
</code></pre>
| 0debug |
Why is implicit conversion from const to non-const allowed? : <p>Why does C++ allow the following code to compile?</p>
<pre><code>std::unordered_map<std::string, int> m;
// ...
for (const std::pair<std::string, int>& p: m)
{
// ...
}
</code></pre>
<p>According to <a href="http://shop.oreilly.com/product/0636920033707.do" rel="noreferrer">Scott Meyers' <em>Effective Modern C++</em></a> (p. 40-41):</p>
<blockquote>
<p>[...] the key part of a <code>std::unordered_map</code> is <code>const</code>, so the type of <code>std::pair</code> in the hash table (which is what a <code>std::unordered_map</code> is) isn’t <code>std::pair<std::string, int></code>, it's <code>std::pair <const std::string, int></code>. But that's not the type declared for the variable <code>p</code> in the loop above. As a result, compilers will strive to find a way to convert <code>std::pair<const std::string, int></code> objects (i.e., what’s in the hash table) to <code>std::pair<std::string, int></code> objects (the declared type for <code>p</code>). They’ll succeed by creating a temporary object of the type that <code>p</code> wants to bind to by copying each object in <code>m</code>, then binding the reference p to that temporary object. At the end of each loop iteration, the temporary object will be destroyed. If you wrote this loop, you'd likely be surprised by this behavior, because you'd almost certainly intend to simply bind the reference <code>p</code> to each element in <code>m</code>.</p>
</blockquote>
<p>What is the benefit of allowing this implicit conversion? Is there some common use case where the developer would expect / prefer this implicit conversion (rather than getting a compiler error)?</p>
| 0debug |
I want to add country code from dropdown in Android : How can I do this, I searched on StackOverflow, but solution is for iphone, not android.
Here is my chat app: https://play.google.com/store/apps/details?id=com.jimmytrivedi.lapitchat | 0debug |
static inline void RENAME(yvu9toyv12)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc,
uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
long width, long height, long lumStride, long chromStride)
{
memcpy(ydst, ysrc, width*height);
}
| 1threat |
static uint64_t fw_cfg_comb_read(void *opaque, target_phys_addr_t addr,
unsigned size)
{
return fw_cfg_read(opaque);
}
| 1threat |
How to join two Optional<String> with a delimiter in Java 8 : <p>I have two <code>Optional</code> strings, <code>name1</code> and <code>name2</code>. I want to join the two such that the result is also an Optional with:</p>
<ol>
<li>If either one is non-empty, the result should be the non-empty name.</li>
<li>If both are non-empty, I want the result to be joined with the delimiter <code>AND</code>.</li>
<li>If both are empty, the result should be an empty <code>Optional</code></li>
</ol>
<p>My attempt at this:</p>
<pre><code>StringBuilder sb = new StringBuilder();
name1.ifPresent(sb::append);
name2.ifPresent(s -> {
if (sb.length() > 0) {
sb.append(" AND ");
}
sb.append(s);
}
Optional<String> joinedOpt = Optional.ofNullable(Strings.emptyToNull(sb.toString()));
</code></pre>
<p>This works, but seems ugly and not very functional.</p>
<p>PS: There is a similar <a href="https://stackoverflow.com/a/46473336/1314028">question</a> but the accepted answer is wrong. Specifically, if <code>name1</code> is empty and <code>name2</code> is not, it returns an empty optional.</p>
| 0debug |
Implementing Binary tree in java : <p>I am new to datastructure.I am trying to implement Binary tree using Linked List.</p>
<p>I need a few clarifications in implementing it.</p>
<p>i)For inserting a new value in tree,Whether we should backtracking and Tree traversal in implementing it.</p>
<p>ii)Please suggest me cases for Searching and Deleting a value also.</p>
<p>iii)Please suggest me the correct material for implementing all type of Trees.</p>
| 0debug |
How to use split function in spak scala : I am supplying line by line to the program and each line consists of date in the format MM/DD/YYYY,how i can use split function here.
val data= line.split("/")
val year = data[2]
println(year)
I am not getting any output can anyone explain me where I am wrong. | 0debug |
void show_help(void)
{
const OptionDef *po;
int i, expert;
printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000,2001 Gerard Lantau\n"
"usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
"Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n"
"\n"
"Main options are:\n");
for(i=0;i<2;i++) {
if (i == 1)
printf("\nAdvanced options are:\n");
for(po = options; po->name != NULL; po++) {
char buf[64];
expert = (po->flags & OPT_EXPERT) != 0;
if (expert == i) {
strcpy(buf, po->name);
if (po->flags & HAS_ARG) {
strcat(buf, " ");
strcat(buf, po->argname);
}
printf("-%-17s %s\n", buf, po->help);
}
}
}
exit(1);
}
| 1threat |
Hash of a complex structure : <p>I'd like to know a relatively simple way to generate the hash of a complex C structure (which form a graph, in my case). By "simple" I mean, if possible, without having to go through all the nodes it forms. My goal would be, afterwards, to check if two structures are identical thanks to their hash, but also to sort them in an orderly way.</p>
<p>There are functions and algorithms for numbers or strings for instance, but I don't know a good way to do it for a structure. What would you recommend? </p>
| 0debug |
START_TEST(unterminated_array)
{
QObject *obj = qobject_from_json("[32");
fail_unless(obj == NULL);
}
| 1threat |
void qemu_init_vcpu(void *_env)
{
CPUState *env = _env;
if (kvm_enabled())
kvm_init_vcpu(env);
env->nr_cores = smp_cores;
env->nr_threads = smp_threads;
return;
}
| 1threat |
Loop add new record to array in typescript : <p>I have a opt variable in Typescript</p>
<pre><code>let opt = [{}];
</code></pre>
<p>if I want to add multiple children to opt variable to below exsample with for loop</p>
<pre><code>options = [
{ name: "option1", value: 1 },
{ name: "option2", value: 2 }
]
</code></pre>
<p>how can I coding</p>
<pre><code>for(i=0; i<=5; i++) {
...
}
</code></pre>
| 0debug |
hibernate with c3p0: createClob() is not yet implemented : <p>In my project I started to use <a href="http://www.mchange.com/projects/c3p0/" rel="noreferrer">c3p0</a> with hibernate for reconnecting to database as hibernate won't restore connection on db failure.</p>
<pre><code><dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.2.9.Final</version>
</dependency>
</code></pre>
<p>I am using hibernate version:</p>
<pre><code><dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.9.Final</version>
</dependency>
</code></pre>
<p>the postgresql driver is:</p>
<pre><code><dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.1.4</version>
</dependency>
</code></pre>
<p>c3p0 configuration is:</p>
<pre><code> properties.put("hibernate.c3p0.preferredTestQuery","SELECT 1");
properties.put("hibernate.c3p0.testConnectionOnCheckout","true");
properties.put("hibernate.c3p0.acquireRetryAttempts","1");
properties.put("hibernate.c3p0.acquireIncrement","1");
properties.put("hibernate.c3p0.idleConnectionTestPeriod","60");
</code></pre>
<p>but I keep getting this error:</p>
<pre><code>18:25:32.910 [localhost-startStop-1] DEBUG c.m.v2.c3p0.impl.NewPooledConnection - com.mchange.v2.c3p0.impl.NewPooledConnection@755e3afe handling a throwable.
java.sql.SQLFeatureNotSupportedException: Method org.postgresql.jdbc.PgConnection.createClob() is not yet implemented.
at org.postgresql.Driver.notImplemented(Driver.java:669) ~[postgresql-42.1.4.jar:42.1.4]
at org.postgresql.jdbc.PgConnection.createClob(PgConnection.java:1246) ~[postgresql-42.1.4.jar:42.1.4]
at com.mchange.v2.c3p0.impl.NewProxyConnection.createClob(NewProxyConnection.java:1408) ~[c3p0-0.9.5.2.jar:0.9.5.2]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
at org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl.useContextualLobCreation(LobCreatorBuilderImpl.java:113) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl.makeLobCreatorBuilder(LobCreatorBuilderImpl.java:54) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.<init>(JdbcEnvironmentImpl.java:271) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:858) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) [spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) [spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) [spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) [spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) [spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) [spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) [spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4971) [catalina.jar:7.0.53]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5467) [catalina.jar:7.0.53]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:7.0.53]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901) [catalina.jar:7.0.53]
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877) [catalina.jar:7.0.53]
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632) [catalina.jar:7.0.53]
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1073) [catalina.jar:7.0.53]
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857) [catalina.jar:7.0.53]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_121]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_121]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]
18:25:32.911 [localhost-startStop-1] DEBUG com.mchange.v2.sql.SqlUtils - Attempted to convert SQLException to SQLException. Leaving it alone. [SQLState: 0A000; errorCode: 0]
java.sql.SQLFeatureNotSupportedException: Method org.postgresql.jdbc.PgConnection.createClob() is not yet implemented.
at org.postgresql.Driver.notImplemented(Driver.java:669) ~[postgresql-42.1.4.jar:42.1.4]
at org.postgresql.jdbc.PgConnection.createClob(PgConnection.java:1246) ~[postgresql-42.1.4.jar:42.1.4]
at com.mchange.v2.c3p0.impl.NewProxyConnection.createClob(NewProxyConnection.java:1408) ~[c3p0-0.9.5.2.jar:0.9.5.2]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
at org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl.useContextualLobCreation(LobCreatorBuilderImpl.java:113) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl.makeLobCreatorBuilder(LobCreatorBuilderImpl.java:54) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.<init>(JdbcEnvironmentImpl.java:271) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:858) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) [spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) [spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) [spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) [spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) [spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) [spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) [spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4971) [catalina.jar:7.0.53]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5467) [catalina.jar:7.0.53]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:7.0.53]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901) [catalina.jar:7.0.53]
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877) [catalina.jar:7.0.53]
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632) [catalina.jar:7.0.53]
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1073) [catalina.jar:7.0.53]
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857) [catalina.jar:7.0.53]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_121]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_121]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]
18:25:32.912 [localhost-startStop-1] DEBUG c.m.v.c.impl.DefaultConnectionTester - Testing a Connection in response to an Exception:
java.sql.SQLFeatureNotSupportedException: Method org.postgresql.jdbc.PgConnection.createClob() is not yet implemented.
at org.postgresql.Driver.notImplemented(Driver.java:669) ~[postgresql-42.1.4.jar:42.1.4]
at org.postgresql.jdbc.PgConnection.createClob(PgConnection.java:1246) ~[postgresql-42.1.4.jar:42.1.4]
at com.mchange.v2.c3p0.impl.NewProxyConnection.createClob(NewProxyConnection.java:1408) ~[c3p0-0.9.5.2.jar:0.9.5.2]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
at org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl.useContextualLobCreation(LobCreatorBuilderImpl.java:113) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl.makeLobCreatorBuilder(LobCreatorBuilderImpl.java:54) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.<init>(JdbcEnvironmentImpl.java:271) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:858) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885) [hibernate-core-5.2.9.Final.jar:5.2.9.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) [spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) [spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) [spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) [spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) [spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) [spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) [spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4971) [catalina.jar:7.0.53]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5467) [catalina.jar:7.0.53]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:7.0.53]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901) [catalina.jar:7.0.53]
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877) [catalina.jar:7.0.53]
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632) [catalina.jar:7.0.53]
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1073) [catalina.jar:7.0.53]
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857) [catalina.jar:7.0.53]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_121]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_121]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]
</code></pre>
<p>I have to note that I'm not calling <code>createClob()</code> myself!</p>
<p>So what whould I change in order to get rid of this error during Tomcat 7 startup? I have also erased postgresql driver from tomcat's lib dir.</p>
| 0debug |
void qdev_prop_register_global(GlobalProperty *prop)
{
QTAILQ_INSERT_TAIL(&global_props, prop, next);
}
| 1threat |
static uint64_t pci_config_get_memory_base(PCIDevice *d, uint32_t base)
{
return ((uint64_t)pci_get_word(d->config + base) & PCI_MEMORY_RANGE_MASK)
<< 16;
}
| 1threat |
How to reduce the size of React Select in v2 : <p>The new v2 react-select control is great, but by default is too large. Is there a (preferably) simple way to reduce the height to the same as a standard select control (using Bootstrap v3)?</p>
| 0debug |
How to create a dynamic variable name by concatenating two strings in golang? : I want to a create variable name by concatenating with current date and provide a value to the created variable name. My variable name should look something like this **"Key-2019-01"**. so that i can store the value as **var Key-2019-01 = "yes"**
I have tried like the below.
package main
import (
"fmt"
"time"
"strconv"
"strings"
)
func main() {
currentMonth := time.Now().Month()
currentYear := time.Now().Year()
var month = int(currentMonth)
var currentDate = strings.Join([]string{strconv.Itoa(currentYear), "-", strconv.Itoa(month)}, "")
var "Key",currentDate string
value, err := json.Marshal("yes")
stub.PutState(("Key", currentDate), value)
}
It could be helpful if I get a working code of this. Please help me in solving this. Thanks in advance.
| 0debug |
How would I write a bash function that can extract all common archive files? : <p>I'd like to have a bash function that can extract zip, tar, tar.gz and other archives.</p>
<p>How can this be done?</p>
| 0debug |
error: invalid use of non-static member function c++ 11 : Issue:
------
I am trying to instantiate a class (say class A) inside another class (say class B) and then call all the member functions of class A inside the class B for the instantiated object. I get the following error message for every call of class A methods inside class B :
***error: invalid use of non-static member function***
I am aware of the following thread about the same problem. https://stackoverflow.com/questions/41326376/invalid-use-of-non-static-member-function-c. But I don't find that solution relevant to my problem. I am elaborating the problem below. Can you please enlighten me what is going wrong ?
Code:
-----
The following are my classes:
**Navigation.h**
class Navigation {
public:
Navigation() {
laserData = n.subscribe("/scan", 200, &Navigation::laserCallback, this);
velPub = n.advertise<geometry_msgs::Twist> ("/mobile_base/commands/velocity", 100, this);
}
~Navigation() {}
geometry_msgs::Twist moveCommand();
geometry_msgs::Twist turnCommand();
geometry_msgs::Twist stopCommand();
void laserCallback(const sensor_msgs::LaserScan::ConstPtr& data);
float getObstacleRange();
void broadcastVelocity(geometry_msgs::Twist velocity);
private:
ros::NodeHandle n;
ros::Publisher velPub;
ros::Subscriber laserData;
float obstacleRange;
ros::Timer normalTurnTimer;
ros::Timer driveTimer;
ros::Timer periodicTurnTimer;
geometry_msgs::Twist drivePower;
};
**Navigation.cpp**
geometry_msgs::Twist Navigation::moveCommand() {
drivePower.linear.x = 0.25;
drivePower.linear.y = 0.0;
drivePower.linear.z = 0.0;
drivePower.angular.x = 0.0;
drivePower.angular.y = 0.0;
drivePower.angular.z = 0.0;
return drivePower;
}
geometry_msgs::Twist Navigation::turnCommand() {
std::random_device scramble;
std::mt19937 num(scramble());
std::uniform_int_distribution<int> dist(30, 100);
float angle = dist(num);
drivePower.linear.x = 0.0;
drivePower.linear.y = 0.0;
drivePower.linear.z = 0.0;
drivePower.angular.x = 0.0;
drivePower.angular.y = 0.0;
drivePower.angular.z = angle * (3.14 / 180);
return drivePower;
}
geometry_msgs::Twist Navigation::stopCommand() {
drivePower.linear.x = 0.0;
drivePower.linear.y = 0.0;
drivePower.linear.z = 0.0;
drivePower.angular.x = 0.0;
drivePower.angular.y = 0.0;
drivePower.angular.z = 0.0;
return drivePower;
}
void Navigation::laserCallback(const sensor_msgs::LaserScan::ConstPtr& data) {
float threshold = 10;
for (const auto& dist : data->ranges) {
if (threshold > dist) threshold = dist;
}
obstacleRange = threshold;
ROS_DEBUG_STREAM("Approach distance to obstacle is : " << obstacleRange);
}
float Navigation::getObstacleRange() {
return obstacleRange;
}
void Navigation::broadcastVelocity(geometry_msgs::Twist velocity) {
velPub.publish(velocity);
}
**Turtlebot.h**
class Turtlebot {
public:
Turtlebot() {
Navigation nomad;
}
~Turtlebot() {}
void drive();
private:
Navigation nomad;
};
**Turtlebot.cpp**
void Turtlebot::drive() {
if (nomad.getObstacleRange() < 0.7) {
nomad.broadcastVelocity(nomad.stopCommand);
int i;
while (i < 5) {
nomad.broadcastVelocity(nomad.turnCommand);
i++;
}
} else nomad.broadcastVelocity(nomad.moveCommand);
}
Errors:
-------
I get the following errors during ***cmake .. && make***
/home/arun/Documents/catkin_ws/src/TinyNomad/src/Turtlebot.cpp: In member function ‘void Turtlebot::drive()’:
/home/arun/Documents/catkin_ws/src/TinyNomad/src/Turtlebot.cpp:37:50: error: invalid use of non-static member function
nomad.broadcastVelocity(nomad.stopCommand);
^
/home/arun/Documents/catkin_ws/src/TinyNomad/src/Turtlebot.cpp:40:54: error: invalid use of non-static member function
nomad.broadcastVelocity(nomad.turnCommand);
^
/home/arun/Documents/catkin_ws/src/TinyNomad/src/Turtlebot.cpp:43:53: error: invalid use of non-static member function
} else nomad.broadcastVelocity(nomad.moveCommand);
^
TinyNomad/CMakeFiles/tinynomad.dir/build.make:110: recipe for target 'TinyNomad/CMakeFiles/tinynomad.dir/src/Turtlebot.cpp.o' failed
make[2]: *** [TinyNomad/CMakeFiles/tinynomad.dir/src/Turtlebot.cpp.o] Error 1
CMakeFiles/Makefile2:1191: recipe for target 'TinyNomad/CMakeFiles/tinynomad.dir/all' failed
make[1]: *** [TinyNomad/CMakeFiles/tinynomad.dir/all] Error 2
Makefile:138: recipe for target 'all' failed
make: *** [all] Error 2
Invoking "make -j12 -l12" failed
| 0debug |
static int parse_add_fd(QemuOpts *opts, void *opaque)
{
int fd, dupfd, flags;
int64_t fdset_id;
const char *fd_opaque = NULL;
fd = qemu_opt_get_number(opts, "fd", -1);
fdset_id = qemu_opt_get_number(opts, "set", -1);
fd_opaque = qemu_opt_get(opts, "opaque");
if (fd < 0) {
qerror_report(ERROR_CLASS_GENERIC_ERROR,
"fd option is required and must be non-negative");
return -1;
}
if (fd <= STDERR_FILENO) {
qerror_report(ERROR_CLASS_GENERIC_ERROR,
"fd cannot be a standard I/O stream");
return -1;
}
flags = fcntl(fd, F_GETFD);
if (flags == -1 || (flags & FD_CLOEXEC)) {
qerror_report(ERROR_CLASS_GENERIC_ERROR,
"fd is not valid or already in use");
return -1;
}
if (fdset_id < 0) {
qerror_report(ERROR_CLASS_GENERIC_ERROR,
"set option is required and must be non-negative");
return -1;
}
#ifdef F_DUPFD_CLOEXEC
dupfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
#else
dupfd = dup(fd);
if (dupfd != -1) {
qemu_set_cloexec(dupfd);
}
#endif
if (dupfd == -1) {
qerror_report(ERROR_CLASS_GENERIC_ERROR,
"Error duplicating fd: %s", strerror(errno));
return -1;
}
monitor_fdset_add_fd(dupfd, true, fdset_id, fd_opaque ? true : false,
fd_opaque, NULL);
return 0;
}
| 1threat |
static int parallels_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVParallelsState *s = bs->opaque;
ParallelsHeader ph;
int ret, size, i;
QemuOpts *opts = NULL;
Error *local_err = NULL;
char *buf;
bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
false, errp);
if (!bs->file) {
return -EINVAL;
}
ret = bdrv_pread(bs->file, 0, &ph, sizeof(ph));
if (ret < 0) {
goto fail;
}
bs->total_sectors = le64_to_cpu(ph.nb_sectors);
if (le32_to_cpu(ph.version) != HEADER_VERSION) {
goto fail_format;
}
if (!memcmp(ph.magic, HEADER_MAGIC, 16)) {
s->off_multiplier = 1;
bs->total_sectors = 0xffffffff & bs->total_sectors;
} else if (!memcmp(ph.magic, HEADER_MAGIC2, 16)) {
s->off_multiplier = le32_to_cpu(ph.tracks);
} else {
goto fail_format;
}
s->tracks = le32_to_cpu(ph.tracks);
if (s->tracks == 0) {
error_setg(errp, "Invalid image: Zero sectors per track");
ret = -EINVAL;
goto fail;
}
if (s->tracks > INT32_MAX/513) {
error_setg(errp, "Invalid image: Too big cluster");
ret = -EFBIG;
goto fail;
}
s->bat_size = le32_to_cpu(ph.bat_entries);
if (s->bat_size > INT_MAX / sizeof(uint32_t)) {
error_setg(errp, "Catalog too large");
ret = -EFBIG;
goto fail;
}
size = bat_entry_off(s->bat_size);
s->header_size = ROUND_UP(size, bdrv_opt_mem_align(bs->file->bs));
s->header = qemu_try_blockalign(bs->file->bs, s->header_size);
if (s->header == NULL) {
ret = -ENOMEM;
goto fail;
}
s->data_end = le32_to_cpu(ph.data_off);
if (s->data_end == 0) {
s->data_end = ROUND_UP(bat_entry_off(s->bat_size), BDRV_SECTOR_SIZE);
}
if (s->data_end < s->header_size) {
s->header_size = size;
}
ret = bdrv_pread(bs->file, 0, s->header, s->header_size);
if (ret < 0) {
goto fail;
}
s->bat_bitmap = (uint32_t *)(s->header + 1);
for (i = 0; i < s->bat_size; i++) {
int64_t off = bat2sect(s, i);
if (off >= s->data_end) {
s->data_end = off + s->tracks;
}
}
if (le32_to_cpu(ph.inuse) == HEADER_INUSE_MAGIC) {
s->header_unclean = true;
if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
error_setg(errp, "parallels: Image was not closed correctly; "
"cannot be opened read/write");
ret = -EACCES;
goto fail;
}
}
opts = qemu_opts_create(¶llels_runtime_opts, NULL, 0, &local_err);
if (local_err != NULL) {
goto fail_options;
}
qemu_opts_absorb_qdict(opts, options, &local_err);
if (local_err != NULL) {
goto fail_options;
}
s->prealloc_size =
qemu_opt_get_size_del(opts, PARALLELS_OPT_PREALLOC_SIZE, 0);
s->prealloc_size = MAX(s->tracks, s->prealloc_size >> BDRV_SECTOR_BITS);
buf = qemu_opt_get_del(opts, PARALLELS_OPT_PREALLOC_MODE);
s->prealloc_mode = qapi_enum_parse(prealloc_mode_lookup, buf,
PRL_PREALLOC_MODE__MAX, PRL_PREALLOC_MODE_FALLOCATE, &local_err);
g_free(buf);
if (local_err != NULL) {
goto fail_options;
}
if (!(flags & BDRV_O_RESIZE) || !bdrv_has_zero_init(bs->file->bs) ||
bdrv_truncate(bs->file, bdrv_getlength(bs->file->bs),
PREALLOC_MODE_OFF, NULL) != 0) {
s->prealloc_mode = PRL_PREALLOC_MODE_FALLOCATE;
}
if (flags & BDRV_O_RDWR) {
s->header->inuse = cpu_to_le32(HEADER_INUSE_MAGIC);
ret = parallels_update_header(bs);
if (ret < 0) {
goto fail;
}
}
s->bat_dirty_block = 4 * getpagesize();
s->bat_dirty_bmap =
bitmap_new(DIV_ROUND_UP(s->header_size, s->bat_dirty_block));
qemu_co_mutex_init(&s->lock);
return 0;
fail_format:
error_setg(errp, "Image not in Parallels format");
ret = -EINVAL;
fail:
qemu_vfree(s->header);
return ret;
fail_options:
error_propagate(errp, local_err);
ret = -EINVAL;
goto fail;
}
| 1threat |
ram_addr_t xen_ram_addr_from_mapcache(void *ptr)
{
MapCacheEntry *entry = NULL;
MapCacheRev *reventry;
hwaddr paddr_index;
hwaddr size;
int found = 0;
QTAILQ_FOREACH(reventry, &mapcache->locked_entries, next) {
if (reventry->vaddr_req == ptr) {
paddr_index = reventry->paddr_index;
size = reventry->size;
found = 1;
break;
}
}
if (!found) {
fprintf(stderr, "%s, could not find %p\n", __func__, ptr);
QTAILQ_FOREACH(reventry, &mapcache->locked_entries, next) {
DPRINTF(" "TARGET_FMT_plx" -> %p is present\n", reventry->paddr_index,
reventry->vaddr_req);
}
abort();
return 0;
}
entry = &mapcache->entry[paddr_index % mapcache->nr_buckets];
while (entry && (entry->paddr_index != paddr_index || entry->size != size)) {
entry = entry->next;
}
if (!entry) {
DPRINTF("Trying to find address %p that is not in the mapcache!\n", ptr);
return 0;
}
return (reventry->paddr_index << MCACHE_BUCKET_SHIFT) +
((unsigned long) ptr - (unsigned long) entry->vaddr_base);
}
| 1threat |
trying to fetch json in recyclerview but didin't get sucessfull : **Previously I have worked with ArrayAdapter and list view, so i did this code to update the UI**
private class UserAsync extends AsyncTask<String,Void,List<User>>{
@Override
protected List<User> doInBackground(String... urls) {
if(urls.length <1 || urls[0] == null){
return null;
}
List<User> result = null;
try {
result = QueryUtils.fetchJson(urls[0]);
} catch (JSONException e) {
Log.e(LOG_TAG,"Error in fetching json",e);
}
return result;
}
@Override
protected void onPostExecute(List<User> users) {
// Clear the adapter of previous earthquake data
mAdapter.clear();
// If there is a valid list of {@link user}s, then add them to the adapter's
// data set. This will trigger the ListView to update.
if(users != null && !users.isEmpty()){
mAdapter.addAll(users);
// After adding user to the adapter, Notify adapter for UI update
mAdapter.notifyDataSetChanged();
}
}
}
Now I have tried **RecyclerView** and **CardView** to fetch the data but the above code is not working for recyclerview..
I want to know how to implement the **doInBackground** and **onPostExecute** for recycler VIew
**activity_main.xml**
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="examle.android.com.recyclerviewnetwork.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
**items.xml**
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="8dp"
app:cardCornerRadius="5dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:padding="25dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/avatar"
android:layout_width="108dp"
android:layout_height="108dp"
android:padding="15dp"
tools:src="@mipmap/ic_launcher" />
<LinearLayout
android:paddingRight="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="15dp"
tools:text="LOGIN_USER" />
<TextView
android:id="@+id/type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="3dp"
tools:text="USER_TYPE" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
**Main_activity.java**
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
UserAdapter mAdapter;
RecyclerView.LayoutManager layoutManager;
private static final String JSON_URL = "https://api.github.com/users";
private static final String LOG_TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
mAdapter = new UserAdapter(new ArrayList<User>(),this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mAdapter);
UserAsyncTask task = new UserAsyncTask();
task.execute(JSON_URL);
}
public class UserAsyncTask extends AsyncTask<String, Void, List<User>>{
@Override
protected List<User> doInBackground(String... urls) {
if(urls.length < 1 || urls[0] == null ){
return null;
}
List<User> result = null;
try{
result = QueryUtils.fetchJson(urls[0]);
} catch (JSONException e) {
Log.e(LOG_TAG,"Error in fetching json",e);
}
return result;
}
@Override
protected void onPostExecute(List<User> users) {
super.onPostExecute(users);
}
}
}
**QueryUtils.java**
public class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
public QueryUtils() {
}
public static List<User> fetchJson(String requestUrl) throws JSONException{
//create URL object
URL url = createUrl(requestUrl);
//perform http request to the URL and receive a json
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG,"problem in making http request",e);
}
List<User> users = extractJson(jsonResponse);
return users;
}
/**
* Returns new URL object from the given string URL.
*/
private static URL createUrl(String stringUrl){
URL url = null;
try{
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG,"Error in creating Url",e);
}
return url;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private static String makeHttpRequest(URL url) throws IOException{
String jsonResponse = "";
//if url == null, return early
if(url == null){
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
if(urlConnection.getResponseCode() == 200){
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}else {
Log.e(LOG_TAG,"Error response code" + urlConnection.getResponseCode());
}
}catch (IOException e){
Log.e(LOG_TAG,"Problem in retreving Json Response",e);
}finally {
if (urlConnection != null){
urlConnection.disconnect();
}
if (inputStream !=null){
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if(inputStream != null){
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null){
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<User> extractJson(String json) throws JSONException{
// If the JSON string is empty or null, then return early.
if(TextUtils.isEmpty(json)){
return null;
}
//create an empty arrylist
List<User> users = new ArrayList<>();
try{
JSONArray jsonArray = new JSONArray();
for (int i = 0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String login = jsonObject.getString("login");
String type = jsonObject.getString("type");
String avatar = jsonObject.getString("avatar_url");
User user = new User(login,type,avatar);
users.add(user);
}
}catch (JSONException e){
Log.e(LOG_TAG,"Error in parsing the JSON",e);
}
return users;
}
}
**UserAdapter.java**
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserViewHolder> {
ArrayList<User> users = new ArrayList<>();
Context context;
public UserAdapter(ArrayList<User> users, Context context) {
this.users = users;
this.context = context;
}
@Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items,parent,false);
return new UserViewHolder(view);
}
@Override
public void onBindViewHolder(UserViewHolder holder, int position) {
holder.login.setText(users.get(position).getUser_login());
holder.type.setText(users.get(position).getType());
Picasso.with(context).load(String.valueOf(users.get(position))).into(holder.avatar);
}
@Override
public int getItemCount() {
return users.size();
}
public class UserViewHolder extends RecyclerView.ViewHolder {
TextView login;
TextView type;
ImageView avatar;
public UserViewHolder(View itemView) {
super(itemView);
login = (TextView)itemView.findViewById(R.id.login);
type = (TextView)itemView.findViewById(R.id.type);
avatar = (ImageView)itemView.findViewById(R.id.avatar);
}
}
}
**User.java**
public class User {
private String user_login;
private String type;
private String url;
public User(String user_login, String type, String url) {
this.user_login = user_login;
this.type = type;
this.url = url;
}
public String getUser_login() {
return user_login;
}
public String getType() {
return type;
}
public String getUrl() {
return url;
}
}
| 0debug |
int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
int *got_picture_ptr,
AVPacket *avpkt)
{
AVCodecInternal *avci = avctx->internal;
int ret;
*got_picture_ptr = 0;
if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
return -1;
avctx->internal->pkt = avpkt;
ret = apply_param_change(avctx, avpkt);
if (ret < 0) {
av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
if (avctx->err_recognition & AV_EF_EXPLODE)
return ret;
}
avcodec_get_frame_defaults(picture);
if (!avctx->refcounted_frames)
av_frame_unref(&avci->to_free);
if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
avpkt);
else {
ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
avpkt);
picture->pkt_dts = avpkt->dts;
if (!(avctx->codec->capabilities & CODEC_CAP_DR1)) {
picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
picture->width = avctx->width;
picture->height = avctx->height;
picture->format = avctx->pix_fmt;
}
}
emms_c();
if (ret < 0 && picture->buf[0])
av_frame_unref(picture);
if (*got_picture_ptr) {
if (!avctx->refcounted_frames) {
avci->to_free = *picture;
avci->to_free.extended_data = avci->to_free.data;
memset(picture->buf, 0, sizeof(picture->buf));
}
avctx->frame_number++;
}
} else
ret = 0;
return ret;
}
| 1threat |
Promotion in java : <p>I exectued this statement</p>
<pre><code>System.out.println(3.0 + 5/2);
</code></pre>
<p>And found the answer to be 5.0.
Now according to promotion, if an expression contains a double type data, every operand will be promoted to double type. So 5 and 2 will be promoted to 5.0 and 2.0 respectively. Therefore the logical expression here should be </p>
<pre><code>3.0+5.0/2.0
</code></pre>
<p>Which should give the answer 5.5 instead of 5.0.</p>
| 0debug |
set cookies of other website using php : <p>I have a website that I want to get the names of the company using the div but the problem is the link keeps redirecting me into the homepage of the website</p>
<p>this is the site <a href="http://us.kompass.com/" rel="nofollow noreferrer">http://us.kompass.com/</a></p>
<p>I found that the problem is the cookies, is it possible to set the cookies of the website that you want to get?
is it possible to do that in php? or any ways to block the redirect?</p>
<p>referrer doesn't work here.</p>
| 0debug |
How can I copy to the clipboard the output of a cell in a Jupyter notebook? : <p>How can I copy to the clipboard the output of a cell in a Jupyter notebook, without having to select it with drag-and-drop?</p>
<p><a href="https://i.stack.imgur.com/dOrc3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dOrc3.png" alt="enter image description here"></a></p>
| 0debug |
Access span text jquery : I need to change a text in a span.
<span class="count_bottom"><i class="blue"><i class="fa fa-sort-asc"></i>12% </i> From last seen</span>
I only need to change `From last seen` text according to button click event.
How can I do this?
| 0debug |
int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
{
BlockDriver *drv;
drv = bdrv_find_protocol(filename);
if (drv == NULL) {
drv = bdrv_find_format("file");
}
return bdrv_create(drv, filename, options);
}
| 1threat |
Cannot implicity convet type error : Sorry guys, I'm totaly new on this.
Trying to fill Combobox with data from a database and I'm using ExecuteReader as below, but when I try to instanciate my connection it shows me the error "Cannot implicity convet type error".
My BDConnect class code:
public class DBConnect
{
private SqlConnection connection;
private string servername = "10.1.76.109,1433";
private string database = "EngLib";
private string dbuser;
private string userpassword;
public DBConnect()
{
}
public void doDBConnect(string dbuserform, string userpasswordform)
{
dbuser = dbuserform;
userpassword = userpasswordform;
}
public void Initialize()
{
}
public bool openConnection()
{
string connectionString;
connectionString = "Server=" + servername + ";Database=" + database + ";user id=" + dbuser + ";Password=" + userpassword;
Console.WriteLine(connectionString);
connection = new SqlConnection(connectionString);
try
{
connection.Open();
return true;
}
catch (SqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Não é possível contactar o servidor. Entre em contato com o administrador");
break;
case 18456:
MessageBox.Show("Usuário/Senha inválidos, tente novamente");
break;
}
return false;
}
}
My form code:
{
public Form2()
{
InitializeComponent();
}
public void Form2_Load(object sender, EventArgs e)
{
SqlDataReader rdr = null;
DBConnect sqlConnection;
sqlConnection = new DBConnect();
sqlConnection.doDBConnect(dbuserform: "usertest", userpasswordform: "usertest");
{
try
{
{
sqlConnection.openConnection();
SqlCommand sqlCmd;
sqlCmd = new SqlCommand("SELECT Material FROM EngLib");
sqlCmd.Connection = sqlConnection;
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
comboBox1.Items.Add(sqlReader["Material"].ToString());
}
sqlReader.Close();
}
}
finally
{
// close the reader
if (rdr != null)
{
rdr.Close();
}
}
}
}
}
}
The user and password in the code is just temporary.
| 0debug |
Angular2 Router - Anyone know how to use canActivate in app.ts so that I can redirect to home page if not logged in : <p>Angular2 Router - Anyone know how to use canActivate in app.ts so that I can redirect to home page if not logged in</p>
<p>I'm using typescript and angular 2.</p>
<p><strong>Current attempt under my constructor in my app.ts file:</strong></p>
<pre><code> canActivate(instruction) {
console.log("here - canActivate");
console.log(instruction);
this.router.navigate(['Home']);
}
</code></pre>
<p>It currently doesnt get hit.
Any idea why?</p>
| 0debug |
static bool megasas_use_msi(MegasasState *s)
{
return s->msi != ON_OFF_AUTO_OFF;
}
| 1threat |
static void qmp_input_type_str(Visitor *v, char **obj, const char *name,
Error **errp)
{
QmpInputVisitor *qiv = to_qiv(v);
QObject *qobj = qmp_input_get_object(qiv, name, true);
if (!qobj || qobject_type(qobj) != QTYPE_QSTRING) {
error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",
"string");
return;
}
*obj = g_strdup(qstring_get_str(qobject_to_qstring(qobj)));
}
| 1threat |
Handling custom __new__() and _del__() with inheritance : When I derive a class in python, I need to call the `Base.__init__(self)` from the derived `__init__(self)` function like
class Base(object):
def __init__(self):
pass
class Der(Base):
def __init__(self) :
Base.__init__(self)
Do I need to do the same for `__new__(self)` and `__del__(self)` functions like
class Base(object):
def __new__(self):
pass
def __init__(self):
pass
def __del__(self) :
pass
class Der(Base):
def __new__(self):
Base.__new__(self)
def __init__(self) :
Base.__init__(self)
def __del__(self) :
Base.__del__(self)
I am wondering because nothing seems to go WRONG if I don't do that.
I am sure that python `gc` will take care, but is there anything I need to be worried about if I don't call them from Derived chain
| 0debug |
How to check if a column has only NA values? : <p>I have a data frame with 30k observations but i think one of my columns has only NA values. How to check if that specific column has only NA values or not because having so much observation i can check them without code.</p>
| 0debug |
python not understanding simple math question : <p>I am making mortgage calculator, I have provided information for variables p, i, n, but get error in the equation.</p>
<pre><code>p[i(1 + i) ^ n] / [(1 + i) ^ n – 1]
</code></pre>
| 0debug |
build_srat(GArray *table_data, BIOSLinker *linker, MachineState *machine)
{
AcpiSystemResourceAffinityTable *srat;
AcpiSratMemoryAffinity *numamem;
int i;
int srat_start, numa_start, slots;
uint64_t mem_len, mem_base, next_base;
MachineClass *mc = MACHINE_GET_CLASS(machine);
const CPUArchIdList *apic_ids = mc->possible_cpu_arch_ids(machine);
PCMachineState *pcms = PC_MACHINE(machine);
ram_addr_t hotplugabble_address_space_size =
object_property_get_int(OBJECT(pcms), PC_MACHINE_MEMHP_REGION_SIZE,
NULL);
srat_start = table_data->len;
srat = acpi_data_push(table_data, sizeof *srat);
srat->reserved1 = cpu_to_le32(1);
for (i = 0; i < apic_ids->len; i++) {
int node_id = apic_ids->cpus[i].props.has_node_id ?
apic_ids->cpus[i].props.node_id : 0;
uint32_t apic_id = apic_ids->cpus[i].arch_id;
if (apic_id < 255) {
AcpiSratProcessorAffinity *core;
core = acpi_data_push(table_data, sizeof *core);
core->type = ACPI_SRAT_PROCESSOR_APIC;
core->length = sizeof(*core);
core->local_apic_id = apic_id;
core->proximity_lo = node_id;
memset(core->proximity_hi, 0, 3);
core->local_sapic_eid = 0;
core->flags = cpu_to_le32(1);
} else {
AcpiSratProcessorX2ApicAffinity *core;
core = acpi_data_push(table_data, sizeof *core);
core->type = ACPI_SRAT_PROCESSOR_x2APIC;
core->length = sizeof(*core);
core->x2apic_id = cpu_to_le32(apic_id);
core->proximity_domain = cpu_to_le32(node_id);
core->flags = cpu_to_le32(1);
}
}
next_base = 0;
numa_start = table_data->len;
numamem = acpi_data_push(table_data, sizeof *numamem);
build_srat_memory(numamem, 0, 640 * 1024, 0, MEM_AFFINITY_ENABLED);
next_base = 1024 * 1024;
for (i = 1; i < pcms->numa_nodes + 1; ++i) {
mem_base = next_base;
mem_len = pcms->node_mem[i - 1];
if (i == 1) {
mem_len -= 1024 * 1024;
}
next_base = mem_base + mem_len;
if (mem_base <= pcms->below_4g_mem_size &&
next_base > pcms->below_4g_mem_size) {
mem_len -= next_base - pcms->below_4g_mem_size;
if (mem_len > 0) {
numamem = acpi_data_push(table_data, sizeof *numamem);
build_srat_memory(numamem, mem_base, mem_len, i - 1,
MEM_AFFINITY_ENABLED);
}
mem_base = 1ULL << 32;
mem_len = next_base - pcms->below_4g_mem_size;
next_base += (1ULL << 32) - pcms->below_4g_mem_size;
}
numamem = acpi_data_push(table_data, sizeof *numamem);
build_srat_memory(numamem, mem_base, mem_len, i - 1,
MEM_AFFINITY_ENABLED);
}
slots = (table_data->len - numa_start) / sizeof *numamem;
for (; slots < pcms->numa_nodes + 2; slots++) {
numamem = acpi_data_push(table_data, sizeof *numamem);
build_srat_memory(numamem, 0, 0, 0, MEM_AFFINITY_NOFLAGS);
}
if (hotplugabble_address_space_size) {
numamem = acpi_data_push(table_data, sizeof *numamem);
build_srat_memory(numamem, pcms->hotplug_memory.base,
hotplugabble_address_space_size, pcms->numa_nodes - 1,
MEM_AFFINITY_HOTPLUGGABLE | MEM_AFFINITY_ENABLED);
}
build_header(linker, table_data,
(void *)(table_data->data + srat_start),
"SRAT",
table_data->len - srat_start, 1, NULL, NULL);
}
| 1threat |
BlockDriverAIOCB *paio_ioctl(BlockDriverState *bs, int fd,
unsigned long int req, void *buf,
BlockDriverCompletionFunc *cb, void *opaque)
{
struct qemu_paiocb *acb;
acb = qemu_aio_get(&raw_aio_pool, bs, cb, opaque);
if (!acb)
return NULL;
acb->aio_type = QEMU_AIO_IOCTL;
acb->aio_fildes = fd;
acb->ev_signo = SIGUSR2;
acb->async_context_id = get_async_context_id();
acb->aio_offset = 0;
acb->aio_ioctl_buf = buf;
acb->aio_ioctl_cmd = req;
acb->next = posix_aio_state->first_aio;
posix_aio_state->first_aio = acb;
qemu_paio_submit(acb);
return &acb->common;
}
| 1threat |
Vue 2 arguments in inline (in-template) event handler : <p>Is it possible to access arguments/parameters passed to an emitted event within an inline / in-template handler? Something like:</p>
<pre><code><component @some-event="someObject.field = $arguments[0]"></component
</code></pre>
<p>What I'm trying to do exactly is assign a value to an object in the scope. I know I can create a method to do that and use it as a handler for the event but I was wondering if this could work as an inline statement.</p>
| 0debug |
php code and website functioning on localhost but not working on server : <p>Good day, my login script which i've been building on my localhost host wamp server is working perfectly well on the localhost but has refused to function well ever since i uploaded it to the server. it reads the username and password and if correct it does nothing but if wrong it alerts me that is it wrong. if correct it is supposed to redirect me to the home page. i've been struggling with it ever since on the server. please any one that will be of help will be much appreciated. it does the same thing too for my register page. it registers but doesnt give any feedback and also does not redirect to the login page but on the localhost everything seems fine
login script
</p>
<pre><code> <?php
include 'connection.php';
if(isset($_SESSION['use'])) // Checking whether the session is already there or not if
// true then header redirect it to the home page directly
{
header("Location:home.php");
}
if(isset($_POST['login'])) // it checks whether the user clicked login button or not
{
$user = $_POST['code'];
$pass = $_POST['user'];
if(!filter_var($_POST['code'], FILTER_VALIDATE_EMAIL)) {
echo "<script>alert('invalid Email Address')</script>" ; // Use your own error handling ;)
}
if (!preg_match("/^[a-zA-Z0-9 ]*$/",$pass)) {
echo "<script>alert('Invalid password. Only letters, numbers and white space allowed')</script>" ;
}
// Secure the credentials
// Check the users input against the DB.
$user = stripslashes($user);
$pass = stripslashes($pass);
$check=mysqli_query($conn, "SELECT * FROM userregister WHERE email = '$user' AND password = '$pass'");
$checkrows=mysqli_num_rows($check);
if($checkrows>0){
while( $row = mysqli_fetch_assoc($check) ){
$_SESSION['use']=$row['email'];
header("Location:home.php");
// On Successful Login redirects to home.php
}}
else
{
echo "<script>alert('Incorrect Login details')</script>" ;
header("refresh:0");
}
}
?>
<html>
<head>
<title>Prediction Home</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="icon" type="image/png" href="2.png">
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="w3.css">
</head>
<body>
<div class="topnav" id="myTopnav">
<a href="index.php">Prediction Home</a>
<a href="javascript:void(0);" class="icon" onclick="myFunction()">X
</a>
</div>
<div>
<h4>Enter your Log-In details</h4>
</div>
<div class="form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<label for="E-mail">E-mail</label>
<input type="text" id="E-mail" name="code" required="required">
<label for="">Password</label>
<input type="password" id="" name="user" required="required">
<input type="submit" name="login" value="Log-In">
</form>
<p>Forgot Password? <a class="button" href="forgotpass.php"><span>Click Me!</span></a></p>
</div>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
</body>
</html>
</code></pre>
<p>register script</p>
<pre><code> <!doctype html>
<html>
<head>
<title>Prediction Home</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="w3.css">
<link rel="icon" type="image/png" href="2.png">
</head>
<body>
<div class="topnav" id="myTopnav">
<a href="index.php">Prediction Home</a>
<a href="javascript:void(0);" class="icon" onclick="myFunction()">X
</a>
</div>
<div>
<h2>REGISTRATION PAGE</h2>
</div>
<div class="form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<label for="fname">FULL NAME</label>
<input type="text" name="option" required="required">
<label for="Email">E-mail</label>
<input type="text" name="option1" required="required">
<label for="pass">PASSWORD</label>
<input type="password" name="password" required="required">
<label for="pass2">RE-ENTER PASSWORD</label>
<input type="password" name="password2" required="required">
<input type="submit" name="register" value="Register">
</form>
<p>Already Registerd? <a class="button" href="login.php"><span>Sign In</span></a></p>
</div>
<div id="page"></div>
<footer style="background-color: purple ">
<div style="text-align: center">
<h2>Quick Links</h2>
<a style="vertical-align: middle;color: white" href="index.php">Prediction Home</a>
<a style="vertical-align: middle;color: white" href="contact.php">Contact Us</a>
<a style="vertical-align: middle;color: white" href="Store.php">My Store</a>
<a style="vertical-align: middle;color: white" href="basic.php">Basic</a>
<a style="vertical-align: middle;color: white" href="regular.php">Regular</a>
<a style="vertical-align: middle;color: white" href="weekend.php">Weekend</a>
<a style="vertical-align: middle;color: white" href="about.PHP">About</a>
<a style="vertical-align: middle;color: white" href="conditions.PHP">Terms & Conditions</a>
</div>
<div style="text-align: center;">
<h2>Contacts:</h2>
<p style="color: white;vertical-align: middle">Call Us On:08136668621 <br>
MAil:user@predicthome.com</p>
<a href="https:/twitter.com/predicthome" class="fa fa-twitter"></a>
<a href="https://www.instagram.com/predictionhome/" class="fa fa-instagram"></a>
<a href="mailto:user@predictionhome.com" class="fa fa-yahoo"></a>
</div>
<div style="color: yellow;text-align: center;">Prediction Home &copy; <?php echo date("Y");?></div>
</footer>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<?php
include 'connection.php';
if(isset($_POST['register'])) // it checks whether the user clicked login button or not
{
$option = $_POST['option'];
$option1 = $_POST['option1'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
if(!filter_var($_POST['option1'], FILTER_VALIDATE_EMAIL)) {
echo "<script>alert('invalid Email Address')</script>" ; // Use your own error handling ;)
}
if (!preg_match("/^[a-zA-Z0-9 ]*$/",$option)) {
echo "<script>alert('Invalid NAME. Only letters, numbers and white space allowed')</script>" ;
}
if (!preg_match("/^[a-zA-Z0-9 ]*$/",$password)) {
echo "<script>alert('Invalid password. Only letters, numbers and white space allowed')</script>" ;
}
if (!preg_match("/^[a-zA-Z0-9 ]*$/",$password2)) {
echo "<script>alert('Invalid password. Only letters, numbers and white space allowed')</script>" ;
}
if ($password !=$password2) {
echo "<script>alert('Password does not match')</script>" ;
}
// Secure the credentials
// Check the users input against the DB.
$insert=mysqli_query($conn,"SELECT * FROM userregister WHERE email='$option1'");
$insertrows=mysqli_num_rows($insert);
if($insertrows>0 || $password !=$password2|| !preg_match("/^[a-zA-Z0-9 ]*$/",$password) || !filter_var($_POST['option1'], FILTER_VALIDATE_EMAIL) ){
echo "<script>alert('Email already exists or Invalid Email address')</script>" ;
}
else {
$check="INSERT IGNORE INTO userregister(name,email,password) VALUES('$option','$option1','$password')";
if ($conn->query($check) === TRUE) {
header("refresh:0;url=login.php");
echo "<script>alert('registered')</script>" ;
$to = "$option1";
$subject = "Account Registration Successful";
$body = "Hi $option, Welcome to Predict Home. Your Favourite Site to select the best of Games that wll Bring you Good money\r\nWe hope we keep in touch and hear from you more often. \r\nVisit our site regularly to view our predicted Games from our highly acclaimed analysts.\r\nOnce again you are Welcome.\r\nPredict Home Admin";
$lheaders= "From: <user@predicthome.com>";
mail($to, $subject, $body, $lheaders);
}
}
//send email
}
?>
</body>
</html>
</code></pre>
| 0debug |
static void tcp_chr_read(void *opaque)
{
CharDriverState *chr = opaque;
TCPCharDriver *s = chr->opaque;
uint8_t buf[1024];
int len, size;
if (!s->connected || s->max_size <= 0)
return;
len = sizeof(buf);
if (len > s->max_size)
len = s->max_size;
size = tcp_chr_recv(chr, (void *)buf, len);
if (size == 0) {
s->connected = 0;
if (s->listen_fd >= 0) {
qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
}
qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
closesocket(s->fd);
s->fd = -1;
qemu_chr_event(chr, CHR_EVENT_CLOSED);
} else if (size > 0) {
if (s->do_telnetopt)
tcp_chr_process_IAC_bytes(chr, s, buf, &size);
if (size > 0)
qemu_chr_read(chr, buf, size);
if (s->msgfd != -1) {
close(s->msgfd);
s->msgfd = -1;
}
}
}
| 1threat |
Strange process while turning off my computer : <p>So I was on my way to turn off my computer when unexpectedly, in the screen where you see the programs that block Windows to turn off, i saw one process with a strange name like {4593-9493-8949-9390} (not the exact same name but similar) and before i could click on the cancel button the process close.</p>
<p>My question here is if I should be wondering about that strange process or its just some random Windows 10 routine</p>
| 0debug |
static void v9fs_setattr(void *opaque)
{
int err = 0;
int32_t fid;
V9fsFidState *fidp;
size_t offset = 7;
V9fsIattr v9iattr;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
pdu_unmarshal(pdu, offset, "dI", &fid, &v9iattr);
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
if (v9iattr.valid & P9_ATTR_MODE) {
err = v9fs_co_chmod(pdu, &fidp->path, v9iattr.mode);
if (err < 0) {
goto out;
}
}
if (v9iattr.valid & (P9_ATTR_ATIME | P9_ATTR_MTIME)) {
struct timespec times[2];
if (v9iattr.valid & P9_ATTR_ATIME) {
if (v9iattr.valid & P9_ATTR_ATIME_SET) {
times[0].tv_sec = v9iattr.atime_sec;
times[0].tv_nsec = v9iattr.atime_nsec;
} else {
times[0].tv_nsec = UTIME_NOW;
}
} else {
times[0].tv_nsec = UTIME_OMIT;
}
if (v9iattr.valid & P9_ATTR_MTIME) {
if (v9iattr.valid & P9_ATTR_MTIME_SET) {
times[1].tv_sec = v9iattr.mtime_sec;
times[1].tv_nsec = v9iattr.mtime_nsec;
} else {
times[1].tv_nsec = UTIME_NOW;
}
} else {
times[1].tv_nsec = UTIME_OMIT;
}
err = v9fs_co_utimensat(pdu, &fidp->path, times);
if (err < 0) {
goto out;
}
}
if ((v9iattr.valid & (P9_ATTR_UID | P9_ATTR_GID)) ||
((v9iattr.valid & P9_ATTR_CTIME)
&& !((v9iattr.valid & P9_ATTR_MASK) & ~P9_ATTR_CTIME))) {
if (!(v9iattr.valid & P9_ATTR_UID)) {
v9iattr.uid = -1;
}
if (!(v9iattr.valid & P9_ATTR_GID)) {
v9iattr.gid = -1;
}
err = v9fs_co_chown(pdu, &fidp->path, v9iattr.uid,
v9iattr.gid);
if (err < 0) {
goto out;
}
}
if (v9iattr.valid & (P9_ATTR_SIZE)) {
err = v9fs_co_truncate(pdu, &fidp->path, v9iattr.size);
if (err < 0) {
goto out;
}
}
err = offset;
out:
put_fid(pdu, fidp);
out_nofid:
complete_pdu(s, pdu, err);
}
| 1threat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.