problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
void error_vprepend(Error **errp, const char *fmt, va_list ap)
{
GString *newmsg;
if (!errp) {
return;
}
newmsg = g_string_new(NULL);
g_string_vprintf(newmsg, fmt, ap);
g_string_append(newmsg, (*errp)->msg);
(*errp)->msg = g_string_free(newmsg, 0);
}
| 1threat
|
Competitive - Algorithm to solve this : I tried to solve this challenge some competitive website. here is the desc:
<br><br>
Given a string, a character is said to be superior if it has two neighboring letters that are strictly smaller than itself. We compare characters by their location in the alphabet.
More formally, we say that the character at the ith position is superior if a character exists at the (i+1)th position and (i-1)th position, and the character at the ith position is strictly greater than the character at both (i+1)thand (i-1)th positions.
Given the frequencies of the lowercase English letters, form a string using all these characters, such that the resultant string has the maximum number of superior characters. You need to print the maximum number of superior characters.
Complete the function maximumSuperiorCharacters which takes in an array of integers denoting the frequencies of the English letters and returns an integer denoting the maximum number of superior characters.
0 0 0 0 2 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 we have two es, one l, one s, and none of the other letters. We can form a string with one superior character, for example, else. One can also show that this is the maximum number of superior characters that can be present. Thus, the answer is 1. There are also many other permutations of characters possible to form a string with maximum superior characters.
Here is what i done so far
int maximumSuperiorCharacters(int[] Q)
{
int R = 0;
for (int V : Q) R += V;
return --R / 2;
}
| 0debug
|
static int push_single_pic(AVFilterLink *outlink)
{
AVFilterContext *ctx = outlink->src;
AVFilterLink *inlink = ctx->inputs[0];
ShowWavesContext *showwaves = ctx->priv;
int64_t n = 0, max_samples = showwaves->total_samples / outlink->w;
AVFrame *out = showwaves->outpicref;
struct frame_node *node;
const int nb_channels = inlink->channels;
const int x = 255 / (showwaves->split_channels ? 1 : nb_channels);
const int ch_height = showwaves->split_channels ? outlink->h / nb_channels : outlink->h;
const int linesize = out->linesize[0];
int col = 0;
int64_t *sum = showwaves->sum;
av_log(ctx, AV_LOG_DEBUG, "Create frame averaging %"PRId64" samples per column\n", max_samples);
memset(sum, 0, nb_channels);
for (node = showwaves->audio_frames; node; node = node->next) {
int i;
const AVFrame *frame = node->frame;
const int16_t *p = (const int16_t *)frame->data[0];
for (i = 0; i < frame->nb_samples; i++) {
int ch;
for (ch = 0; ch < nb_channels; ch++)
sum[ch] += abs(p[ch + i*nb_channels]) << 1;
if (n++ == max_samples) {
for (ch = 0; ch < nb_channels; ch++) {
int16_t sample = sum[ch] / max_samples;
uint8_t *buf = out->data[0] + col;
if (showwaves->split_channels)
buf += ch*ch_height*linesize;
av_assert0(col < outlink->w);
showwaves->draw_sample(buf, ch_height, linesize, sample, &showwaves->buf_idy[ch], x);
sum[ch] = 0;
col++;
n = 0;
return push_frame(outlink);
| 1threat
|
i want to konw the program flow in recursive method in java? : class Test {
int i=0;
void method2(){
if(i==6) return;
System.out.print("before");
i++;
method2();
System.out.println("after"):
}
}
if I call method2() from another class .I want to know how the program will flow here . or why the output that's executed.
| 0debug
|
How Can I Place A MYSQL Database Record In A Variable With PHP? : <p>I need some assistance with my code here. I'm using a mail() function to send a welcome email to a registrant.</p>
<p>My mailer script looks like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
$to = print require("includes/email.php");
$subject = "This is where I have my subject";
$txt = "Greetings
"."\n"."
Thank you for registering.
"."\n"."
This is some of my text
"."\n"."
Best Regards
Admin";
$headers = "From: [email protected]";
mail($to,$subject,$txt,$headers);
header("Location: pay.php");
?></code></pre>
</div>
</div>
</p>
<p>and my includes/email.php code looks like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
$sql = 'SELECT email_address FROM table WHERE id=(SELECT MAX(id) FROM `table`)';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['email_address'];
}}
$conn->close();
?></code></pre>
</div>
</div>
</p>
<p>Now I want my $to variable to have the email_address record from my database and for the mail() function to send an email to that email when the mailer script is run. When I run the script, an email is displayed on the screen and no email is sent but everything works when I manually put an email address on the $to variable. How can I successfully get the script to send the email to the requested email on the database?</p>
| 0debug
|
What should I use to run HTML/CSS/JS code? : <p>I've created a few simple HTML/CSS/JS games. This time a few friends and I are going to create another game that people can download from some website. We want to use HTML CSS and JS even though that is probably not the best option. </p>
<p>All the games I created before I've used Chrome to run them. Of course I can't just make people run my games with Chrome. So how should I run it?</p>
| 0debug
|
japanese and portuguese language cannot support : My site Japanese supported. But Portuguese language cannot fully display
Display on In�Cio Sobre N�S.
I have use for header('Content-type: text/html; charset=UTF-8') ;
this only Japanese language support.
I need to both language (Japanese and Portuguese) should be display.
I need to helper for best solution.
Thanks,
| 0debug
|
href style rel - What is the right order when linking a CSS stylesheet to an HTML file : <p>When you link a CSS stylesheet to an HTML file you have to use:
Is there something wrong if I will use for href , type and rel a different order?</p>
<p>Should they be written in this order? If yes, is there any explanation for this?</p>
<p>Thanks!</p>
| 0debug
|
db.execute('SELECT * FROM products WHERE product_id = ' + product_input)
| 1threat
|
static int compand_delay(AVFilterContext *ctx, AVFrame *frame)
{
CompandContext *s = ctx->priv;
AVFilterLink *inlink = ctx->inputs[0];
const int channels = inlink->channels;
const int nb_samples = frame->nb_samples;
int chan, i, av_uninit(dindex), oindex, av_uninit(count);
AVFrame *out_frame = NULL;
if (s->pts == AV_NOPTS_VALUE) {
s->pts = (frame->pts == AV_NOPTS_VALUE) ? 0 : frame->pts;
}
av_assert1(channels > 0);
for (chan = 0; chan < channels; chan++) {
AVFrame *delay_frame = s->delay_frame;
const double *src = (double *)frame->extended_data[chan];
double *dbuf = (double *)delay_frame->extended_data[chan];
ChanParam *cp = &s->channels[chan];
double *dst;
count = s->delay_count;
dindex = s->delay_index;
for (i = 0, oindex = 0; i < nb_samples; i++) {
const double in = src[i];
update_volume(cp, fabs(in));
if (count >= s->delay_samples) {
if (!out_frame) {
out_frame = ff_get_audio_buffer(inlink, nb_samples - i);
if (!out_frame) {
av_frame_free(&frame);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out_frame, frame);
out_frame->pts = s->pts;
s->pts += av_rescale_q(nb_samples - i,
(AVRational){ 1, inlink->sample_rate },
inlink->time_base);
}
dst = (double *)out_frame->extended_data[chan];
dst[oindex++] = av_clipd(dbuf[dindex] *
get_volume(s, cp->volume), -1, 1);
} else {
count++;
}
dbuf[dindex] = in;
dindex = MOD(dindex + 1, s->delay_samples);
}
}
s->delay_count = count;
s->delay_index = dindex;
av_frame_free(&frame);
return out_frame ? ff_filter_frame(ctx->outputs[0], out_frame) : 0;
}
| 1threat
|
Swift create array of first letters from array of strings with no duplicates : <p>I have an array of strings. I want to iterate through the array and grab the first letter from each string and add it to another array but only if that letter hasn't already been added. All of the answers i've found on google are really advanced and I was looking for a simple function.</p>
| 0debug
|
DeviceState *qdev_device_add(QemuOpts *opts)
{
DeviceClass *k;
const char *driver, *path, *id;
DeviceState *qdev;
BusState *bus;
driver = qemu_opt_get(opts, "driver");
if (!driver) {
qerror_report(QERR_MISSING_PARAMETER, "driver");
return NULL;
}
k = DEVICE_CLASS(object_class_by_name(driver));
path = qemu_opt_get(opts, "bus");
if (path != NULL) {
bus = qbus_find(path);
if (!bus) {
return NULL;
}
if (bus->info != k->bus_info) {
qerror_report(QERR_BAD_BUS_FOR_DEVICE,
driver, bus->info->name);
return NULL;
}
} else {
bus = qbus_find_recursive(main_system_bus, NULL, k->bus_info);
if (!bus) {
qerror_report(QERR_NO_BUS_FOR_DEVICE,
driver, k->bus_info->name);
return NULL;
}
}
if (qdev_hotplug && !bus->allow_hotplug) {
qerror_report(QERR_BUS_NO_HOTPLUG, bus->name);
return NULL;
}
qdev = qdev_create_from_info(bus, driver);
id = qemu_opts_id(opts);
if (id) {
qdev->id = id;
qdev_property_add_child(qdev_get_peripheral(), qdev->id, qdev, NULL);
} else {
static int anon_count;
gchar *name = g_strdup_printf("device[%d]", anon_count++);
qdev_property_add_child(qdev_get_peripheral_anon(), name,
qdev, NULL);
g_free(name);
}
if (qemu_opt_foreach(opts, set_property, qdev, 1) != 0) {
qdev_free(qdev);
return NULL;
}
if (qdev_init(qdev) < 0) {
qerror_report(QERR_DEVICE_INIT_FAILED, driver);
return NULL;
}
qdev->opts = opts;
return qdev;
}
| 1threat
|
static char *choose_pix_fmts(OutputStream *ost)
{
if (ost->keep_pix_fmt) {
if (ost->filter)
avfilter_graph_set_auto_convert(ost->filter->graph->graph,
AVFILTER_AUTO_CONVERT_NONE);
if (ost->st->codec->pix_fmt == PIX_FMT_NONE)
return NULL;
return av_strdup(av_get_pix_fmt_name(ost->st->codec->pix_fmt));
}
if (ost->st->codec->pix_fmt != PIX_FMT_NONE) {
return av_strdup(av_get_pix_fmt_name(choose_pixel_fmt(ost->st, ost->enc, ost->st->codec->pix_fmt)));
} else if (ost->enc->pix_fmts) {
const enum PixelFormat *p;
AVIOContext *s = NULL;
uint8_t *ret;
int len;
if (avio_open_dyn_buf(&s) < 0)
exit_program(1);
p = ost->enc->pix_fmts;
if (ost->st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
if (ost->st->codec->codec_id == CODEC_ID_MJPEG) {
p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
} else if (ost->st->codec->codec_id == CODEC_ID_LJPEG) {
p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
}
}
for (; *p != PIX_FMT_NONE; p++) {
const char *name = av_get_pix_fmt_name(*p);
avio_printf(s, "%s:", name);
}
len = avio_close_dyn_buf(s, &ret);
ret[len - 1] = 0;
return ret;
} else
return NULL;
}
| 1threat
|
How to convert SQL select statement with particular fields and where clause to pandas dataframe : <p>I am trying to convert fallowing SQL statement into pandas dataframe in python</p>
<pre><code>SELECT sum(money) from df where sex='female'
</code></pre>
<p>I am unable to get this in pandas</p>
<p>Thanks in advance</p>
| 0debug
|
Generating Random string : <p>Can anyone tell me how can I generate a random string containing only letters in c#?
I basically want a Random value and fill it in my form. I want this value to contain letters only?
How can I do this?</p>
| 0debug
|
How to merge two arrays in Angular? : <p>According to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat" rel="nofollow">JS documentation</a> there a concat() method for concatenating arrays, but if I try it in angular:</p>
<pre><code>$scope.array1 = [];
$scope.array2 = [];
$scope.myConcatenatedData = array1 .concat(array2);
</code></pre>
<p>I got an error: <code>ReferenceError: array1 is not defined</code> because I don't use var in declaring arrays. </p>
| 0debug
|
static int pci_add_option_rom(PCIDevice *pdev)
{
int size;
char *path;
void *ptr;
char name[32];
if (!pdev->romfile)
return 0;
if (strlen(pdev->romfile) == 0)
return 0;
if (!pdev->rom_bar) {
int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
if (class == 0x0300) {
rom_add_vga(pdev->romfile);
} else {
rom_add_option(pdev->romfile);
}
return 0;
}
path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
if (path == NULL) {
path = qemu_strdup(pdev->romfile);
}
size = get_image_size(path);
if (size < 0) {
error_report("%s: failed to find romfile \"%s\"",
__FUNCTION__, pdev->romfile);
return -1;
}
if (size & (size - 1)) {
size = 1 << qemu_fls(size);
}
if (pdev->qdev.info->vmsd)
snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->vmsd->name);
else
snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->name);
pdev->rom_offset = qemu_ram_alloc(&pdev->qdev, name, size);
ptr = qemu_get_ram_ptr(pdev->rom_offset);
load_image(path, ptr);
qemu_free(path);
pci_register_bar(pdev, PCI_ROM_SLOT, size,
0, pci_map_option_rom);
return 0;
}
| 1threat
|
Should you put quotes around type annotations in python : <p>What's the difference between these two functions? I've seen people put quotes around type annotations and other times leave them out but I couldn't find why people choose to use one or the other.</p>
<pre><code>def do_something(entity: Entity):
pass
def do_something(entity: 'Entity'):
pass
</code></pre>
<p>Are there advantages or disadvantages to any of these?</p>
| 0debug
|
Asking to remove the time in datetime without chaging the datatype : I want to ask about this one
[Picture][1]
[1]: https://i.stack.imgur.com/9YU9i.png
1. How to remove the time in "Tanggal" column, without changing its datatype?
2. How to remove the 2 last digit 0 in "Harga" column?
Thank you
| 0debug
|
Dart 2.3 for, if and spread support warning message regarding versions : <p>I am getting the warning message '<strong>The for, if and spread elements were not supported until version 2.2.2, but this code is required to be able to run on earlier versions</strong>' but the code </p>
<pre><code>Column( crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
if (document['propertyid'] == '1') Text('jjj'),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
PropertyDetails(document['propertyid'])));
},
child: Text(document['propertyname'],
style: TextStyle(
color: Colors.blue,
fontStyle: FontStyle.italic,
fontWeight: FontWeight
.w500) //Theme.of(context).textTheme.title,
),
),
],
),
</code></pre>
<p>works as expected. The minSDKVersion etc is 28. Why does it think I want to be able to run this code on any earlier version? What do I need to change to a later version?</p>
| 0debug
|
redirect to 404 page automatically at laravel 5.4 : <p>i made simple resume site with laravel 5.4 and i wanna if users type anything except my site name and my site.com/panel automatically redirect to 404 page.</p>
<p>how can i do that?</p>
<p>is there any route to do that or what?</p>
<p>i found this code but not use</p>
<pre><code> public function render($request, Exception $e)
{
if ($e instanceof
\Symfony\Component\HttpKernel\Exception\NotFoundHttpException){
return response(redirect(url('/')), 404);
}
return parent::render($request, $e);
}
</code></pre>
| 0debug
|
db.execute('SELECT * FROM employees WHERE id = ' + user_input)
| 1threat
|
If you allow, you can help solve this problem : Gradle 'My Application' project refresh failed
Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at https://docs.gradle.org/4.1/userguide/gradle_daemon.html
Please read the following process output to find out more:
-----------------------
-Xmx1536m: illegal argument
usage: java [-options] class
where options include:
-help print out this message
-version print out the build version
-v -verbose turn on verbose mode
-debug enable remote JAVA debugging
-noasyncgc don't allow asynchronous garbage collection
-verbosegc print a message when garbage collection occurs
-noclassgc disable class garbage collection
-ss<number> set the maximum native stack size for any thread
-oss<number> set the maximum Java stack size for any thread
-ms<number> set the initial Java heap size
-mx<number> set the maximum Java heap size
-classpath <directories separated by semicolons>
list directories in which to look for classes
-prof[:<file>] output profiling data to .\java.prof or .\<file>
-verify verify all classes when read in
-verifyremote verify classes read in over the network [default]
-noverify do not verify any class
-nojit disable JIT compiler
Consult IDE log for more details (Help | Show Log)
| 0debug
|
Kubernetes vs. Docker: What Does It Really Mean? : <p>I know that Docker and Kubernetes aren’t direct competitors. Docker is the container platform and containers are coordinated and scheduled by Kubernetes, which is a tool. </p>
<p>What does it really mean and how can I deploy my app on Docker for Azure ? </p>
| 0debug
|
POJO to org.bson.Document and Vice Versa : <p>Is there a simple way to convert Simple POJO to org.bson.Document?</p>
<p>I'm aware that there are ways to do this like this one:</p>
<pre><code>Document doc = new Document();
doc.append("name", person.getName()):
</code></pre>
<p>But does it have a much simpler and typo less way?</p>
| 0debug
|
Is there a way to clone all api of a site like https://www.food2fork.com/ to save it on my own server to continue use in future : <p>The site food to fork served a lot, now it's going to be shutdown soon. So is there a way to clone all its data so we can made it public for all user.</p>
| 0debug
|
plt.show() does nothing when used for the second time : <p>I am just starting to learn data science using python on Data Camp and I noticed something while using the functions in matplotlib.pyplot</p>
<pre><code>import matplotlib.pyplot as plt
year = [1500, 1600, 1700, 1800, 1900, 2000]
pop = [458, 580, 682, 1000, 1650, 6,127]
plt.plot(year, pop)
plt.show() # Here a window opens up and shows the figure for the first time
</code></pre>
<p>but when I try to show it again it doesn't..</p>
<pre><code>plt.show() # for the second time.. nothing happens
</code></pre>
<p>And I have to retype the line above the <code>show()</code> to be able to show a figure again</p>
<p>Is this the normal thing or a problem?</p>
<p>Note: I am using the REPL</p>
| 0debug
|
static int multiwrite_f(BlockDriverState *bs, int argc, char **argv)
{
struct timeval t1, t2;
int Cflag = 0, qflag = 0;
int c, cnt;
char **buf;
int64_t offset, first_offset = 0;
int total = 0;
int nr_iov;
int nr_reqs;
int pattern = 0xcd;
QEMUIOVector *qiovs;
int i;
BlockRequest *reqs;
while ((c = getopt(argc, argv, "CqP:")) != EOF) {
switch (c) {
case 'C':
Cflag = 1;
break;
case 'q':
qflag = 1;
break;
case 'P':
pattern = parse_pattern(optarg);
if (pattern < 0) {
return 0;
}
break;
default:
return qemuio_command_usage(&writev_cmd);
}
}
if (optind > argc - 2) {
return qemuio_command_usage(&writev_cmd);
}
nr_reqs = 1;
for (i = optind; i < argc; i++) {
if (!strcmp(argv[i], ";")) {
nr_reqs++;
}
}
reqs = g_malloc0(nr_reqs * sizeof(*reqs));
buf = g_malloc0(nr_reqs * sizeof(*buf));
qiovs = g_malloc(nr_reqs * sizeof(*qiovs));
for (i = 0; i < nr_reqs && optind < argc; i++) {
int j;
offset = cvtnum(argv[optind]);
if (offset < 0) {
printf("non-numeric offset argument -- %s\n", argv[optind]);
goto out;
}
optind++;
if (offset & 0x1ff) {
printf("offset %lld is not sector aligned\n",
(long long)offset);
goto out;
}
if (i == 0) {
first_offset = offset;
}
for (j = optind; j < argc; j++) {
if (!strcmp(argv[j], ";")) {
break;
}
}
nr_iov = j - optind;
buf[i] = create_iovec(bs, &qiovs[i], &argv[optind], nr_iov, pattern);
if (buf[i] == NULL) {
goto out;
}
reqs[i].qiov = &qiovs[i];
reqs[i].sector = offset >> 9;
reqs[i].nb_sectors = reqs[i].qiov->size >> 9;
optind = j + 1;
pattern++;
}
nr_reqs = i;
gettimeofday(&t1, NULL);
cnt = do_aio_multiwrite(bs, reqs, nr_reqs, &total);
gettimeofday(&t2, NULL);
if (cnt < 0) {
printf("aio_multiwrite failed: %s\n", strerror(-cnt));
goto out;
}
if (qflag) {
goto out;
}
t2 = tsub(t2, t1);
print_report("wrote", &t2, first_offset, total, total, cnt, Cflag);
out:
for (i = 0; i < nr_reqs; i++) {
qemu_io_free(buf[i]);
if (reqs[i].qiov != NULL) {
qemu_iovec_destroy(&qiovs[i]);
}
}
g_free(buf);
g_free(reqs);
g_free(qiovs);
return 0;
}
| 1threat
|
Any way to make Backup Exec choose storage for job properly? : <p>Here is my problem: We are using Backup Exec 16 with 3 drives (2TB each) for storage configured (SAN device with 3 RAID arrays exposed to BE). </p>
<p>Since there is not much space, I had to configure backup jobs to use ANY storage it sees fit, because otherwise it would be a nightmare to balance storage usage. And that is where my problem begins: For some reason Backup Exec tries to do impossible things, like backup 170 GB mailbox database to the storage which have 50GB free, or even to full storage, while there is another storage with over 500GB to do the job. </p>
<p>I thought maybe that 500 GB Free storage was full at time of backup, so I ran backup job manually, but no luck - it still chooses another full storage, instead of proper one.</p>
<p>So, my question is: Is BE supposed to be dumb as rock or is that me misconfigured something?</p>
<p>PS: Also I am not allowed to rebuild those 3 raids into one space. </p>
| 0debug
|
Creating a histogram in python : I have below dataframe. I want to create a simple histogram by sorting number of tweets numbers.
**Source** **Number of Tweets**
Twitter for Android 59472
Twitter for iPhone 27244
Twitter Web Client 9239
Twitter Lite 6479
Twitter for iPad 1159
TweetCaster for Android 407
Twitter for Windows Phone 233
TweetDeck 219
Mobile Web (M2) 197
Twitter for Windows 134
Commun.it 121
Facebook 18
Media Studio 16
MeTweets for Windows Phone 14
Here is the code;
my_plot = data.sort(columns='Number of Tweets',ascending=False).plot(kind='bar',legend=None,title="Tweet Numbers Per Source")
my_plot.set_xlabel("Source")
my_plot.set_ylabel("Tweet Numbers")
but I get below warning;
/home/bd/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py:1: FutureWarning: sort(columns=....) is deprecated, use sort_values(by=.....)
if __name__ == '__main__':
Also; when I code;
my_plot.show()
I get below error message.
AttributeError: 'AxesSubplot' object has no attribute 'show'
How can I fix this ? Any suggestions? Thank you..
| 0debug
|
How can I check if a browser supports WebAssembly? : <p>With support for WebAssembly coming into all new major browsers, how can I check whether the current browser which is visiting my website supports it?</p>
| 0debug
|
def remove_even(str1):
str2 = ''
for i in range(1, len(str1) + 1):
if(i % 2 != 0):
str2 = str2 + str1[i - 1]
return str2
| 0debug
|
static void process_subpacket_9 (QDM2Context *q, QDM2SubPNode *node)
{
GetBitContext gb;
int i, j, k, n, ch, run, level, diff;
init_get_bits(&gb, node->packet->data, node->packet->size*8);
n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1;
for (i = 1; i < n; i++)
for (ch=0; ch < q->nb_channels; ch++) {
level = qdm2_get_vlc(&gb, &vlc_tab_level, 0, 2);
q->quantized_coeffs[ch][i][0] = level;
for (j = 0; j < (8 - 1); ) {
run = qdm2_get_vlc(&gb, &vlc_tab_run, 0, 1) + 1;
diff = qdm2_get_se_vlc(&vlc_tab_diff, &gb, 2);
for (k = 1; k <= run; k++)
q->quantized_coeffs[ch][i][j + k] = (level + ((k*diff) / run));
level += diff;
j += run;
}
}
for (ch = 0; ch < q->nb_channels; ch++)
for (i = 0; i < 8; i++)
q->quantized_coeffs[ch][0][i] = 0;
}
| 1threat
|
static int qemu_rdma_registration_start(QEMUFile *f, void *opaque,
uint64_t flags)
{
QEMUFileRDMA *rfile = opaque;
RDMAContext *rdma = rfile->rdma;
CHECK_ERROR_STATE();
DDDPRINTF("start section: %" PRIu64 "\n", flags);
qemu_put_be64(f, RAM_SAVE_FLAG_HOOK);
qemu_fflush(f);
return 0;
}
| 1threat
|
vb6 insert data into excel from database : I have been looking for a solution to inserting data into excel using vb6 code and access database. There are many cases where I need to write to an excel spreadsheet multiple times with different records of data. I have an existing workbook that I am trying to open and save as when I am complete. so far I have been able to open the excel workbook, target the sheet, and the cells I am writing to, however I can only write to the workbook once and when I leave the scope of the open workbook the connection is gone.
I think i need to build some sort of dictionary so I can store multiple records from the Datasource, but i am just not sure. I can share the current code I have but I didn't know if it would be much help here. So if i have multiple works it will loop through the workbook connection until there are no more records to go through. And a sub routine that creates the workbook object, opens the existing workbook and work sheet, rights to a specified cell number to insert the new data. I have looked at https://support.microsoft.com/en-us/help/247412/methods-for-transferring-data-to-excel-from-visual-basic and it don't seem to have what I am looking for at this time.
Am I making this to complicated or is there a solution for this? Please help. If I need to I will post the code.
| 0debug
|
Exporting a database in phpmyadmin fails (localhost) : <p>When I try to export a database sql file in phpmyadmin it fails. I get the following error: "Your output is incomplete, due to a low execution time limit on PHP level" .</p>
<p>I don't know what to do..</p>
| 0debug
|
static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
unsigned int *wlen)
{
int ret;
ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
if (ret < sizeof(*hdr)) {
error_report("failed to send a req, %s", strerror(errno));
return ret;
}
ret = qemu_co_send(sockfd, data, *wlen);
if (ret < *wlen) {
error_report("failed to send a req, %s", strerror(errno));
}
return ret;
}
| 1threat
|
Inhibit all warnings option in Xcode project doesn't hide warning when building : <ol>
<li><p>Cocoapods inhibit_all_warnings! doesn't set the Pods project "Inhibit all warnings" to "Yes"</p></li>
<li><p>Xcode still displays pods warning after settings Pods project and individual pods "Inhibit all warnings" option to "Yes"</p></li>
</ol>
<p>Cocoapods version: 0.39.0
Xcode version: 7.2</p>
<p>My pod is here:</p>
<pre><code>source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
# ignore all warnings from all pods
inhibit_all_warnings!
pod 'SnapKit', '~> 0.15.0'
pod 'Crashlytics'
pod 'YLGIFImage'
pod 'Fabric'
pod "AFNetworking", "~> 2.0"
pod 'SDWebImage', '~>3.7'
# Changes build active architecture only
post_install do |installer_representation|
installer_representation.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['ONLY_ACTIVE_ARCH'] = 'NO'
end
end
end
</code></pre>
| 0debug
|
static int vc1_decode_sprites(VC1Context *v, GetBitContext* gb)
{
int ret;
MpegEncContext *s = &v->s;
AVCodecContext *avctx = s->avctx;
SpriteData sd;
memset(&sd, 0, sizeof(sd));
ret = vc1_parse_sprites(v, gb, &sd);
if (ret < 0)
return ret;
if (!s->current_picture.f->data[0]) {
av_log(avctx, AV_LOG_ERROR, "Got no sprites\n");
return -1;
}
if (v->two_sprites && (!s->last_picture_ptr || !s->last_picture.f->data[0])) {
av_log(avctx, AV_LOG_WARNING, "Need two sprites, only got one\n");
v->two_sprites = 0;
}
av_frame_unref(v->sprite_output_frame);
if ((ret = ff_get_buffer(avctx, v->sprite_output_frame, 0)) < 0)
return ret;
vc1_draw_sprites(v, &sd);
return 0;
}
| 1threat
|
Microsoft Edge isPersonal SavePersonalAndPaymentData brake React app : <p>I have a simple form, one input and one submit button inside the React app. It works well in every web browsers. Now I started testing in the IE and Edge (<code>Edge/18.17763</code>).</p>
<p>When I hit the submit button I got errors in the console:</p>
<pre><code>Unable to get property 'isPersonal' of undefined or null reference
Unable to get property 'SavePersonalAndPaymentData' of undefined or null reference
</code></pre>
<p>They brake the app completely. Any idea of what they are and where they came from?</p>
<p>I do not have anything remotely related in the codebase to <code>isPersonal</code> and <code>SavePersonalAndPaymentData</code>.</p>
| 0debug
|
Meaning of self.__dict__ = self in a class definition : <p>I'm trying to understand the following snippet of code:</p>
<pre><code>class Config(dict):
def __init__(self):
self.__dict__ = self
</code></pre>
<p>What is the purpose of the line <code>self.__dict__ = self</code>? I suppose it overrides the default <code>__dict__</code> function with something that simply returns the object itself, but since <code>Config</code> inherits from <code>dict</code> I haven't been able to find any difference with the default behavior.</p>
| 0debug
|
VBA to update MS SQL 2014 DB table : I am getting an error when this code attemps to .execute the function "GetinsertText". i am getting an error of "Run-Time '-214721900 (80040e14)': [Microsoft][ODBC SQL Server Driver] [SQL Server] Incorrect syntax near the keyword "open" Option Explicit. i am using the Microsoft ActiveX data object 6.1 as my reference. is it my type of data i am passing which is decimal and dates?
Option Explicit
Const SQLConStr As String = "Driver={SQL Server};Server=test;Database=Test1;User Id=TestTest1;Password=X;"
------------------------------------------
Sub HITBTC_Ticker_DB_Update()
Dim HITBTCupdate As ADODB.Connection
Dim HITBTCcmd As ADODB.Command
Set HITBTCupdate = New ADODB.Connection
Set HITBTCcmd = New ADODB.Command
HITBTCupdate.ConnectionString = SQLConStr
HITBTCupdate.Open
HITBTCcmd.ActiveConnection = HITBTCupdate
HITBTCcmd.CommandText = GetinsertText
HITBTCcmd.Execute
HITBTCupdate.Close
Set HITBTCupdate = Nothing
End Sub
------------------------------------------
Function GetinsertText() As String
Dim SQLstr As String
SQLstr = "INSERT INTO tblBCNBTC(" & _
"Column1.ask, Column1.bid, Column1.last, Column1.open, Column1.low, Column1.high, Column1.volume, Column1.volumeQuote, Column1.timestamp, Column1.symbol)" & " Values(" & _
"0.0000005939', '0.0000005904', '0.0000005922', '0.0000005800', '0.0000005686', '0.0000006000','833783600','485.83049356',#2018-01-26T01:17:08.060Z#,'BCNBTC)"
GetinsertText = SQLstr
End Function
| 0debug
|
how to determine if the input to a function is integer in matlab : I'm writing a code to take an input ( and integer) interpretes the input as year and return the century . the code works fine except for input like cent = centuries ([ 1 2])
,in this case it is supposed to return empty string but it is returning first century . I've used ~isinteger and ~isscalar and y<1 and the likes but its still returning a value. please what can i do here ?
| 0debug
|
static void filter_mb_edgecv( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
const int index_a = qp + h->slice_alpha_c0_offset;
const int alpha = (alpha_table+52)[index_a];
const int beta = (beta_table+52)[qp + h->slice_beta_offset];
if (alpha ==0 || beta == 0) return;
if( bS[0] < 4 ) {
int8_t tc[4];
tc[0] = (tc0_table+52)[index_a][bS[0]]+1;
tc[1] = (tc0_table+52)[index_a][bS[1]]+1;
tc[2] = (tc0_table+52)[index_a][bS[2]]+1;
tc[3] = (tc0_table+52)[index_a][bS[3]]+1;
h->s.dsp.h264_h_loop_filter_chroma(pix, stride, alpha, beta, tc);
} else {
h->s.dsp.h264_h_loop_filter_chroma_intra(pix, stride, alpha, beta);
}
}
| 1threat
|
db.execute('SELECT * FROM employees WHERE id = ' + user_input)
| 1threat
|
NameError: name 'x2' is not defined : <p>I am trying to read data from a senor using my PI and in order to calculate the magnitude to determine acceleration but but I always get the following error when I run a test program</p>
<pre><code>Time elasped: 0
Traceback (most recent call last):
File "MMA7455.py", line 47, in <module>
print("X = ", x2)
NameError: name 'x2' is not defined
</code></pre>
<p>This is the the code that ive been using </p>
<pre><code>def calculateMag():
x = MMA7455.getValueX()
x2 = ((x + 128) % 256) -128
y = MMA7455.getValueY()
y2 = ((y - 240 + 128) % 256) -128
z = MMA7455.getValueZ()
z2 = ((z - 64 + 128) % 256) -128
magnitude = int(math.sqrt((x2*x2) + (y2*y2) + (z2*z2)))
return x2, y2, z2, magnitude
for i in range (1000):
timeGo()
calculateMag()
print("X = ", x2)
print("Y = ", y2)
print("Z = ", z2)
</code></pre>
<p>Ive tried passing x, y, z into the function but this didnt seem to work.Thanks for the help it would be much appreciated.</p>
| 0debug
|
how to speed up this double loop by vectorization in R? : I need to find the minimum distance between coordinates. Unfortunately, my data contains the coordinates in a special coordinate system and i have to calculate the distance by hand.
My double for loop (code below) is far too slow. Can someone help me vectorizing my loop?
for (i in 1:nrow(d.small)) {
cat(i, " ")
for ( j in 1:nrow(haltestelle.small)) {
diff.ost <- d.small[i, .(GKODE)] - haltestelle.small[j, .(y_Koord_Ost)]
diff.nord <- d.small[i, .(GKODN)] - haltestelle.small[j, .(x_Koord_Nord)]
dist.oev[i,1] <- min(sqrt(diff.ost^2 + diff.nord^2))
dist.oev[i,2] <- which.min(sqrt(diff.ost^2 + diff.nord^2))
}
}
| 0debug
|
show account chooser every time with GoogleSignInApi : <p>I am using the new GoogleSignInApi that was introduced in play services 8.3. It remembers the last selected account and doesn't show account picker from 2nd time onwards. But I want it to let user choose account every time. Looks like the clearDefaultAccountAndReconnect() method of GoogleApiClient is not allowed to be used with googleSignInApi. Is there any way to achieve this without implementing a custom account chooser? I am on play services 8.3 and google services 1.5.0.</p>
| 0debug
|
static void imx_eth_write(void *opaque, hwaddr offset, uint64_t value,
unsigned size)
{
IMXFECState *s = IMX_FEC(opaque);
uint32_t index = offset >> 2;
FEC_PRINTF("reg[%s] <= 0x%" PRIx32 "\n", imx_eth_reg_name(s, index),
(uint32_t)value);
switch (index) {
case ENET_EIR:
s->regs[index] &= ~value;
break;
case ENET_EIMR:
s->regs[index] = value;
break;
case ENET_RDAR:
if (s->regs[ENET_ECR] & ENET_ECR_ETHEREN) {
if (!s->regs[index]) {
s->regs[index] = ENET_RDAR_RDAR;
imx_eth_enable_rx(s);
}
} else {
s->regs[index] = 0;
}
break;
case ENET_TDAR:
if (s->regs[ENET_ECR] & ENET_ECR_ETHEREN) {
s->regs[index] = ENET_TDAR_TDAR;
imx_eth_do_tx(s);
}
s->regs[index] = 0;
break;
case ENET_ECR:
if (value & ENET_ECR_RESET) {
return imx_eth_reset(DEVICE(s));
}
s->regs[index] = value;
if ((s->regs[index] & ENET_ECR_ETHEREN) == 0) {
s->regs[ENET_RDAR] = 0;
s->rx_descriptor = s->regs[ENET_RDSR];
s->regs[ENET_TDAR] = 0;
s->tx_descriptor = s->regs[ENET_TDSR];
}
break;
case ENET_MMFR:
s->regs[index] = value;
if (extract32(value, 29, 1)) {
s->regs[ENET_MMFR] = deposit32(s->regs[ENET_MMFR], 0, 16,
do_phy_read(s,
extract32(value,
18, 10)));
} else {
do_phy_write(s, extract32(value, 18, 10), extract32(value, 0, 16));
}
s->regs[ENET_EIR] |= ENET_INT_MII;
break;
case ENET_MSCR:
s->regs[index] = value & 0xfe;
break;
case ENET_MIBC:
s->regs[index] = (value & 0x80000000) ? 0xc0000000 : 0;
break;
case ENET_RCR:
s->regs[index] = value & 0x07ff003f;
break;
case ENET_TCR:
s->regs[index] = value;
if (value & 1) {
s->regs[ENET_EIR] |= ENET_INT_GRA;
}
break;
case ENET_PALR:
s->regs[index] = value;
s->conf.macaddr.a[0] = value >> 24;
s->conf.macaddr.a[1] = value >> 16;
s->conf.macaddr.a[2] = value >> 8;
s->conf.macaddr.a[3] = value;
break;
case ENET_PAUR:
s->regs[index] = (value | 0x0000ffff) & 0xffff8808;
s->conf.macaddr.a[4] = value >> 24;
s->conf.macaddr.a[5] = value >> 16;
break;
case ENET_OPD:
s->regs[index] = (value & 0x0000ffff) | 0x00010000;
break;
case ENET_IAUR:
case ENET_IALR:
case ENET_GAUR:
case ENET_GALR:
break;
case ENET_TFWR:
if (s->is_fec) {
s->regs[index] = value & 0x3;
} else {
s->regs[index] = value & 0x13f;
}
break;
case ENET_RDSR:
if (s->is_fec) {
s->regs[index] = value & ~3;
} else {
s->regs[index] = value & ~7;
}
s->rx_descriptor = s->regs[index];
break;
case ENET_TDSR:
if (s->is_fec) {
s->regs[index] = value & ~3;
} else {
s->regs[index] = value & ~7;
}
s->tx_descriptor = s->regs[index];
break;
case ENET_MRBR:
s->regs[index] = value & 0x00003ff0;
break;
default:
if (s->is_fec) {
imx_fec_write(s, index, value);
} else {
imx_enet_write(s, index, value);
}
return;
}
imx_eth_update(s);
}
| 1threat
|
How to manually plug in values in an array of strings? : <p>I often have a problem picking up what movie I should watch. So, I decided to make a simple program to randomize my pick but got stuck on the first step. <strong>I want to know how to assign Strings - that are the movie names- to an array. Here is my unfinished code</strong></p>
<pre><code> Scanner input = new Scanner(System.in);
System.out.println("How many movies are you considering?");
int number = input.nextInt();
String[] movies = new String[number];
System.out.println("Enter movie titles...");
for(int i=1; i <= number; i++){
System.out.print(i + "- ");
movies[i] = input.next();
System.out.println();
}
</code></pre>
| 0debug
|
void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
{
struct capture_callback *cb;
for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
if (cb->opaque == cb_opaque) {
cb->ops.destroy (cb_opaque);
QLIST_REMOVE (cb, entries);
g_free (cb);
if (!cap->cb_head.lh_first) {
SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
while (sw) {
SWVoiceCap *sc = (SWVoiceCap *) sw;
#ifdef DEBUG_CAPTURE
dolog ("freeing %s\n", sw->name);
#endif
sw1 = sw->entries.le_next;
if (sw->rate) {
st_rate_stop (sw->rate);
sw->rate = NULL;
}
QLIST_REMOVE (sw, entries);
QLIST_REMOVE (sc, entries);
g_free (sc);
sw = sw1;
}
QLIST_REMOVE (cap, entries);
g_free (cap);
}
return;
}
}
}
| 1threat
|
Why is dplyr so slow? : <p>Like most people, I'm impressed by Hadley Wickham and what he's done for <code>R</code> -- so i figured that i'd move some functions toward his <code>tidyverse</code> ... having done so i'm left wondering what the point of it all is? </p>
<p>My new <code>dplyr</code> functions are <strong>much slower</strong> than their base equivalents -- i hope i'm doing something wrong. I'd particularly like some payoff from the effort required to understand <code>non-standard-evaluation</code>.</p>
<p>So, what am i doing wrong? Why is <code>dplyr</code> so slow?</p>
<p>An example: </p>
<pre><code>require(microbenchmark)
require(dplyr)
df <- tibble(
a = 1:10,
b = c(1:5, 4:0),
c = 10:1)
addSpread_base <- function() {
df[['spread']] <- df[['a']] - df[['b']]
df
}
addSpread_dplyr <- function() df %>% mutate(spread := a - b)
all.equal(addSpread_base(), addSpread_dplyr())
microbenchmark(addSpread_base(), addSpread_dplyr(), times = 1e4)
</code></pre>
<p>Timing results: </p>
<pre><code>Unit: microseconds
expr min lq mean median uq max neval
addSpread_base() 12.058 15.769 22.07805 24.58 26.435 2003.481 10000
addSpread_dplyr() 607.537 624.697 666.08964 631.19 636.291 41143.691 10000
</code></pre>
<p>So using <code>dplyr</code> functions to transform the data takes about 30x longer -- surely this isn't the intention? </p>
<p>I figured that perhaps this is too easy a case -- and that <code>dplyr</code> would really shine if we had a more realistic case where we are adding a column and sub-setting the data -- but this was worse. As you can see from the timings below, this is ~70x slower than the base approach. </p>
<pre><code># mutate and substitute
addSpreadSub_base <- function(df, col1, col2) {
df[['spread']] <- df[['a']] - df[['b']]
df[, c(col1, col2, 'spread')]
}
addSpreadSub_dplyr <- function(df, col1, col2) {
var1 <- as.name(col1)
var2 <- as.name(col2)
qq <- quo(!!var1 - !!var2)
df %>%
mutate(spread := !!qq) %>%
select(!!var1, !!var2, spread)
}
all.equal(addSpreadSub_base(df, col1 = 'a', col2 = 'b'),
addSpreadSub_dplyr(df, col1 = 'a', col2 = 'b'))
microbenchmark(addSpreadSub_base(df, col1 = 'a', col2 = 'b'),
addSpreadSub_dplyr(df, col1 = 'a', col2 = 'b'),
times = 1e4)
</code></pre>
<p>Results: </p>
<pre><code>Unit: microseconds
expr min lq mean median uq max neval
addSpreadSub_base(df, col1 = "a", col2 = "b") 22.725 30.610 44.3874 45.450 53.798 2024.35 10000
addSpreadSub_dplyr(df, col1 = "a", col2 = "b") 2748.757 2837.337 3011.1982 2859.598 2904.583 44207.81 10000
</code></pre>
| 0debug
|
static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
{
MatroskaCluster cluster = { 0 };
EbmlList *blocks_list;
MatroskaBlock *blocks;
int i, res;
int64_t pos = url_ftell(matroska->ctx->pb);
matroska->prev_pkt = NULL;
if (matroska->has_cluster_id){
res = ebml_parse_id(matroska, matroska_clusters,
MATROSKA_ID_CLUSTER, &cluster);
pos -= 4;
matroska->has_cluster_id = 0;
} else
res = ebml_parse(matroska, matroska_clusters, &cluster);
blocks_list = &cluster.blocks;
blocks = blocks_list->elem;
for (i=0; i<blocks_list->nb_elem; i++)
if (blocks[i].bin.size > 0) {
int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
res=matroska_parse_block(matroska,
blocks[i].bin.data, blocks[i].bin.size,
blocks[i].bin.pos, cluster.timecode,
blocks[i].duration, is_keyframe,
pos);
}
ebml_free(matroska_cluster, &cluster);
if (res < 0) matroska->done = 1;
return res;
}
| 1threat
|
How to add an element to a existing json array : I have a JSON object:
var data = [{"name":"albin"},{"name, "alvin"}];
How can I add an element to all the records?
I want to add "age":"18" to all the records:
[{"name":"albin", "age":"18"},{"name, "alvin", "age":"18"}];
| 0debug
|
What is an alternative of textarea in react-native? : <p>Is there any built in text area component for react-native? I have tried to implement these ones:</p>
<p><a href="https://github.com/buildo/react-autosize-textarea" rel="noreferrer">https://github.com/buildo/react-autosize-textarea</a></p>
<p><a href="https://github.com/andreypopp/react-textarea-autosize" rel="noreferrer">https://github.com/andreypopp/react-textarea-autosize</a></p>
<p>but getting an error "Expected a component class got object object".</p>
| 0debug
|
static void get_cpuid_vendor(CPUX86State *env, uint32_t *ebx,
uint32_t *ecx, uint32_t *edx)
{
*ebx = env->cpuid_vendor1;
*edx = env->cpuid_vendor2;
*ecx = env->cpuid_vendor3;
if (kvm_enabled() && env->cpuid_vendor_override) {
host_cpuid(0, 0, NULL, ebx, ecx, edx);
}
}
| 1threat
|
HOW TO MAKE LINKS, BUTTONS, DIVS HOVER ON A MOBILE DEVICE? : I'm a beginner in HTML/CSS and I am having trouble making elements hover on a mobile device.
In my CSS, I type something like:
.button:hover {
background-color: #fff;
}
This seems to hover fine on my desktop, however on my iPhone and other touch devices, I can't seem to make the button hover which makes you feel detached from the website when you click on buttons and links etc.
I hope someone can help me on this– I would appreciate any possible solutions.
Kind regards,
Billy
| 0debug
|
static int decode_hybrid(const uint8_t *sptr, uint8_t *dptr, int dx, int dy,
int h, int w, int stride, const uint32_t *pal)
{
int x, y;
const uint8_t *orig_src = sptr;
for (y = dx + h; y > dx; y--) {
uint8_t *dst = dptr + (y * stride) + dy * 3;
for (x = 0; x < w; x++) {
if (*sptr & 0x80) {
unsigned c = AV_RB16(sptr) & ~0x8000;
unsigned b = c & 0x1F;
unsigned g = (c >> 5) & 0x1F;
unsigned r = c >> 10;
*dst++ = (b << 3) | (b >> 2);
*dst++ = (g << 3) | (g >> 2);
*dst++ = (r << 3) | (r >> 2);
sptr += 2;
} else {
uint32_t c = pal[*sptr++];
bytestream_put_le24(&dst, c);
}
}
}
return sptr - orig_src;
}
| 1threat
|
MIUI 10 doesn't let service start activity - Xiaomi Redmi Note : <p>My app has a service and an activity. From the service, activity is called with following code:</p>
<pre><code>Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
</code></pre>
<p>even without the flags, normally the activity window is displayed with its correct layout.
However, on Xiaomi Redmi Note 4 with Android 7, activity layout is not displayed. I only see the following line on logcat:</p>
<blockquote>
<p>I/Timeline: Timeline: Activity_launch_request time:281438674
intent:Intent { flg=0x30000000 cmp=com.test.app/.MainActivity }</p>
</blockquote>
<p>I believe this is not an Android 7 (API 24) issue because on another device with Android 7, service can successfully start the activity.
I guess, MIUI is preventing the launch of the activity from service.</p>
<p>I tried changing how the activity was defined in the manifest. I also tried with several different flags.
All of my tests failed. I could not succeed in starting the activity. Worst issue is that there is no error/exception in the logs.</p>
<p>Any ideas on this please ?</p>
| 0debug
|
Set current time to yyyy-MM-dd using swift : the code I've used is working but I have a problem. For example, when the minute is 02, it says 2. I want it to be 02. He writes without 0. Do you help me share the code?
@objc func tick() {
var calendar = Calendar(identifier: .iso8601)
calendar.timeZone = NSTimeZone.local
let currentDay = calendar.component(.day, from: Date())
let currentMonth = calendar.component(.month, from: Date())
let currentYear = calendar.component(.year, from: Date())
let currentHour = calendar.component(.hour, from: Date())
let currentHour1 = calendar.component(.minute, from: Date())
labelTimer.text = String (currentDay) + ("/") + String (currentMonth) + ("/") + String (currentYear) + ("/") + String (currentHour) + (":") + String (currentHour1)
}
| 0debug
|
void qmp_xen_save_devices_state(const char *filename, Error **errp)
{
QEMUFile *f;
QIOChannelFile *ioc;
int saved_vm_running;
int ret;
saved_vm_running = runstate_is_running();
vm_stop(RUN_STATE_SAVE_VM);
global_state_store_running();
ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT, 0660, errp);
if (!ioc) {
goto the_end;
}
qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
f = qemu_fopen_channel_output(QIO_CHANNEL(ioc));
ret = qemu_save_device_state(f);
qemu_fclose(f);
if (ret < 0) {
error_setg(errp, QERR_IO_ERROR);
}
the_end:
if (saved_vm_running) {
vm_start();
}
}
| 1threat
|
Java : Date ( next day ) : <p>As part of a college assignment we were given a Date class and told to make some modifications. Stuck on the nextDay() method, and why it won't implement. I have a test class and understand how that works so its just that code snippet. Any help and/or explanations appreciated</p>
<pre><code> public class Date
{
private int month; // 1-12
private int day; // 1-31 based on month
private int year; // any year
private static final int[] daysPerMonth = // days in each month
{ 0,31,28,31,30,31,30,31,31,30,31,30,31 };
//constructor: call checkMonth to confirm proper value for month
//call checkDay to confirm proper value for day
public Date( int theDay, int theMonth, int theYear )
{
month = checkMonth( theMonth );//validate moth
year = theYear; // could validate year
day = checkDay( theDay ); //validate day
System.out.printf(
"Date object constructor for date %s\n", this );
}// end Date constructor
//method to return day
public int getDay()
{
return day;
}// end method getDay
// method to return month
public int getMonth()
{
return month;
}//end method getMonth
//method to get year
public int getYear()
{
return year;
}//end method getYear
//utility method to confirm proper month value
private int checkMonth( int testMonth )
{
if ( testMonth > 0 && testMonth <= 12 ) //validate month
return testMonth;
else // month is invalid
throw new IllegalArgumentException(" month must be 1-12" );
}// end method check month
// utilty method to confirm proper day value based on month and year
private int checkDay( int testDay )
{
// check if day in range for month
if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
return testDay;
if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||
( year % 4 == 0 && year % 100 != 0 ) ) )
return testDay;
throw new IllegalArgumentException(
"day out of range for the specified month and year" );
}// end method check day
public String toString()
{
return String.format( "%d-%d-%d", day, month, year );
}// end method toString
public void setDate ( int d, int m, int y )
{
setDay( d );
setMonth( m );
setYear( y );
}
public void setDay( int d )
{
// check if day in range for month
if ( d > 0 && d <= daysPerMonth[ month ] )
day = d;
if ( month == 2 && d == 29 && ( year % 400 == 0 ||
( year % 4 == 0 && year % 100 != 0 ) ) )
day = d;
throw new IllegalArgumentException(
"day out of range for the specified month and year" );
}
public void setMonth( int m )
{
if ( m> 0 && m <= 12 ) //validate month
month = m;
else // month is invalid
throw new IllegalArgumentException(" month must be 1-12" );
}
public void setYear( int y )
{
year = y;
}
public String toString2()
{
return String.format( "%2d - %2d - %4d ", getDay(), getMonth(), getYear() );
}
public void nextDay()
{
getDay();
day = day++;
return day;
//if( d = daysPerMonth[ month ] )
// return day = 1 && month++;
//else if( m = 2 && d = 28 )
// return day++ && m= 2;
//else if( m = 12 && d = 31 )
// return m = 1 && d = 1 ;
}
</code></pre>
<p>}</p>
<p>// end class date</p>
| 0debug
|
React - How to check if JWT is valid before sending a post request? : <p>another noob question. I'm logging in my user to the system using JWT authorization, getting the token and saving it in <code>localstorage</code> and then sending a post request that saves data (its a big form basically). Problem is, the sever is invalidating the token after a given time (20 minutes or so) and so, some of my post requests are returning <code>401 status</code>. How to verify (and if needed, show a login prompt) before sending the post request? I'm using <code>redux-form</code> to make my forms. </p>
<p>P.S: I know I'm supposed to use action creators and such, but I'm still a newbie, so not very good at those stuff. </p>
<p>here's my authentication: </p>
<pre><code>export function loginUser(creds) {
const data = querystring.stringify({_username: creds.username, _password: creds.password});
let config = {
method: 'POST',
headers: { 'Content-Type':'application/x-www-form-urlencoded' },
body: data
};
return dispatch => {
// We dispatch requestLogin to kickoff the call to the API
dispatch(requestLogin(creds));
return fetch(BASE_URL+'/login_check', config)
.then(response =>
response.json().then(user => ({ user, response }))
).then(({ user, response }) => {
if (!response.ok) {
// If there was a problem, we want to
// dispatch the error condition
dispatch(loginError(user.message));
return Promise.reject(user)
} else {
// If login was successful, set the token in local storage
localStorage.setItem('id_token', user.token);
let token = localStorage.getItem('id_token')
console.log(token);
// Dispatch the success action
dispatch(receiveLogin(user));
}
}).catch(err => console.log("Error: ", err))
}
}
</code></pre>
<p>and here's the <code>POST</code> request (I'm getting the <code>values</code> object from <code>redux-form</code>)</p>
<pre><code>const token = localStorage.getItem('id_token');
const AuthStr = 'Bearer '.concat(token);
let headers ={
headers: { 'Content-Type':'application/json','Authorization' : AuthStr }
};
export default (async function showResults(values, dispatch) {
axios.post(BASE_URL + '/new', values, headers)
.then(function (response) {
console.log(values);
console.log(response);
})
.catch(function (error) {
console.log(token);
console.log(values)
console.log(error.response);
});
});
</code></pre>
<p>P.P.S: if anyone has any suggestion for improving my code, feel free to comment.</p>
| 0debug
|
My app's system alert showing wrongly on 'phone' app : Please find the scenario below,
- My app asks permission for push notification through system alert
- At that time, phone call comes
- Now that system alert is howing above the phone app
Please provide the solution for the above
| 0debug
|
Why does console.log(undefined) works sometimes but not others? : <h2>Consider this code:</h2>
<pre><code>function x(){
console.log(y);
}
x();
var t = x();
console.log(t);
</code></pre>
<p>This will throw an error. But if you comment the first console.log inside the function, it will work and print <code>undefined</code>.</p>
<p>What is the explanation of this behavior.</p>
<p>Thank you.</p>
| 0debug
|
I am trying to set a value to an already string labeled radio button. I do not understand my mistake. :
public class RoomListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
double roomtype;
if (event.getSource() == room1)
roomtype = 60;
else if (event.getSource() == room2)
roomtype = 75;
else
roomtype = 100;
}
}
public class CostListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
double NightLength, roomNumber, cost;
String NightText = NumberOfNights.getText();
String RoomText = NumberOfRooms.getText();
NightLength = Double.parseDouble(NightText);
roomNumber = Double.parseDouble(RoomText);
RoomListener.actionPerformed(RoomType);
cost = roomtype * NightLength * roomNumber;
CostCalculation.setText(Double.toString(cost));
NumberFormat fmt = NumberFormat.getNumberInstance();
CostCalculation.setText(fmt.format(cost));
}
}
| 0debug
|
static uint32_t suov32(CPUTriCoreState *env, int64_t arg)
{
uint32_t ret;
int64_t max_pos = UINT32_MAX;
if (arg > max_pos) {
env->PSW_USB_V = (1 << 31);
env->PSW_USB_SV = (1 << 31);
ret = (target_ulong)max_pos;
} else {
if (arg < 0) {
env->PSW_USB_V = (1 << 31);
env->PSW_USB_SV = (1 << 31);
ret = 0;
} else {
env->PSW_USB_V = 0;
ret = (target_ulong)arg;
}
}
env->PSW_USB_AV = arg ^ arg * 2u;
env->PSW_USB_SAV |= env->PSW_USB_AV;
return ret;
}
| 1threat
|
Custom Number.prototype working with variable but NOT working directly with number : <p>I have included custom Number.prototype in my JS as below:</p>
<pre><code>Number.prototype.isBetween = function (first, last) {
return (first < last ? this >= first && this <= last : this >= last && this <= first);
};
</code></pre>
<p>This is working as expected with below code:</p>
<pre><code>var a = 40;
a.isBetween(10,50)
</code></pre>
<p><strong>Result :</strong>
true</p>
<p>But when i try to execute as below, it is throwing an error:</p>
<pre><code>40.isBetween(10,50)
</code></pre>
<p><strong>Result :</strong>
Uncaught SyntaxError: Invalid or unexpected token</p>
<p>How to make this(40.isBetween(10,50)) work?</p>
| 0debug
|
how has-a-relationship is said to be composition? : <p>I have searched books read through website but cannot get a justified answer.
whats is the proper meaning of composition and how we attain has-a-relationship in the program.</p>
| 0debug
|
int avpriv_exif_decode_ifd(AVCodecContext *avctx, GetByteContext *gbytes, int le,
int depth, AVDictionary **metadata)
{
int i, ret;
int entries;
entries = ff_tget_short(gbytes, le);
if (bytestream2_get_bytes_left(gbytes) < entries * 12) {
return AVERROR_INVALIDDATA;
}
for (i = 0; i < entries; i++) {
if ((ret = exif_decode_tag(avctx, gbytes, le, depth, metadata)) < 0) {
return ret;
}
}
return ff_tget_long(gbytes, le);
}
| 1threat
|
static inline int pic_is_unused(MpegEncContext *s, Picture *pic)
{
if (pic->f->buf[0] == NULL)
return 1;
if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
return 1;
return 0;
}
| 1threat
|
Angular UI Bootstrap Pagination ng-model not updating : <p>I am trying to use a UI Bootstrap Pagination directive in my project, but for some strange reason the ng-model used for updating the current page is not working. The pagination is showing up correctly with the correct number of tabs and everything, but when I click on a different number, the ng-model variable is not getting updated. For the life of me, I can't figure out why not.</p>
<p>The code I am using is taken from the examples on the UI Bootstrap homepage:</p>
<pre><code><uib-pagination total-items="totalItems" ng-model="currentPage"
ng-change="pageChanged()"></uib-pagination>
</code></pre>
<p>The controller looks like this: </p>
<pre><code>$scope.currentPage = 1;
$scope.totalItems = 160;
$scope.pageChanged = function() {
console.log('Page changed to: ' + $scope.currentPage);
};
</code></pre>
<p>Here are the different required sources I am including:</p>
<pre><code><link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.0.3.js"></script>
</code></pre>
<p>The strangest thing is I have created a plnkr which replicates my code and it works! You can see here: <a href="http://plnkr.co/edit/4DoKnRACbKjLnMH5vGB6">http://plnkr.co/edit/4DoKnRACbKjLnMH5vGB6</a></p>
<p>Can anybody think of any ideas that might be causing this not to work? I'm scratching my head here, and can't think of anything obvious I am doing wrong...</p>
<p>All help much apprecatiated!</p>
| 0debug
|
def check_Equality(s):
return (ord(s[0]) == ord(s[len(s) - 1]));
def count_Substring_With_Equal_Ends(s):
result = 0;
n = len(s);
for i in range(n):
for j in range(1,n-i+1):
if (check_Equality(s[i:i+j])):
result+=1;
return result;
| 0debug
|
cannot use function (type func()) as type in argument to Golang : package main
import (
"log"
"strings"
"go.scope.charter.com/busboy"
)
/*
Trivial service to demonstrate chaining service together
Message starts in originator, travels through a couple formatters, and then gets back to originator
*/
type MessageTest struct {
Body string `json:"body"`
}
var s *busboy.Service
func main() {
var (
err error
cid string
)
//var m MessageDelivery
var g busboy.MessageHandler
g = UpperCaseHandler
// UpperCaser := busboy.NewService("UpperCaser", "", false)
UpperCaser := busboy.NewService("UpperCaser")
if err = UpperCaser.ConsumeFunc("rio-service-uc", []string{"rio-service-uc"},func() interface{} {
return ""
},g); err != nil {
log.Fatalf("Error starting consumer: %v", err)
}
// Repeater := busboy.NewService("Repeater", "", false)
Repeater := busboy.NewService("Repeater")
if err = Repeater.ConsumeFunc("rio-service-repeat", []string{"rio-service-repeat"}, func() interface{} {
return ""
}, RepeatHandler); err != nil {
//if err = Repeater.ConsumeFunc("rio-service-repeat", []string{"rio-service-repeat"}, mg busboy.MessageGenerator, mh busboy.MessageHandler); err != nil {
log.Fatalf("Error starting consumer: %v", err)
}
// originator := busboy.NewService("Originator", "", false)
originator := busboy.NewService("Originator")
deliveryChan := make(chan busboy.MessageDelivery)
m := busboy.MessagePublishing{
Message: MessageTest{"this is a test"},
RoutingKeys: []string{"rio-service-uc", "rio-service-repeat"},
}
if cid, err = originator.RPCPublish(m, deliveryChan); err != nil {
log.Fatalf("Failed to publish: %v", err)
}
message := <-deliveryChan
log.Printf("Originator Got: %+v", message.Message)
originator.RemoveQueue(cid)
UpperCaser.Wait()
}
func UpperCaseHandler(md busboy.MessageDelivery) {
s.Reply(MessageTest{strings.ToUpper(md.Message.(string))}, md.Delivery)
}
func RepeatHandler(md busboy.MessageDelivery) {
s.Reply(MessageTest{strings.Repeat(md.Message.(string), 5)}, md.Delivery)
}
package busboy
> Error
>
>./chains.go:26:10: cannot use UpperCaseHandler (typefunc(busboy.MessageDelivery)) as type busboy.MessageHandler in
> assignment
>./chains.go:37:86: cannot use RepeatHandler (type func(busboy.MessageDelivery)) as type busboy.MessageHandler in
> argument to Repeater.ConsumeFunc
type MessageDelivery struct {
Delivery amqp.Delivery
Message interface{}
Error error
Context *Context
}
type MessageGenerator func() interface{}
> I tried running the code,where am i going wrong,how do i right pass
> function as argument to another function. The function returns
> interface and error. Though function is taking MessageDelivery Struct as argument,function signature is same.where am i going wrong
| 0debug
|
static void *qemu_dummy_cpu_thread_fn(void *arg)
{
#ifdef _WIN32
fprintf(stderr, "qtest is not supported under Windows\n");
exit(1);
#else
CPUState *cpu = arg;
sigset_t waitset;
int r;
qemu_mutex_lock_iothread();
qemu_thread_get_self(cpu->thread);
cpu->thread_id = qemu_get_thread_id();
cpu->exception_index = -1;
cpu->can_do_io = 1;
sigemptyset(&waitset);
sigaddset(&waitset, SIG_IPI);
cpu->created = true;
qemu_cond_signal(&qemu_cpu_cond);
current_cpu = cpu;
while (1) {
current_cpu = NULL;
qemu_mutex_unlock_iothread();
do {
int sig;
r = sigwait(&waitset, &sig);
} while (r == -1 && (errno == EAGAIN || errno == EINTR));
if (r == -1) {
perror("sigwait");
exit(1);
}
qemu_mutex_lock_iothread();
current_cpu = cpu;
qemu_wait_io_event_common(cpu);
}
return NULL;
#endif
}
| 1threat
|
Single vs Double quotes in Julia : <p>What is the difference between single quotes and double quotes in Julia?</p>
<p>Unlike Python, for strings, it doesn't allow single quotes:</p>
<pre><code>> s = 'abc'
syntax: invalid character literal
> s = "abc"
> print(s)
abc
</code></pre>
<p>But when trying to single quote a double quote, it's allowed:</p>
<pre><code>> s = '"'
> print(s)
"
</code></pre>
<p><strong>What is the single quote use for in Julia? Is there documentation like Python's PEP to explain for reason why single quotes are not used?</strong> </p>
| 0debug
|
static inline void gen_arm_shift_reg(TCGv var, int shiftop,
TCGv shift, int flags)
{
if (flags) {
switch (shiftop) {
case 0: gen_helper_shl_cc(var, var, shift); break;
case 1: gen_helper_shr_cc(var, var, shift); break;
case 2: gen_helper_sar_cc(var, var, shift); break;
case 3: gen_helper_ror_cc(var, var, shift); break;
}
} else {
switch (shiftop) {
case 0: gen_helper_shl(var, var, shift); break;
case 1: gen_helper_shr(var, var, shift); break;
case 2: gen_helper_sar(var, var, shift); break;
case 3: tcg_gen_andi_i32(shift, shift, 0x1f);
tcg_gen_rotr_i32(var, var, shift); break;
}
}
dead_tmp(shift);
}
| 1threat
|
SQL request with JOUN and COUNT : [I cant make a database query, as in this picture][1]
[1]: http://i.stack.imgur.com/5o6lv.png
| 0debug
|
Google Drive API V3 (javascript) update file contents : <p>I want to update the contents of a Google doc using the Google Drive API V3 (javascript):</p>
<p><a href="https://developers.google.com/drive/v3/reference/files/update" rel="noreferrer">https://developers.google.com/drive/v3/reference/files/update</a></p>
<p>I'm able to update the file metadata (such as the name) but the documentation doesn't include patch semantics for the actual file content. Is there a way to pass a <code>JSON.stringify()</code> value as a param in the <code>gapi.client.drive.files.update</code> request:</p>
<pre><code>var request = gapi.client.drive.files.update({
'fileId': fileId,
'name' : 'Updated File Name',
'uploadType': 'media',
'mimeType' : 'application/vnd.google-apps.document'
});
var fulfilledCallback = function(fulfilled) {
console.log("Update fulfilled!", fulfilled);
};
var rejectedCallback = function(rejected) {
console.log("Update rejected!", rejected);
};
request.then(fulfilledCallback, rejectedCallback)
</code></pre>
| 0debug
|
Deep Learning + ML + CV > Requirements.txt file : <p>I need to know any place or link or personal requirements.txt for either ML , DL or Computer Vision. It will save my time to install all again . </p>
<p>I also need help me in making Ubuntu image st to port environments to other computer.</p>
| 0debug
|
Main Thread Checker: UI API called on a background thread: -[UIApplication applicationState] : <p>I am using google maps in Xcode 9 beta, iOS 11.</p>
<p>I am getting an error outputted to the log as follows:</p>
<blockquote>
<p>Main Thread Checker: UI API called on a background thread: -[UIApplication applicationState]
PID: 4442, TID: 837820, Thread name: com.google.Maps.LabelingBehavior, Queue name: com.apple.root.default-qos.overcommit, QoS: 21</p>
</blockquote>
<p>Why would this be occurring as I am almost certain I'm not altering any interface elements from the main thread in my code.</p>
<pre class="lang-html prettyprint-override"><code> override func viewDidLoad() {
let locationManager = CLLocationManager()
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
viewMap.delegate = self
let camera = GMSCameraPosition.camera(withLatitude: 53.7931183329367, longitude: -1.53649874031544, zoom: 17.0)
viewMap.animate(to: camera)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {
}
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
if(moving > 1){
moving = 1
UIView.animate(withDuration: 0.5, delay: 0, animations: {
self.topBarConstraint.constant = self.topBarConstraint.constant + (self.topBar.bounds.height / 2)
self.bottomHalfConstraint.constant = self.bottomHalfConstraint.constant + (self.topBar.bounds.height / 2)
self.view.layoutIfNeeded()
}, completion: nil)
}
moving = 1
}
// Camera change Position this methods will call every time
func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
moving = moving + 1
if(moving == 2){
UIView.animate(withDuration: 0.5, delay: 0, animations: {
self.topBarConstraint.constant = self.topBarConstraint.constant - (self.topBar.bounds.height / 2)
self.bottomHalfConstraint.constant = self.bottomHalfConstraint.constant - (self.topBar.bounds.height / 2)
self.view.layoutIfNeeded()
}, completion: nil)
}
DispatchQueue.main.async {
print("Moving: \(moving) Latitude: \(self.viewMap.camera.target.latitude)")
print("Moving: \(moving) Longitude: \(self.viewMap.camera.target.longitude)")
}
}
</code></pre>
| 0debug
|
static int img_commit(int argc, char **argv)
{
int c, ret, flags;
const char *filename, *fmt, *cache, *base;
BlockBackend *blk;
BlockDriverState *bs, *base_bs;
BlockJob *job;
bool progress = false, quiet = false, drop = false;
bool writethrough;
Error *local_err = NULL;
CommonBlockJobCBInfo cbi;
bool image_opts = false;
AioContext *aio_context;
fmt = NULL;
cache = BDRV_DEFAULT_CACHE;
base = NULL;
for(;;) {
static const struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"object", required_argument, 0, OPTION_OBJECT},
{"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
{0, 0, 0, 0}
};
c = getopt_long(argc, argv, "f:ht:b:dpq",
long_options, NULL);
if (c == -1) {
break;
}
switch(c) {
case '?':
case 'h':
help();
break;
case 'f':
fmt = optarg;
break;
case 't':
cache = optarg;
break;
case 'b':
base = optarg;
drop = true;
break;
case 'd':
drop = true;
break;
case 'p':
progress = true;
break;
case 'q':
quiet = true;
break;
case OPTION_OBJECT: {
QemuOpts *opts;
opts = qemu_opts_parse_noisily(&qemu_object_opts,
optarg, true);
if (!opts) {
return 1;
}
} break;
case OPTION_IMAGE_OPTS:
image_opts = true;
break;
}
}
if (quiet) {
progress = false;
}
if (optind != argc - 1) {
error_exit("Expecting one image file name");
}
filename = argv[optind++];
if (qemu_opts_foreach(&qemu_object_opts,
user_creatable_add_opts_foreach,
NULL, NULL)) {
return 1;
}
flags = BDRV_O_RDWR | BDRV_O_UNMAP;
ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
if (ret < 0) {
error_report("Invalid cache option: %s", cache);
return 1;
}
blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
if (!blk) {
return 1;
}
bs = blk_bs(blk);
qemu_progress_init(progress, 1.f);
qemu_progress_print(0.f, 100);
if (base) {
base_bs = bdrv_find_backing_image(bs, base);
if (!base_bs) {
error_setg(&local_err,
"Did not find '%s' in the backing chain of '%s'",
base, filename);
goto done;
}
} else {
base_bs = backing_bs(bs);
if (!base_bs) {
error_setg(&local_err, "Image does not have a backing file");
goto done;
}
}
cbi = (CommonBlockJobCBInfo){
.errp = &local_err,
.bs = bs,
};
aio_context = bdrv_get_aio_context(bs);
aio_context_acquire(aio_context);
commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
&cbi, &local_err, false);
aio_context_release(aio_context);
if (local_err) {
goto done;
}
if (!drop) {
bdrv_ref(bs);
}
job = block_job_get("commit");
run_block_job(job, &local_err);
if (local_err) {
goto unref_backing;
}
if (!drop && bs->drv->bdrv_make_empty) {
ret = bs->drv->bdrv_make_empty(bs);
if (ret) {
error_setg_errno(&local_err, -ret, "Could not empty %s",
filename);
goto unref_backing;
}
}
unref_backing:
if (!drop) {
bdrv_unref(bs);
}
done:
qemu_progress_end();
blk_unref(blk);
if (local_err) {
error_report_err(local_err);
return 1;
}
qprintf(quiet, "Image committed.\n");
return 0;
}
| 1threat
|
Android Studio, CMake. How to print debug message in compile time? : <p>I'm using Android Studio 2.3 beta 3. I put <code>message(AUTHOR_WARNING "Hello CMake, hello Android")</code> In my CMakeLists.txt</p>
<p>But I saw this message only few times when rebuilding project in Android Studio. In most cases there's no <code>"Hello CMake, hello Android"</code> string in Gradle Console after build finishes. I've tried resync gradle and clean/rebuild project, still no expected output.</p>
<p>I have some problems with my build (I think it's incorrect paths) so my goal - to print CMake variables in compile time to better understand what is actually going on.</p>
| 0debug
|
Add "ON" / "OFF" text to togglebutton : <p>I'm trying to add text to some togglebuttons; "ON" in the purple section when the button is on, and "OFF" in the grey section when the toggle is off. I've tried using the <code>content: "ON"</code> property to add "ON" or "OFF", but I may be using it incorrectly. Any help will be appreciated. </p>
<p>Link to js fiddle: <a href="https://jsfiddle.net/8hbybnbn/3/" rel="nofollow noreferrer">https://jsfiddle.net/8hbybnbn/3/</a></p>
| 0debug
|
I have a problem with password-verify. Even though I know the password has been entered correctly I still get a false result : I use this code to enter the hash value in mySql database: I have replaced the server login details.
The input comes from a form that is created when a user scans an NFC microchip.
```
$servername = "localhost";
$username = "xxxxxxxxx";
$password = "xxxxxxxxx";
$database = "xxxxxxxxx"; // substitute your mysql database name
$hash = password_hash($Pass, PASSWORD_DEFAULT);
if ($UID === "0") {
echo "You have not scanned a chip to enter the registration process";
}
else {
$Type = $_POST["Type"];
$Units = $_POST["UNITS"];
$LstStln = $_POST["LstStln"];
$Country = $_POST["Country"];
if (empty($_POST["eMail"])) {
$emailErr = "Email is required";
echo "Email is required";
} else {
$eMail = test_input($_POST["eMail"]);
// check if e-mail address is well-formed
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$eMail)) {
die ("Invalid email format.
Try again.");
}
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO ItsMine (UID, Password, email, Type, UNITS, LstStln, Country) VALUES ('$UID', '$hash', '$eMail', '$Type', '$Units', '$LstStln', '$Country')";
$result = $conn->query($sql);
```
This is corresponding code that processes the input from this form and is returning false from password verify.
```
$servername = "localhost";
$username = "xxxxxxxxx";
$password = "xxxxxxxxx";
$database = "xxxxxxxxxx"; // substitute your mysql database name
$email = $_POST['email'];
$Pass = $_POST['Password'];
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//get the hashed password from the database
$sql = "SELECT * From ItsMine where eMail = '$email'";
$result = $conn->query($sql);
$row=mysqli_fetch_assoc($result);
$hash = $row["Password"];
//Check password entered against the stored hash
if (password_verify($Pass, $hash)) {
$tql = "SELECT * From ItsMine where eMail = '$email'";
```
| 0debug
|
static int kvm_sclp_service_call(S390CPU *cpu, struct kvm_run *run,
uint16_t ipbh0)
{
CPUS390XState *env = &cpu->env;
uint32_t sccb;
uint64_t code;
int r = 0;
cpu_synchronize_state(CPU(cpu));
if (env->psw.mask & PSW_MASK_PSTATE) {
enter_pgmcheck(cpu, PGM_PRIVILEGED);
return 0;
}
sccb = env->regs[ipbh0 & 0xf];
code = env->regs[(ipbh0 & 0xf0) >> 4];
r = sclp_service_call(sccb, code);
if (r < 0) {
enter_pgmcheck(cpu, -r);
}
setcc(cpu, r);
return 0;
}
| 1threat
|
How can I prove wether a char in a string is equal to a spepcific char? : I would like to prove wether the first character in my string is equal to "@". How can I do this? I'm using c#
```
if (string[1] == "<character>")
{
Console.WriteLine("TRUE");
}
```
| 0debug
|
PLEASE HELP (Hello World) : i made a simple hello world app, i want the button to change 2 different text names every time i tap the button, i want the label to say "hello"
, and if i tap button again, i want it to say "goodbye " i want this changes every single time i tap the button, i have tried for days, and i still dont get it, please help.
here is the code:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var labelText: UILabel!
@IBAction func buttonTapped(_ sender: Any) {
if labelText.text == "hello" {
} else {
labelText.text = "goodbye"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 0debug
|
static void ehci_advance_state(EHCIState *ehci,
int async)
{
EHCIQueue *q = NULL;
int again;
int iter = 0;
do {
if (ehci_get_state(ehci, async) == EST_FETCHQH) {
iter++;
assert(iter < MAX_ITERATIONS);
#if 0
if (iter > MAX_ITERATIONS) {
DPRINTF("\n*** advance_state: bailing on MAX ITERATIONS***\n");
ehci_set_state(ehci, async, EST_ACTIVE);
break;
}
#endif
}
switch(ehci_get_state(ehci, async)) {
case EST_WAITLISTHEAD:
again = ehci_state_waitlisthead(ehci, async);
break;
case EST_FETCHENTRY:
again = ehci_state_fetchentry(ehci, async);
break;
case EST_FETCHQH:
q = ehci_state_fetchqh(ehci, async);
again = q ? 1 : 0;
break;
case EST_FETCHITD:
again = ehci_state_fetchitd(ehci, async);
break;
case EST_FETCHSITD:
again = ehci_state_fetchsitd(ehci, async);
break;
case EST_ADVANCEQUEUE:
again = ehci_state_advqueue(q, async);
break;
case EST_FETCHQTD:
again = ehci_state_fetchqtd(q, async);
break;
case EST_HORIZONTALQH:
again = ehci_state_horizqh(q, async);
break;
case EST_EXECUTE:
iter = 0;
again = ehci_state_execute(q, async);
break;
case EST_EXECUTING:
assert(q != NULL);
again = ehci_state_executing(q, async);
break;
case EST_WRITEBACK:
assert(q != NULL);
again = ehci_state_writeback(q, async);
break;
default:
fprintf(stderr, "Bad state!\n");
again = -1;
assert(0);
break;
}
if (again < 0) {
fprintf(stderr, "processing error - resetting ehci HC\n");
ehci_reset(ehci);
again = 0;
}
}
while (again);
ehci_commit_interrupt(ehci);
}
| 1threat
|
How to do rails db:migrate on multiple shards that are not master slave relationship at once on rails? : <p>I have an app which which uses different database based on the subdomain. So essentially, the schema would be the same, but the data would differ for each databases. But when I release some new features and it would require some schema changes, I would need to run a command that would run on all databases configured in the <code>shards.yml</code>.</p>
<p><strong>database.yml</strong></p>
<pre><code>default: &default
adapter: postgresql
encoding: unicode
pool: 15
host: localhost
port: 5432
username: postgres
password:
development:
<<: *default
database: app_default
production:
<<: *default
database: app_default
username: <%= ENV['BACKEND_DATABASE_USERNAME'] %>
password: <%= ENV['BACKEND_DATABASE_PASSWORD'] %>
</code></pre>
<p><strong>shards.yml</strong></p>
<pre><code>shared: &shared
adapter: postgresql
encoding: unicode
pool: 15
host: localhost
username: postgres
password:
port: 5432
octopus:
environments:
- development
- test
- production
development:
default:
<<: *shared
database: app
first:
<<: *shared
database: first
second:
<<: *shared
database: second
....
test:
test:
host: postgres
adapter: postgresql
database: app_test
production:
default:
<<: *shared
database: app
first:
<<: *shared
database: first
second:
<<: *shared
database: second
....
</code></pre>
<p>I am using Octopus to set the shard based on subdomain, which works fine. The problems I have are:</p>
<ol>
<li>I cannot do <code>rails db:reset</code> . Getting the error <code>ActiveRecord::StatementInvalid: PG::ObjectInUse: ERROR: cannot drop the currently open database</code></li>
<li>I cannot do <code>rails db:migrate</code> that would migrate on all databases</li>
</ol>
| 0debug
|
def lateralsurface_cube(l):
LSA = 4 * (l * l)
return LSA
| 0debug
|
Is there a way to automatically select an Entrybox in tkinter? : <p>My GUI is structured such that I have a main class, and each page of my GUI, of which I can navigate between, is instantiated whenever I call it. One of my pages has an entry box, but i have to manually move my cursor and select the entry box to begin typing. Is there a way for the entry box to automatically be selected when I call that page?</p>
<p>Seems like an interesting problem</p>
| 0debug
|
What is the correct way to put multiple controls inside update panel? : <p>I have one registration form which contains 3 to 4 dropdown controls and 2 datepickers and now when dropdown controls value are selected(selectedindex change are fired)
then i dont want my page to postback.</p>
<p>I have use update panel to stop this behaviour of post like below:</p>
<pre><code><asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<%--Update Panel for date picker%>
<asp:UpdatePanel ID="UpdatePanelDatepicker" runat="server">
<ContentTemplate>
<telerik:RadDatePicker ID="rdpDate1" runat="server">
</telerik:RadDatePicker>
</ContentTemplate>
</asp:UpdatePanel>
<%--Update Panel for Dropdown--%>
<asp:UpdatePanel ID="updatepaneldata" runat="server">
<ContentTemplate>
<telerik:RadComboBox ID="ddlCountry" runat="server">
</telerik:RadComboBox>
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
</asp:UpdatePanel>
</code></pre>
<p>So i just wanted to ask that is this correct way to put multiple controls under update panels??</p>
| 0debug
|
VSCode: Prevent split editor to open same file left & right : <p>I'm currently using VSCode as my main editor, however, when I split the editor into 2, it opens the same file twice, like left & right (see image below).</p>
<p><a href="https://i.stack.imgur.com/AE7eM.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/AE7eM.jpg" alt="enter image description here"></a>
Is there any way to prevent it from opening the same file on the next editor? Currently, I have my custom settings and can be copied from <a href="https://gist.github.com/genesisneo/4e98d3c0ad1f3e634f474a32d36b9f12" rel="noreferrer">here</a>.</p>
| 0debug
|
int nbd_trip(BlockDriverState *bs, int csock, off_t size, uint64_t dev_offset,
off_t *offset, uint32_t nbdflags, uint8_t *data, int data_size)
{
struct nbd_request request;
struct nbd_reply reply;
TRACE("Reading request.");
if (nbd_receive_request(csock, &request) == -1)
return -1;
if (request.len + NBD_REPLY_SIZE > data_size) {
LOG("len (%u) is larger than max len (%u)",
request.len + NBD_REPLY_SIZE, data_size);
errno = EINVAL;
return -1;
}
if ((request.from + request.len) < request.from) {
LOG("integer overflow detected! "
"you're probably being attacked");
errno = EINVAL;
return -1;
}
if ((request.from + request.len) > size) {
LOG("From: %" PRIu64 ", Len: %u, Size: %" PRIu64
", Offset: %" PRIu64 "\n",
request.from, request.len, (uint64_t)size, dev_offset);
LOG("requested operation past EOF--bad client?");
errno = EINVAL;
return -1;
}
TRACE("Decoding type");
reply.handle = request.handle;
reply.error = 0;
switch (request.type) {
case NBD_CMD_READ:
TRACE("Request type is READ");
if (bdrv_read(bs, (request.from + dev_offset) / 512,
data + NBD_REPLY_SIZE,
request.len / 512) == -1) {
LOG("reading from file failed");
errno = EINVAL;
return -1;
}
*offset += request.len;
TRACE("Read %u byte(s)", request.len);
cpu_to_be32w((uint32_t*)data, NBD_REPLY_MAGIC);
cpu_to_be32w((uint32_t*)(data + 4), reply.error);
cpu_to_be64w((uint64_t*)(data + 8), reply.handle);
TRACE("Sending data to client");
if (write_sync(csock, data,
request.len + NBD_REPLY_SIZE) !=
request.len + NBD_REPLY_SIZE) {
LOG("writing to socket failed");
errno = EINVAL;
return -1;
}
break;
case NBD_CMD_WRITE:
TRACE("Request type is WRITE");
TRACE("Reading %u byte(s)", request.len);
if (read_sync(csock, data, request.len) != request.len) {
LOG("reading from socket failed");
errno = EINVAL;
return -1;
}
if (nbdflags & NBD_FLAG_READ_ONLY) {
TRACE("Server is read-only, return error");
reply.error = 1;
} else {
TRACE("Writing to device");
if (bdrv_write(bs, (request.from + dev_offset) / 512,
data, request.len / 512) == -1) {
LOG("writing to file failed");
errno = EINVAL;
return -1;
}
*offset += request.len;
}
if (nbd_send_reply(csock, &reply) == -1)
return -1;
break;
case NBD_CMD_DISC:
TRACE("Request type is DISCONNECT");
errno = 0;
return 1;
default:
LOG("invalid request type (%u) received", request.type);
errno = EINVAL;
return -1;
}
TRACE("Request/Reply complete");
return 0;
}
| 1threat
|
int tcp_fconnect(struct socket *so)
{
Slirp *slirp = so->slirp;
int ret=0;
DEBUG_CALL("tcp_fconnect");
DEBUG_ARG("so = %lx", (long )so);
if( (ret=so->s=socket(AF_INET,SOCK_STREAM,0)) >= 0) {
int opt, s=so->s;
struct sockaddr_in addr;
fd_nonblock(s);
opt = 1;
setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(opt ));
opt = 1;
setsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(opt ));
addr.sin_family = AF_INET;
if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==
slirp->vnetwork_addr.s_addr) {
if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {
if (get_dns_addr(&addr.sin_addr) < 0)
addr.sin_addr = loopback_addr;
} else {
addr.sin_addr = loopback_addr;
}
} else
addr.sin_addr = so->so_faddr;
addr.sin_port = so->so_fport;
DEBUG_MISC((dfd, " connect()ing, addr.sin_port=%d, "
"addr.sin_addr.s_addr=%.16s\n",
ntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));
ret = connect(s,(struct sockaddr *)&addr,sizeof (addr));
soisfconnecting(so);
}
return(ret);
}
| 1threat
|
How can I design an Android interface that support different screen size? : <p>I want that my android app support different screen size, so what is best practice to do these, how should I choose the sizes of textView and button and Should I design different layout for every screen size?</p>
| 0debug
|
static USBDevice *usb_try_create_simple(USBBus *bus, const char *name,
Error **errp)
{
Error *err = NULL;
USBDevice *dev;
dev = USB_DEVICE(qdev_try_create(&bus->qbus, name));
if (!dev) {
error_setg(errp, "Failed to create USB device '%s'", name);
return NULL;
}
object_property_set_bool(OBJECT(dev), true, "realized", &err);
if (err) {
error_propagate(errp, err);
error_prepend(errp, "Failed to initialize USB device '%s': ",
name);
object_unparent(OBJECT(dev));
return NULL;
}
return dev;
}
| 1threat
|
static int scsi_qdev_init(DeviceState *qdev)
{
SCSIDevice *dev = SCSI_DEVICE(qdev);
SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);
SCSIDevice *d;
int rc = -1;
if (dev->channel > bus->info->max_channel) {
error_report("bad scsi channel id: %d", dev->channel);
goto err;
}
if (dev->id != -1 && dev->id > bus->info->max_target) {
error_report("bad scsi device id: %d", dev->id);
goto err;
}
if (dev->id == -1) {
int id = -1;
if (dev->lun == -1) {
dev->lun = 0;
}
do {
d = scsi_device_find(bus, dev->channel, ++id, dev->lun);
} while (d && d->lun == dev->lun && id <= bus->info->max_target);
if (id > bus->info->max_target) {
error_report("no free target");
goto err;
}
dev->id = id;
} else if (dev->lun == -1) {
int lun = -1;
do {
d = scsi_device_find(bus, dev->channel, dev->id, ++lun);
} while (d && d->lun == lun && lun < bus->info->max_lun);
if (lun > bus->info->max_lun) {
error_report("no free lun");
goto err;
}
dev->lun = lun;
} else {
d = scsi_device_find(bus, dev->channel, dev->id, dev->lun);
if (dev->lun == d->lun && dev != d) {
qdev_free(&d->qdev);
}
}
QTAILQ_INIT(&dev->requests);
rc = scsi_device_init(dev);
if (rc == 0) {
dev->vmsentry = qemu_add_vm_change_state_handler(scsi_dma_restart_cb,
dev);
}
err:
return rc;
}
| 1threat
|
need to implement virtual wallet in an iOS app (For Austria region), where the user can pay via credits to the seller and i take my cut in real time : <p>I need to implement virtual wallet in an iOS app (For Austria region), where the user can pay via credits to the seller and I take my cut in real time. For example, if user has to pay $ 10 to the seller, then I'd get $ 2 in my account and 8 to seller's. Is there any service that I can leverage for this workflow? or if apple in-App is the answer?</p>
<p>I'd be fine even if transaction happens in real currency (can do away virtual credits etc), the priority is I get my cut to be credited in real time as well before seller gets the fee; please suggest.</p>
| 0debug
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.