problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
executing a block of stetement at one go : <p>I have some block statements which fetches data from database increment it's value by one and again update in database,If am firing 5 requests it's working fine but if I am firing number of request (consider 10) within few seconds(consider 10 to 15 secs) I am getting same value for 2 to 3 request out of 10 request. what is solution so that I can get next value for each request ? I have tried synchronised block but it's not working...!</p>
| 0debug |
how to convert dmp oracle export to sql ??? (without import to oracle) : I'm new to oracle
I want to restore dmp file backup but size of my file about 300GB
how can i convert to sql without import
because when i import it to my windows oracle get many errors
the backup file from cent-os oracle 10g
is that any way to convert heavy dmp file to sql directly ???
if there is no way to convert, can i import that backup export from linux server oracle to my windows oracle ??? | 0debug |
how to do mathematical operation in html : <p>i want show in percentage. im getting value like this 14.00</p>
<p>Expected value 56%.</p>
<p>14 is 56% of 25.</p>
<p>code</p>
<pre><code><h2>(@Model[1].filled.ToString("N2"))</h2>
</code></pre>
| 0debug |
static void kvm_arm_gic_put(GICState *s)
{
uint32_t reg;
int i;
int cpu;
int num_cpu;
int num_irq;
if (!kvm_arm_gic_can_save_restore(s)) {
DPRINTF("Cannot put kernel gic state, no kernel interface");
return;
}
reg = s->enabled;
kvm_gicd_access(s, 0x0, 0, ®, true);
kvm_gicd_access(s, 0x4, 0, ®, false);
num_irq = ((reg & 0x1f) + 1) * 32;
num_cpu = ((reg & 0xe0) >> 5) + 1;
if (num_irq < s->num_irq) {
fprintf(stderr, "Restoring %u IRQs, but kernel supports max %d\n",
s->num_irq, num_irq);
abort();
} else if (num_cpu != s->num_cpu) {
fprintf(stderr, "Restoring %u CPU interfaces, kernel only has %d\n",
s->num_cpu, num_cpu);
abort();
}
kvm_dist_put(s, 0x180, 1, s->num_irq, translate_clear);
kvm_dist_put(s, 0x100, 1, s->num_irq, translate_enabled);
kvm_dist_put(s, 0x80, 1, s->num_irq, translate_group);
kvm_dist_put(s, 0x800, 8, s->num_irq, translate_targets);
kvm_dist_put(s, 0xc00, 2, s->num_irq, translate_trigger);
kvm_dist_put(s, 0x280, 1, s->num_irq, translate_clear);
kvm_dist_put(s, 0x200, 1, s->num_irq, translate_pending);
kvm_dist_put(s, 0x380, 1, s->num_irq, translate_clear);
kvm_dist_put(s, 0x300, 1, s->num_irq, translate_active);
kvm_dist_put(s, 0x400, 8, s->num_irq, translate_priority);
kvm_dist_put(s, 0xf10, 8, GIC_NR_SGIS, translate_clear);
kvm_dist_put(s, 0xf20, 8, GIC_NR_SGIS, translate_sgisource);
for (cpu = 0; cpu < s->num_cpu; cpu++) {
reg = s->cpu_enabled[cpu];
kvm_gicc_access(s, 0x00, cpu, ®, true);
reg = (s->priority_mask[cpu] & 0xff);
kvm_gicc_access(s, 0x04, cpu, ®, true);
reg = (s->bpr[cpu] & 0x7);
kvm_gicc_access(s, 0x08, cpu, ®, true);
reg = (s->abpr[cpu] & 0x7);
kvm_gicc_access(s, 0x1c, cpu, ®, true);
for (i = 0; i < 4; i++) {
reg = s->apr[i][cpu];
kvm_gicc_access(s, 0xd0 + i * 4, cpu, ®, true);
}
}
}
| 1threat |
Python - Check from how many combinations in a list you can create a triangle : I'm writing a PYTHON program that returns out of how many combinations in a list you can create a triangle.
EXAMPLE:
--> test([1,1,3])
0 #you cant make a triangle out of 1,1,3 (the only combination in this list)
--> test([2,789,5,3,3237,4])
3 #you can make a triangle out of [2,5,4],[5,3,4] and [2,4,3]
ANY HELP IS APPRECIATED
| 0debug |
static void coroutine_fn mirror_run(void *opaque)
{
MirrorBlockJob *s = opaque;
MirrorExitData *data;
BlockDriverState *bs = blk_bs(s->common.blk);
BlockDriverState *target_bs = blk_bs(s->target);
int64_t length;
BlockDriverInfo bdi;
char backing_filename[2];
int ret = 0;
int target_cluster_size = BDRV_SECTOR_SIZE;
if (block_job_is_cancelled(&s->common)) {
goto immediate_exit;
}
s->bdev_length = bdrv_getlength(bs);
if (s->bdev_length < 0) {
ret = s->bdev_length;
goto immediate_exit;
} else if (s->bdev_length == 0) {
block_job_event_ready(&s->common);
s->synced = true;
while (!block_job_is_cancelled(&s->common) && !s->should_complete) {
block_job_yield(&s->common);
}
s->common.cancelled = false;
goto immediate_exit;
}
length = DIV_ROUND_UP(s->bdev_length, s->granularity);
s->in_flight_bitmap = bitmap_new(length);
bdrv_get_backing_filename(target_bs, backing_filename,
sizeof(backing_filename));
if (!bdrv_get_info(target_bs, &bdi) && bdi.cluster_size) {
target_cluster_size = bdi.cluster_size;
}
if (backing_filename[0] && !target_bs->backing
&& s->granularity < target_cluster_size) {
s->buf_size = MAX(s->buf_size, target_cluster_size);
s->cow_bitmap = bitmap_new(length);
}
s->target_cluster_sectors = target_cluster_size >> BDRV_SECTOR_BITS;
s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
s->buf = qemu_try_blockalign(bs, s->buf_size);
if (s->buf == NULL) {
ret = -ENOMEM;
goto immediate_exit;
}
mirror_free_init(s);
s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
if (!s->is_none_mode) {
ret = mirror_dirty_init(s);
if (ret < 0 || block_job_is_cancelled(&s->common)) {
goto immediate_exit;
}
}
assert(!s->dbi);
s->dbi = bdrv_dirty_iter_new(s->dirty_bitmap, 0);
for (;;) {
uint64_t delay_ns = 0;
int64_t cnt, delta;
bool should_complete;
if (s->ret < 0) {
ret = s->ret;
goto immediate_exit;
}
block_job_pause_point(&s->common);
cnt = bdrv_get_dirty_count(s->dirty_bitmap);
s->common.len = s->common.offset +
(cnt + s->sectors_in_flight) * BDRV_SECTOR_SIZE;
delta = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->last_pause_ns;
if (delta < SLICE_TIME &&
s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
if (s->in_flight >= MAX_IN_FLIGHT || s->buf_free_count == 0 ||
(cnt == 0 && s->in_flight > 0)) {
trace_mirror_yield(s, s->in_flight, s->buf_free_count, cnt);
mirror_wait_for_io(s);
continue;
} else if (cnt != 0) {
delay_ns = mirror_iteration(s);
}
}
should_complete = false;
if (s->in_flight == 0 && cnt == 0) {
trace_mirror_before_flush(s);
ret = blk_flush(s->target);
if (ret < 0) {
if (mirror_error_action(s, false, -ret) ==
BLOCK_ERROR_ACTION_REPORT) {
goto immediate_exit;
}
} else {
if (!s->synced) {
block_job_event_ready(&s->common);
s->synced = true;
}
should_complete = s->should_complete ||
block_job_is_cancelled(&s->common);
cnt = bdrv_get_dirty_count(s->dirty_bitmap);
}
}
if (cnt == 0 && should_complete) {
trace_mirror_before_drain(s, cnt);
bdrv_co_drain(bs);
cnt = bdrv_get_dirty_count(s->dirty_bitmap);
}
ret = 0;
trace_mirror_before_sleep(s, cnt, s->synced, delay_ns);
if (!s->synced) {
block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
if (block_job_is_cancelled(&s->common)) {
break;
}
} else if (!should_complete) {
delay_ns = (s->in_flight == 0 && cnt == 0 ? SLICE_TIME : 0);
block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
} else if (cnt == 0) {
assert(QLIST_EMPTY(&bs->tracked_requests));
s->common.cancelled = false;
break;
}
s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
}
immediate_exit:
if (s->in_flight > 0) {
assert(ret < 0 || (!s->synced && block_job_is_cancelled(&s->common)));
mirror_drain(s);
}
assert(s->in_flight == 0);
qemu_vfree(s->buf);
g_free(s->cow_bitmap);
g_free(s->in_flight_bitmap);
bdrv_dirty_iter_free(s->dbi);
bdrv_release_dirty_bitmap(bs, s->dirty_bitmap);
data = g_malloc(sizeof(*data));
data->ret = ret;
bdrv_drained_begin(bs);
block_job_defer_to_main_loop(&s->common, mirror_exit, data);
}
| 1threat |
Set a stage status in Jenkins Pipelines : <p>Is there any way in a scripted pipeline to mark a stage as unstable but only show that stage as unstable without marking every stage as unstable in the output?</p>
<p>I can do something like this:</p>
<pre><code>node()
{
stage("Stage1")
{
// do work (passes)
}
stage("Stage2")
{
// something went wrong, but it isn't catastrophic...
currentBuild.result = 'UNSTABLE'
}
stage("Stage3")
{
// keep going...
}
}
</code></pre>
<p>But when I run this, Jenkins marks everything as unstable... but I'd like the first and last stages to show green if possible and just the stage that had an issue to go yellow.</p>
<p>It's ok if the whole pipeline gets flagged unstable, but it might also be nice to have a later stage over ride that and set the final-result to pass if possible too.</p>
| 0debug |
Change TimeZone dynamically in laravel : <p>In my project there is drop-down of time zones(PT,CST etc), when Admin changes the timezone from drop-down the admin panel reflects the timezone from the selected drop down.<br>
How to change Config/app.php "timezone"( Application Timezone) according to the selected option.</p>
| 0debug |
Can anyone do a many to many relationship between two django models only with the foreighn key? : I have two models lets say an Album and a Song Model.I have a foreighn key field to my Song model so I can correlate multiple songs to an album (many to one relationship).If i don't change anything in my models and leave them as they are can I succeed a many to many relationship (same song to different albums and vise versa) if I change the way that my databse store my data (normalize,denormalize etc)?
Thanks | 0debug |
In Redux, Why it checks all reducer for one case to be executed? : <p>I came to know that in react-redux if we dispatch one action so it checks all cases of reducers throughout application.
In case of big application that should not be the right way.</p>
<p>Is it not time taking process and coz performance get reduced?</p>
| 0debug |
uint64_t qcow2_alloc_cluster_offset(BlockDriverState *bs,
uint64_t offset,
int n_start, int n_end,
int *num, QCowL2Meta *m)
{
BDRVQcowState *s = bs->opaque;
int l2_index, ret;
uint64_t l2_offset, *l2_table, cluster_offset;
int nb_clusters, i = 0;
QCowL2Meta *old_alloc;
ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
if (ret == 0)
return 0;
nb_clusters = size_to_clusters(s, n_end << 9);
nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
cluster_offset = be64_to_cpu(l2_table[l2_index]);
if (cluster_offset & QCOW_OFLAG_COPIED) {
nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,
&l2_table[l2_index], 0, 0);
cluster_offset &= ~QCOW_OFLAG_COPIED;
m->nb_clusters = 0;
goto out;
}
if (cluster_offset & QCOW_OFLAG_COMPRESSED)
nb_clusters = 1;
while (i < nb_clusters) {
i += count_contiguous_clusters(nb_clusters - i, s->cluster_size,
&l2_table[l2_index], i, 0);
if(be64_to_cpu(l2_table[l2_index + i]))
break;
i += count_contiguous_free_clusters(nb_clusters - i,
&l2_table[l2_index + i]);
cluster_offset = be64_to_cpu(l2_table[l2_index + i]);
if ((cluster_offset & QCOW_OFLAG_COPIED) ||
(cluster_offset & QCOW_OFLAG_COMPRESSED))
break;
}
nb_clusters = i;
QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {
uint64_t end_offset = offset + nb_clusters * s->cluster_size;
uint64_t old_offset = old_alloc->offset;
uint64_t old_end_offset = old_alloc->offset +
old_alloc->nb_clusters * s->cluster_size;
if (end_offset < old_offset || offset > old_end_offset) {
} else {
if (offset < old_offset) {
nb_clusters = (old_offset - offset) >> s->cluster_bits;
} else {
nb_clusters = 0;
}
if (nb_clusters == 0) {
m->depends_on = old_alloc;
m->nb_clusters = 0;
*num = 0;
return 0;
}
}
}
if (!nb_clusters) {
abort();
}
QLIST_INSERT_HEAD(&s->cluster_allocs, m, next_in_flight);
cluster_offset = qcow2_alloc_clusters(bs, nb_clusters * s->cluster_size);
m->offset = offset;
m->n_start = n_start;
m->nb_clusters = nb_clusters;
out:
m->nb_available = MIN(nb_clusters << (s->cluster_bits - 9), n_end);
*num = m->nb_available - n_start;
return cluster_offset;
}
| 1threat |
import itertools
def remove_duplicate(list1):
list.sort(list1)
remove_duplicate = list(list1 for list1,_ in itertools.groupby(list1))
return remove_duplicate | 0debug |
What dependency is missing when I get java.lang.NoClassDefFoundError: javax/ws/rs/client/RxInvokerProvider error? : <p>I have a small project where for testing purposes I execute my jersey 2 client by unit test. But, unfortunately, I got the error attached. I don't know what dependency still missing. At the moment Jersey's webpage is down due to maintenance.</p>
<p>I put the same Relevant part of pom.xml, test code and tested code also attached.</p>
<pre><code>public void getWorkItems() {
ClientConfig clientConfig = new ClientConfig();
clientConfig.property(ClientProperties.READ_TIMEOUT, 2000);
Client client = ClientBuilder.newClient(clientConfig);
WebTarget webTarget = client.target("https://fabrikam.visualstudio.com/DefaultCollection/_apis/wit/workitems?ids=100,101&api-version=1.0");
Invocation.Builder inBuilder = webTarget.request(MediaType.APPLICATION_JSON_TYPE);
Response response = inBuilder.get();
}
public class WorkItemTests {
@Test
public void Vsts_Test() {
WorkItems workItems = new WorkItems();
workItems.getWorkItems();
}
}
</code></pre>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20</version>
<configuration>
<includes>
<include>**/*Tests.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>stuff</groupId>
<artifactId>Vsts.Connector</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25.1</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>
</code></pre>
<p>Error:</p>
<pre><code>java.lang.NoClassDefFoundError: javax/ws/rs/client/RxInvokerProvider
at org.glassfish.jersey.internal.inject.Providers.getJaxRsProviderInterfaces(Providers.java:114)
at org.glassfish.jersey.internal.inject.Providers.<clinit>(Providers.java:87)
at org.glassfish.jersey.internal.AbstractRuntimeDelegate.<init>(AbstractRuntimeDelegate.java:86)
at org.glassfish.jersey.server.internal.RuntimeDelegateImpl.<init>(RuntimeDelegateImpl.java:64)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at java.lang.Class.newInstance(Class.java:442)
at javax.ws.rs.ext.FactoryFinder.newInstance(FactoryFinder.java:118)
at javax.ws.rs.ext.FactoryFinder.find(FactoryFinder.java:166)
at javax.ws.rs.ext.RuntimeDelegate.findDelegate(RuntimeDelegate.java:135)
at javax.ws.rs.ext.RuntimeDelegate.getInstance(RuntimeDelegate.java:120)
at javax.ws.rs.core.UriBuilder.newInstance(UriBuilder.java:95)
at javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:119)
at org.glassfish.jersey.client.JerseyWebTarget.<init>(JerseyWebTarget.java:71)
at org.glassfish.jersey.client.JerseyClient.target(JerseyClient.java:290)
at org.glassfish.jersey.client.JerseyClient.target(JerseyClient.java:76)
at WorkItems.getWorkItems(WorkItems.java:24)
at WorkItemTests.Vsts_Test2(WorkItemTests.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.ClassNotFoundException: javax.ws.rs.client.RxInvokerProvider
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 42 more
Process finished with exit code -1
</code></pre>
| 0debug |
static av_cold int amr_nb_encode_init(AVCodecContext *avctx)
{
AMRContext *s = avctx->priv_data;
if (avctx->sample_rate != 8000) {
av_log(avctx, AV_LOG_ERROR, "Only 8000Hz sample rate supported\n");
return AVERROR(ENOSYS);
}
if (avctx->channels != 1) {
av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");
return AVERROR(ENOSYS);
}
avctx->frame_size = 160;
avctx->initial_padding = 50;
ff_af_queue_init(avctx, &s->afq);
s->enc_state = Encoder_Interface_init(s->enc_dtx);
if (!s->enc_state) {
av_log(avctx, AV_LOG_ERROR, "Encoder_Interface_init error\n");
av_freep(&avctx->coded_frame);
return -1;
}
s->enc_mode = get_bitrate_mode(avctx->bit_rate, avctx);
s->enc_bitrate = avctx->bit_rate;
return 0;
}
| 1threat |
PHP 5 to 7 migration - Numbers comparison : <p>I noticed that code below results in different messages in PHP 5.x and 7:</p>
<pre><code>if ('0xFF' == 255) {
echo 'Equal';
} else {
echo 'Not equal';
}
</code></pre>
<ul>
<li>5.x: Equal</li>
<li>7: Not equal</li>
</ul>
<p>Tried to find a description of the changes that cause it in migration guide and in the PHP doc but couldn't find anything. Probably it is somewhere there and I just missed it. Can you, please, point it? Thank you!</p>
<p>Where I looked</p>
<ul>
<li><a href="http://php.net/manual/en/migration70.php" rel="noreferrer">http://php.net/manual/en/migration70.php</a></li>
<li><a href="http://php.net/manual/en/language.types.type-juggling.php" rel="noreferrer">http://php.net/manual/en/language.types.type-juggling.php</a></li>
<li><a href="http://php.net/manual/en/language.operators.comparison.php" rel="noreferrer">http://php.net/manual/en/language.operators.comparison.php</a></li>
</ul>
| 0debug |
Returning array of strings from a function and assigning it to variable later prevents function from working : I have a small question. I have this function, returning a char**. (I'm not sure its working but I think it is).
char** parse_cmdline(char* cmdline) {
char ** arr = malloc(10 * sizeof(char*));
for (int i =0 ; i < 10; ++i)
arr[i] = malloc(30 * sizeof(char));
char * token = strtok(cmdline, " ");
int i = 0;
while(token != NULL) {
if(i > 9) arr = realloc(arr, (i+10)*sizeof(char*) );
arr[i] = token;
token = strtok(NULL, " ");
i++;
}
printf("flag1");
return arr;
}
then i want to assign the return value to a variable in my main function
if(fgets(cmd, sizeof cmd, stdin) == NULL) break;
char ** commands = parse_cmdline(cmd);
printf("%s", commands[0]);
and literally nothing happens. Not even the printf("flag1"); prints. But if I remove the `char ** commands` and put the `printf("%s", commands[0]);` in the parse_cmdline function, everything works, except im not assigning the return. Why and how to fix it? | 0debug |
static uint32_t bonito_spciconf_readw(void *opaque, target_phys_addr_t addr)
{
PCIBonitoState *s = opaque;
uint32_t pciaddr;
uint16_t status;
DPRINTF("bonito_spciconf_readw "TARGET_FMT_plx" \n", addr);
assert((addr&0x1)==0);
pciaddr = bonito_sbridge_pciaddr(s, addr);
if (pciaddr == 0xffffffff) {
return 0xffff;
}
s->pcihost->config_reg = (pciaddr) | (1u << 31);
status = pci_get_word(s->dev.config + PCI_STATUS);
status &= ~(PCI_STATUS_REC_MASTER_ABORT | PCI_STATUS_REC_TARGET_ABORT);
pci_set_word(s->dev.config + PCI_STATUS, status);
return pci_data_read(s->pcihost->bus, s->pcihost->config_reg, 2);
}
| 1threat |
in android studio i need checkboxes to save their state whn i go out of app or the activitt. Please assist : So i need checkboxes to save state when i exit or switch activity. I need many checkboxes, so I need a function that works for all the checkboxes.
please help.
Thanks in advance. | 0debug |
Visual Studio Code: Select each occurrence of word (case sensitive) : <p>I know that <code>ctrl</code> + <code>shift</code> + <code>L</code> is used to select all the instances of word/selection, but is there a case sensitive version of this command? </p>
| 0debug |
C++ code is much slower on linux than on windows : <p>I'm writing simple program and I want to mesure time of its execution on Windows and Linux (both 64). I have a problem, because for 1 000 000 elements in table on Windows it takes about 35 seconds, while on linux it takes about 30 seconds for 10 elements. Why the difference is so huge?
What am I doing wrong? Is there something in my code that is not proper on Linux? </p>
<p>Here is my code:</p>
<pre><code>void fillTable(int s, int t[])
{
srand(time(0));
for (int i = 0; i < s; i++)
{
t[i] = rand();
}
}
void checkIfIsPrimeNotParalleled(int size, int table[])
{
for (int i = 0; i < size; i++)
{
int tmp = table[i];
if (tmp < 2)
{
}
for (int i = 2; i < tmp; i++)
{
if (tmp % i == 0)
{
}
else
{
}
}
}
}
void mesureTime(int size, int table[], int numberOfRepetitions)
{
long long sum = 0;
clock_t start_time, end_time;
fillTable(size, table);
for (int i = 0; i < numberOfRepetitions; i++)
{
start_time = clock();
checkIfIsPrimeNotParalleled(size, table);
end_time = clock();
double duration = (end_time - start_time) / CLOCKS_PER_SEC;
sum += duration;
}
cout << "Avg: " << round(sum / numberOfRepetitions) << " s"<<endl;
}
int main()
{
static constexpr int size = 1000000;
int *table = new int[size];
int numberOfRepetitions = 1;
mesureTime(size, table, numberOfRepetitions);
delete[] table;
return 0;
}
</code></pre>
<p>and the makefile for Linux. On Windows I'm using Visual Studio 2015</p>
<pre><code>.PHONY: Project1
CXX = g++
EXEC = tablut
LDFLAGS = -fopenmp
CXXFLAGS = -std=c++11 -Wall -Wextra -fopenmp -m64
SRC= Project1.cpp
OBJ= $(SRC:.cpp=.o)
all: $(EXEC)
tablut: $(OBJ)
$(CXX) -o tablut $(OBJ) $(LDFLAGS)
%.o: %.cpp
$(CXX) -o $@ -c $< $(CXXFLAGS)
clean:
rm -rf *.o
mrproper: clean
rm -rf tablut
</code></pre>
<p>The main goal is to mesure time.</p>
| 0debug |
Difference(s): android:src and tools:src? : <blockquote>
<p><strong>Difference(s): <code>android:src</code> and <code>tools:src</code>?</strong></p>
</blockquote>
<p>If any, when is it considered proper to use <code>tools:src</code> over <code>android:src</code>?</p>
| 0debug |
conda equivalent of pip install --user : <p>To install to my own directory I can use</p>
<pre><code>pip install --user package
</code></pre>
<p>Alternatively I can use </p>
<p><code>conda install package</code></p>
<p>How do I ask <code>conda</code> to install to my home directory since conda does not take a <code>--user</code> flag?</p>
<p><a href="https://stackoverflow.com/questions/7143077/installing-pip-packages-to-home-folder">Installing pip packages to $HOME folder</a></p>
| 0debug |
How to get/return viewtype in use from adapter in android : is there a way I can get/return a `View` in my case a `RecyclerView` from the `Adapter` using it so as to reuse it in another `Activity`. And if possible how can I then re use it in the `Activity`?Without re-referencing it a new in the `Activity` | 0debug |
Can I commit files to GitHub from Android Phone : <p>I've been doing a school assignment on HTML and CSS. It was an easy assignment and I almost missed the due date when I was away for the weekend. </p>
<p>I have done the assignment on my phone but to hand it in I have to put it on my GitHub page.</p>
<p>Is there a way to put files from Android onto my GitHub page?</p>
| 0debug |
Debugging symbols not loading in .NET standard project targeting .NET Framework : <p>I am using Visual Studio 2017. I created a <strong>.NET Standard</strong> library (let this library be <em>Lib1</em>) project with two Target frameworks, <em>netstandard2.0</em> and <em>net46</em>. Then I have another two projects... one is a "pure" <strong>.NET Framework 4.6</strong> console project (lets call it <em>Console46</em>) and a <strong>.NET Core</strong> console project (lets call it <em>ConsoleCore</em>). Both of them reference Lib1.</p>
<p>When I run the ConsoleCore project, I can debug and put breakpoints without any problem, but when I run Console46, Visual Studio can not load the pdb file, so I can't debug the library, put breakpoints, etc.</p>
<p>I try to load the PDB file manually because it is created for the net46, but it fails also.</p>
<p>What can I do to fix this problem?</p>
<p>Thank you!</p>
| 0debug |
Implement XOR in Assembly : Implement XOR operation between 2 numbers using only ADD,SUB,Branch if equal , Branch if not equal , register r1 that stores the first number , register r2 that stores the second number , and register r3 and r4 that you can use | 0debug |
static int huff_build12(VLC *vlc, uint8_t *len)
{
HuffEntry he[4096];
uint32_t codes[4096];
uint8_t bits[4096];
uint16_t syms[4096];
uint32_t code;
int i;
for (i = 0; i < 4096; i++) {
he[i].sym = 4095 - i;
he[i].len = len[i];
if (len[i] == 0)
return AVERROR_INVALIDDATA;
}
AV_QSORT(he, 4096, HuffEntry, huff_cmp_len12);
code = 1;
for (i = 4095; i >= 0; i--) {
codes[i] = code >> (32 - he[i].len);
bits[i] = he[i].len;
syms[i] = he[i].sym;
code += 0x80000000u >> (he[i].len - 1);
}
ff_free_vlc(vlc);
return ff_init_vlc_sparse(vlc, FFMIN(he[4095].len, 14), 4096,
bits, sizeof(*bits), sizeof(*bits),
codes, sizeof(*codes), sizeof(*codes),
syms, sizeof(*syms), sizeof(*syms), 0);
}
| 1threat |
Static IP without router access? : <p>I am currently living at the student homes to my university. I want to set up a NAS / server to run backups, VM and some other small task. This is also something I want to set up to learn more about Linux and networking. I am currently planning how to set it up and what hardware to buy, but I want to run arch Linux on it with RAID 1. A problem I'm thinking about is that I don't have access to the router and therefore I can't set up port forwarding to connect to the server. Is there a way to get remote access to it without adjusting the settings in the router?</p>
| 0debug |
Why won't my nav bar text center : Okay so my navigation bar text won't center properly, it acts almost like a drop down menu instead when I center it. I couldn't find out why. Also if you could help with this, my social media buttons are all showing up blue instead of the color in the CSS sheet. Thanks!
<DOCTYPE! html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<title>Home</title>
<!--CSS Sheet-->
<style>
h1 {
font-size: 60;
text-align: center;
font-family: "Bodoni MT", Didot, "Didot LT STD", "Hoefler Text", Garamond, "Times New Roman", serif;
}
/* Top Navigation Bar*/
.topnav {
background-color: #666666;
overflow: hidden;
}
.topnav a {
font-family: Rockwell, 'Courier Bold', Courier, Georgia, Times, 'Times New Roman', serif;
float: center;
display: block;
color: #f2f2f2;
text-align: center;
padding: 8px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav .icon {
display: none;
}
@media screen and (max-width: 600px) {
.topnav a:not(:first-child) {display: none;}
.topnav a.icon {
float: right;
display: block;
}
}
@media screen and (max-width: 600px) {
.topnav.responsive {position: relative;}
.topnav.responsive .icon {
position: absolute;
right: 0;
top: 0;
}
.topnav.responsive a {
float: none;
display: block;
text-align: left;
}
}
/*Slideshow*/
/* Slideshow container */
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
/* Caption text */
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
/* Number text (1/3 etc) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
/* The dots/bullets/indicators */
.dot {
height: 13px;
width: 13px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active {
background-color: #717171;
}
/* Fading animation */
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
@-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
/* On smaller screens, decrease text size */
@media only screen and (max-width: 300px) {
.text {font-size: 11px}
}
/*Social Media Buttons*/
.fa {
padding: 20px;
font-size: 30px;
width: 30px;
text-align: center;
text-decoration: none;
margin: 5px 2px;
border-radius: 50%;
}
.fa:hover {
opacity: 0.7;
}
.fa-facebook {
background: #3B5998;
color: white;
}
.fa-twitter {
background: #55ACEE;
color: white;
}
fa-youtube {
background: #bb0000;
color: white;
}
.fa-instagram {
background: #125688;
color: white;
}
.fa-snapchat-ghost {
background: #fffc00;
color: white;
text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}
/*End of Social Media Buttons*/
/*Footer*/
</style>
</head>
<body>
<br>
<!--Title/Logo--><h1>Tavernier Tech</h1>
<br>
<!--Navigation Bar-->
<div class="topnav" id="myTopnav">
<a href="#home">Home</a>
<a href="#articles">Articles</a>
<a href="#news">Shop</a>
<a href="#contact">Contact</a>
<a href="#about">About</a>
<a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">☰</a>
</div>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<br>
<!--Slideshow-->
<div class="slideshow-container">
<div class="mySlides fade">
<div class="numbertext"></div>
<img src="https://media.licdn.com/mpr/mpr/AAEAAQAAAAAAAATOAAAAJDE2NDQ3ZjkzLTljOTAtNDU2Mi04NGRlLTc5NWRkZTYwNzNlMQ.jpg" style="width:90%">
<div class="text"></div>
</div>
<div class="mySlides fade">
<div class="numbertext"></div>
<img src="http://www.ntech.net.au/wp-content/uploads/2015/07/network-switch-ethernet.jpg" style="width:90%">
<div class="text"></div>
</div>
</div>
<br>
<div style="text-align:center">
<span class="dot"></span>
<span class="dot"></span>
</div>
<script>
var slideIndex = 0;
showSlides();
function showSlides() {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex> slides.length) {slideIndex = 1}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
setTimeout(showSlides, 10000); // Change image every 10 seconds
}
</script>
<!--Footer-->
<footer class="">
<!--Social Media Buttons-->
<a href="#" class="fa fa-facebook-official"></a>
<a href="#" class="fa fa-twitter"></a>
<a href="#" class="fa fa-instagram"></a>
<a href="#" class="fa fa-youtube"></a>
</footer>
</body>
</html> | 0debug |
Need to find a way to copy and paste type="password" : <p>Got an assignment to find a way to enable copy function on type="password", I'm thinking that the best approach is with js, I would appreciate any help! thanks</p>
| 0debug |
COLDFUSION run SQL once and includ the count : Is it possible run the SQL once and display the output + the count of amount. how it looks below it works as wished but i run the query twice and may this is not so productive.. see (example attached). Thank you so much for your support and inputs. [enter image description here][1]
<cfquery name="myta" datasource="zett">
Select w.t_id, a.t_qui, w.t_zur
from table_bst a, table_zr w
where 1=1
....
</cfquery>
<cfquery name="meto" datasource="zett">
SELECT a.t_qui as tepamout, COUNT(*) AS epstatus
from table_bst a, table_zr w
where 1=1
....
</cfquery>
<cfif meto.recordcount EQ 0>
<table><tr><td style="color:#FF0000">There is currently an error</td></tr></table>
<cfelse>
<cfoutput>
<div>
<table id="claus" colspan="7">
<td style="font-weight: bold; background-color:##FFFFFF; font-size:12px">Status</td>
<cfloop query="meto"><tr>
<td style="white-space:nowrap; align="middle" width:50%"><button class="link-filter" style="color: ##000000; background-color: transparent; border-color: transparent; cursor: default;"data-filter-column="1" data-filter-text="#meto.tepamout#"><img border="0" alt="ch" src="./assets/img/gt.ico" width="10" height="10" style="opacity:0.6"></button>#meto.tepamout#: #meto.epstatus#</td>
</tr>
</cfloop>
<cfset temp = ValueList(myta.status)>
<td style="font-weight: bold; color:##FF0000"><button id="reset-link" style="color: ##000000; background-color: transparent; border-color: transparent; cursor: default;"><img border="0" alt="ch" src="./assets/img/gt.ico" width="10" height="10" style="opacity:0.6;"></button>Total: <cfoutput>#ListLen(temp)#</cfoutput></td><br /><br /></tr>
[1]: https://i.stack.imgur.com/95fnU.png | 0debug |
AWS ElasticBeanstalk CLI in OS X: EB Command Not Found : <p>I am running into an error attempting to run the ElasticBeanstalk CLI tools on Mac OSX. I have been troubleshooting path issues and hope someone can shed some light. Here is my set up.</p>
<p>I am running Mac OS X El Capital 10.11.6, and I have manually installed Python 3.4 (via the download installer on python.org). I can see that it is installed correctly in <code>/Library/Frameworks/Python.frameworks/Versions</code>. Commands beginning with <code>python3</code> work as expected. I have also installed the the AWS ElasticBeanstalk CLI tools by running <code>sudo pip3 install --upgrade awsebcli</code> and can confirm it is located in the <code>/Users/myuser/Library/Python/3.4/lib/python/site-packages/</code> directory.</p>
<p>I have experimented with modifying my <code>~/.bash_profile</code>, as well as removing it. When I run <code>echo $PATH</code>, here is my output:</p>
<pre><code>/Users/myuser/Library/Python/3.4/lib/python/site-packages/ebcli/:
/Library/Frameworks/Python.framework/Versions/3.4/lib/python/site-packages:
/Library/Frameworks/Python.framework/Versions/3.4/bin:
/Users/myuser/.rvm/gems/ruby-2.2.4/bin:
/Users/myuser/.rvm/gems/ruby-2.2.4@global/bin:
/Users/myuser/.rvm/rubies/ruby-2.2.4/bin:
/usr/local/bin:
/usr/bin:
/bin:
/usr/sbin:
/sbin:
/opt/X11/bin:
/usr/local/git/bin:
/Users/myuser/.rvm/bin
</code></pre>
<p>Here is my <code>~/.bash_profile</code></p>
<pre><code># Load the default .profile
[[ -s "$HOME/.profile" ]] && source "$HOME/.profile"
# Load RVM into a shell session *as a function*
#[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
# Setting PATH for Python 3.4
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}"
# Setting PATH for Python 3.4 site packages
PATH="/Library/Frameworks/Python.framework/Versions/3.4/lib/python/site-packages:${PATH}"
PATH="/Users/myuser/Library/Python/3.4/lib/python/site-packages/ebcli/:${PATH}"
export PATH
</code></pre>
| 0debug |
JAX-RS 2 print JSON request : <p>I'd like to be able to print JAX-RS 2 JSON payload from request, regardless of actual implementation on my application server.</p>
<p>I've tried suggested solutions on SO but all include binaries from actual implementation (like Jersey and similar), and I'm allowed only to use javaee-api v 7.0 in my application.</p>
<p>I've tried implementing ClientRequestFilter and ClientResponseFilter on my Client but they don't contain serialized entities.</p>
<p>Here's an example of client:</p>
<pre><code>WebTarget target = ClientBuilder.newClient().register(MyLoggingFilter.class).target("http://localhost:8080/loggingtest/resources/accounts");
Account acc = target.request().accept(MediaType.APPLICATION_JSON).get(account.Account.class);
</code></pre>
<p>And here's the implementation of MyLoggingFilter:</p>
<pre><code>@Provider
public class MyLoggingFilter implements ClientRequestFilter, ClientResponseFilter {
private static final Logger LOGGER = Logger.getLogger(MyLoggingFilter.class.getName());
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
LOGGER.log(Level.SEVERE, "Request method: {0}", requestContext.getMethod());
}
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
LOGGER.log(Level.SEVERE, "Response status: {0}", responseContext.getStatus());
}
}
</code></pre>
| 0debug |
static int cin_read_packet(AVFormatContext *s, AVPacket *pkt)
{
CinDemuxContext *cin = s->priv_data;
ByteIOContext *pb = s->pb;
CinFrameHeader *hdr = &cin->frame_header;
int rc, palette_type, pkt_size;
if (cin->audio_buffer_size == 0) {
rc = cin_read_frame_header(cin, pb);
if (rc)
return rc;
if ((int16_t)hdr->pal_colors_count < 0) {
hdr->pal_colors_count = -(int16_t)hdr->pal_colors_count;
palette_type = 1;
} else {
palette_type = 0;
}
pkt_size = (palette_type + 3) * hdr->pal_colors_count + hdr->video_frame_size;
if (av_new_packet(pkt, 4 + pkt_size))
return AVERROR(ENOMEM);
pkt->stream_index = cin->video_stream_index;
pkt->pts = cin->video_stream_pts++;
pkt->data[0] = palette_type;
pkt->data[1] = hdr->pal_colors_count & 0xFF;
pkt->data[2] = hdr->pal_colors_count >> 8;
pkt->data[3] = hdr->video_frame_type;
if (get_buffer(pb, &pkt->data[4], pkt_size) != pkt_size)
return AVERROR(EIO);
cin->audio_buffer_size = hdr->audio_frame_size;
return 0;
}
if (av_new_packet(pkt, cin->audio_buffer_size))
return AVERROR(ENOMEM);
pkt->stream_index = cin->audio_stream_index;
pkt->pts = cin->audio_stream_pts;
cin->audio_stream_pts += cin->audio_buffer_size * 2 / cin->file_header.audio_frame_size;
if (get_buffer(pb, pkt->data, cin->audio_buffer_size) != cin->audio_buffer_size)
return AVERROR(EIO);
cin->audio_buffer_size = 0;
return 0;
}
| 1threat |
styled components, with gatsby-link anchor tag css coloring : <p>I am trying to style a <code><Link/></code> component from <code>gatsby-link</code> package using <code>styled-components</code> package Normally I just create a <code>const</code> give it a <code>Name</code> set it equal to <code>styled.a</code> for example and write my css. However when I create a <code>const</code> for <code><Link/></code> I get a <code>Duplicate declaration "Link"</code> error. How do I style a <code><Link></code> component with <code>styled-components</code>.</p>
<p>Here is my code Below</p>
<pre><code>import React from 'react';
import Link from 'gatsby-link';
import styled from "styled-components";
const Header = styled.div`
margin: 3rem auto;
max-width: 600px;
background:red;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
`;
const Title = styled.h1`
color: aqua;
`;
const Link = styled.a`
color: aqua;
`;
export default () => (
<Header>
<Title>
<Link to="/">
Gatsby
</Link>
</Title>
</Header>
);
</code></pre>
| 0debug |
How to scroll all spreadsheet sheets together. (Or other ~3D-like ideas) : I have a simple idea of what I'm looking for, but I'm not sure how to explain it clearly, so apologies in advance!
I would like a "3D" spreadsheet, with the aim of having main entries in the normal 2D cells and then (potentially just-as-important) entries in a third dimension above each cell. This is what the multiple sheets already allow for, the problem is that I cannot easily see all the 3rd dimension cells at once.
I was first hoping to find some sophisticated method of using actual 3D sheets but with no luck so far. I realised that if I could only make sure the other sheets would line up with my first sheet then that would be good enough, so I could "scroll" along the third dimension by switching between sheets.
So, is there any way to scroll all the sheets together? Such that if I scroll down on sheet 1 to see cell 123 A, when I switch to sheet 2, cell 123 A is in the same position on the screen, and so on for sheets 3 and up.
If this is impossible but anyone has suggestions for a different solution that would be great.
Many thanks! | 0debug |
static void avc_biwgt_4width_msa(uint8_t *src,
int32_t src_stride,
uint8_t *dst,
int32_t dst_stride,
int32_t height,
int32_t log2_denom,
int32_t src_weight,
int32_t dst_weight,
int32_t offset_in)
{
if (2 == height) {
avc_biwgt_4x2_msa(src, src_stride, dst, dst_stride,
log2_denom, src_weight, dst_weight,
offset_in);
} else {
avc_biwgt_4x4multiple_msa(src, src_stride, dst, dst_stride,
height, log2_denom, src_weight,
dst_weight, offset_in);
}
}
| 1threat |
! in input buffer in comparison in if statement : I am not clear with the usage of ! in input buffer comparison in sample code as below
/*GLOBAL VARIABLES*/
int pipe_count=0, fd;
static char* args[512];
char *history_file;
char input_buffer[1024];
int main()
{
int status;
char ch[2]={"\n"};
getcwd(current_directory, sizeof(current_directory));
signal(SIGINT, sigintHandler);
while (1)
{
clear_variables();
prompt();
fgets(input_buffer, 1024, stdin);
if(strcmp(input_buffer, ch)==0)
{
continue;
}
if(input_buffer[0]!='!')
{
fileprocess();
filewrite();
}
len = strlen(input_buffer);
input_buffer[len-1]='\0';
strcpy(his_var, input_buffer);
if(strcmp(input_buffer, "exit") == 0)
{
flag = 1;
break;
}
I am not able to understand `if(input_buffer[0]!='!')`
this statement what does '!' mean in comparison does it signify a NULL
or it is some thing else. The full code is very big this is just one part which I am not clear with.I checked the ASCII value of ! from here http://ee.hawaii.edu/~tep/EE160/Book/chap4/subsection2.1.1.1.html but I am not able to understand what is input_buffer[0] being compared against by using ! in code for a NULL etc I as far as I understand it is NULL,'\0',' ' this kind of `input_buffer[0]!='!'`thing is not clear to me as to what it gets translated to ? | 0debug |
what is the advantage of using Alamofire over NSURLSession/NSURLConnection for networking? : <p>Can anyone help me in understanding these question : What is the advantage of using Alamofire over NSURLSession/ NSURLConnection? </p>
<p>What are the differences between NSURLSession and NSURLConnection?</p>
| 0debug |
static int qemu_rbd_snap_list(BlockDriverState *bs,
QEMUSnapshotInfo **psn_tab)
{
BDRVRBDState *s = bs->opaque;
QEMUSnapshotInfo *sn_info, *sn_tab = NULL;
int i, snap_count;
rbd_snap_info_t *snaps;
int max_snaps = RBD_MAX_SNAPS;
do {
snaps = g_malloc(sizeof(*snaps) * max_snaps);
snap_count = rbd_snap_list(s->image, snaps, &max_snaps);
if (snap_count <= 0) {
g_free(snaps);
}
} while (snap_count == -ERANGE);
if (snap_count <= 0) {
goto done;
}
sn_tab = g_malloc0(snap_count * sizeof(QEMUSnapshotInfo));
for (i = 0; i < snap_count; i++) {
const char *snap_name = snaps[i].name;
sn_info = sn_tab + i;
pstrcpy(sn_info->id_str, sizeof(sn_info->id_str), snap_name);
pstrcpy(sn_info->name, sizeof(sn_info->name), snap_name);
sn_info->vm_state_size = snaps[i].size;
sn_info->date_sec = 0;
sn_info->date_nsec = 0;
sn_info->vm_clock_nsec = 0;
}
rbd_snap_list_end(snaps);
g_free(snaps);
done:
*psn_tab = sn_tab;
return snap_count;
}
| 1threat |
static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
uint64_t end_offset, void **p_feature_table,
int flags, Error **errp)
{
BDRVQcow2State *s = bs->opaque;
QCowExtension ext;
uint64_t offset;
int ret;
#ifdef DEBUG_EXT
printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
#endif
offset = start_offset;
while (offset < end_offset) {
#ifdef DEBUG_EXT
if (offset > s->cluster_size)
printf("qcow2_read_extension: suspicious offset %lu\n", offset);
printf("attempting to read extended header in offset %lu\n", offset);
#endif
ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
if (ret < 0) {
error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
"pread fail from offset %" PRIu64, offset);
return 1;
}
be32_to_cpus(&ext.magic);
be32_to_cpus(&ext.len);
offset += sizeof(ext);
#ifdef DEBUG_EXT
printf("ext.magic = 0x%x\n", ext.magic);
#endif
if (offset > end_offset || ext.len > end_offset - offset) {
error_setg(errp, "Header extension too large");
return -EINVAL;
}
switch (ext.magic) {
case QCOW2_EXT_MAGIC_END:
return 0;
case QCOW2_EXT_MAGIC_BACKING_FORMAT:
if (ext.len >= sizeof(bs->backing_format)) {
error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
" too large (>=%zu)", ext.len,
sizeof(bs->backing_format));
return 2;
}
ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
if (ret < 0) {
error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
"Could not read format name");
return 3;
}
bs->backing_format[ext.len] = '\0';
s->image_backing_format = g_strdup(bs->backing_format);
#ifdef DEBUG_EXT
printf("Qcow2: Got format extension %s\n", bs->backing_format);
#endif
break;
case QCOW2_EXT_MAGIC_FEATURE_TABLE:
if (p_feature_table != NULL) {
void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
if (ret < 0) {
error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
"Could not read table");
return ret;
}
*p_feature_table = feature_table;
}
break;
case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
unsigned int cflags = 0;
if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
error_setg(errp, "CRYPTO header extension only "
"expected with LUKS encryption method");
return -EINVAL;
}
if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
error_setg(errp, "CRYPTO header extension size %u, "
"but expected size %zu", ext.len,
sizeof(Qcow2CryptoHeaderExtension));
return -EINVAL;
}
ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
if (ret < 0) {
error_setg_errno(errp, -ret,
"Unable to read CRYPTO header extension");
return ret;
}
be64_to_cpus(&s->crypto_header.offset);
be64_to_cpus(&s->crypto_header.length);
if ((s->crypto_header.offset % s->cluster_size) != 0) {
error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
"not a multiple of cluster size '%u'",
s->crypto_header.offset, s->cluster_size);
return -EINVAL;
}
if (flags & BDRV_O_NO_IO) {
cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
}
s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
qcow2_crypto_hdr_read_func,
bs, cflags, errp);
if (!s->crypto) {
return -EINVAL;
}
} break;
default:
{
Qcow2UnknownHeaderExtension *uext;
uext = g_malloc0(sizeof(*uext) + ext.len);
uext->magic = ext.magic;
uext->len = ext.len;
QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
if (ret < 0) {
error_setg_errno(errp, -ret, "ERROR: unknown extension: "
"Could not read data");
return ret;
}
}
break;
}
offset += ((ext.len + 7) & ~7);
}
return 0;
}
| 1threat |
How to iterator the awk result : I need to split the path into small pieces. As we know, the path is like the format as /home/tommy/test, I really need to split them into home tommy test, So can I iterator the result? For example, I need to get all of the sub items in $PWD. | 0debug |
static void lx_init(const LxBoardDesc *board, MachineState *machine)
{
#ifdef TARGET_WORDS_BIGENDIAN
int be = 1;
#else
int be = 0;
#endif
MemoryRegion *system_memory = get_system_memory();
XtensaCPU *cpu = NULL;
CPUXtensaState *env = NULL;
MemoryRegion *ram, *rom, *system_io;
DriveInfo *dinfo;
pflash_t *flash = NULL;
QemuOpts *machine_opts = qemu_get_machine_opts();
const char *cpu_model = machine->cpu_model;
const char *kernel_filename = qemu_opt_get(machine_opts, "kernel");
const char *kernel_cmdline = qemu_opt_get(machine_opts, "append");
const char *dtb_filename = qemu_opt_get(machine_opts, "dtb");
const char *initrd_filename = qemu_opt_get(machine_opts, "initrd");
int n;
if (!cpu_model) {
cpu_model = XTENSA_DEFAULT_CPU_MODEL;
}
for (n = 0; n < smp_cpus; n++) {
cpu = cpu_xtensa_init(cpu_model);
if (cpu == NULL) {
error_report("unable to find CPU definition '%s'\n",
cpu_model);
exit(EXIT_FAILURE);
}
env = &cpu->env;
env->sregs[PRID] = n;
qemu_register_reset(lx60_reset, cpu);
cpu_reset(CPU(cpu));
}
ram = g_malloc(sizeof(*ram));
memory_region_init_ram(ram, NULL, "lx60.dram", machine->ram_size,
&error_abort);
vmstate_register_ram_global(ram);
memory_region_add_subregion(system_memory, 0, ram);
system_io = g_malloc(sizeof(*system_io));
memory_region_init(system_io, NULL, "lx60.io", 224 * 1024 * 1024);
memory_region_add_subregion(system_memory, 0xf0000000, system_io);
lx60_fpga_init(system_io, 0x0d020000);
if (nd_table[0].used) {
lx60_net_init(system_io, 0x0d030000, 0x0d030400, 0x0d800000,
xtensa_get_extint(env, 1), nd_table);
}
if (!serial_hds[0]) {
serial_hds[0] = qemu_chr_new("serial0", "null", NULL);
}
serial_mm_init(system_io, 0x0d050020, 2, xtensa_get_extint(env, 0),
115200, serial_hds[0], DEVICE_NATIVE_ENDIAN);
dinfo = drive_get(IF_PFLASH, 0, 0);
if (dinfo) {
flash = pflash_cfi01_register(board->flash_base,
NULL, "lx60.io.flash", board->flash_size,
blk_bs(blk_by_legacy_dinfo(dinfo)),
board->flash_sector_size,
board->flash_size / board->flash_sector_size,
4, 0x0000, 0x0000, 0x0000, 0x0000, be);
if (flash == NULL) {
error_report("unable to mount pflash\n");
exit(EXIT_FAILURE);
}
}
if (kernel_filename) {
uint32_t entry_point = env->pc;
size_t bp_size = 3 * get_tag_size(0);
uint32_t tagptr = 0xfe000000 + board->sram_size;
uint32_t cur_tagptr;
BpMemInfo memory_location = {
.type = tswap32(MEMORY_TYPE_CONVENTIONAL),
.start = tswap32(0),
.end = tswap32(machine->ram_size),
};
uint32_t lowmem_end = machine->ram_size < 0x08000000 ?
machine->ram_size : 0x08000000;
uint32_t cur_lowmem = QEMU_ALIGN_UP(lowmem_end / 2, 4096);
rom = g_malloc(sizeof(*rom));
memory_region_init_ram(rom, NULL, "lx60.sram", board->sram_size,
&error_abort);
vmstate_register_ram_global(rom);
memory_region_add_subregion(system_memory, 0xfe000000, rom);
if (kernel_cmdline) {
bp_size += get_tag_size(strlen(kernel_cmdline) + 1);
}
if (dtb_filename) {
bp_size += get_tag_size(sizeof(uint32_t));
}
if (initrd_filename) {
bp_size += get_tag_size(sizeof(BpMemInfo));
}
tagptr = (tagptr - bp_size) & ~0xff;
cur_tagptr = put_tag(tagptr, BP_TAG_FIRST, 0, NULL);
cur_tagptr = put_tag(cur_tagptr, BP_TAG_MEMORY,
sizeof(memory_location), &memory_location);
if (kernel_cmdline) {
cur_tagptr = put_tag(cur_tagptr, BP_TAG_COMMAND_LINE,
strlen(kernel_cmdline) + 1, kernel_cmdline);
}
if (dtb_filename) {
int fdt_size;
void *fdt = load_device_tree(dtb_filename, &fdt_size);
uint32_t dtb_addr = tswap32(cur_lowmem);
if (!fdt) {
error_report("could not load DTB '%s'\n", dtb_filename);
exit(EXIT_FAILURE);
}
cpu_physical_memory_write(cur_lowmem, fdt, fdt_size);
cur_tagptr = put_tag(cur_tagptr, BP_TAG_FDT,
sizeof(dtb_addr), &dtb_addr);
cur_lowmem = QEMU_ALIGN_UP(cur_lowmem + fdt_size, 4096);
}
if (initrd_filename) {
BpMemInfo initrd_location = { 0 };
int initrd_size = load_ramdisk(initrd_filename, cur_lowmem,
lowmem_end - cur_lowmem);
if (initrd_size < 0) {
initrd_size = load_image_targphys(initrd_filename,
cur_lowmem,
lowmem_end - cur_lowmem);
}
if (initrd_size < 0) {
error_report("could not load initrd '%s'\n", initrd_filename);
exit(EXIT_FAILURE);
}
initrd_location.start = tswap32(cur_lowmem);
initrd_location.end = tswap32(cur_lowmem + initrd_size);
cur_tagptr = put_tag(cur_tagptr, BP_TAG_INITRD,
sizeof(initrd_location), &initrd_location);
cur_lowmem = QEMU_ALIGN_UP(cur_lowmem + initrd_size, 4096);
}
cur_tagptr = put_tag(cur_tagptr, BP_TAG_LAST, 0, NULL);
env->regs[2] = tagptr;
uint64_t elf_entry;
uint64_t elf_lowaddr;
int success = load_elf(kernel_filename, translate_phys_addr, cpu,
&elf_entry, &elf_lowaddr, NULL, be, ELF_MACHINE, 0);
if (success > 0) {
entry_point = elf_entry;
} else {
hwaddr ep;
int is_linux;
success = load_uimage(kernel_filename, &ep, NULL, &is_linux);
if (success > 0 && is_linux) {
entry_point = ep;
} else {
error_report("could not load kernel '%s'\n",
kernel_filename);
exit(EXIT_FAILURE);
}
}
if (entry_point != env->pc) {
static const uint8_t jx_a0[] = {
#ifdef TARGET_WORDS_BIGENDIAN
0x0a, 0, 0,
#else
0xa0, 0, 0,
#endif
};
env->regs[0] = entry_point;
cpu_physical_memory_write(env->pc, jx_a0, sizeof(jx_a0));
}
} else {
if (flash) {
MemoryRegion *flash_mr = pflash_cfi01_get_memory(flash);
MemoryRegion *flash_io = g_malloc(sizeof(*flash_io));
memory_region_init_alias(flash_io, NULL, "lx60.flash",
flash_mr, board->flash_boot_base,
board->flash_size - board->flash_boot_base < 0x02000000 ?
board->flash_size - board->flash_boot_base : 0x02000000);
memory_region_add_subregion(system_memory, 0xfe000000,
flash_io);
}
}
}
| 1threat |
Code splitting causes chunks to fail to load after new deployment for SPA : <p>I have a single page app that I code split on each route. When I deploy a new version of my app the users will usually get an error if a user still has the page open and visits a route they haven't visited before. </p>
<p>Another scenario where this can also happen is if the app has service workers enabled. When the user visits a page after a new deployment, the service worker will serve from the cache. Then if the user tries to visit a page not in their cache, they'll get the chunk loading failure.</p>
<p>Currently I disabled code splitting in my app to avoid this but I've been very curious what's the best way to handle this issue. I've thought about pre-loading all the other routes after the user finishes loading the initial page and I believe this might fix the issue for code splitting on routes. But let's say I want to code split on components then that would mean I have to try to figure out when and how to pre-load all of those components. </p>
<p>So I'm wondering how do people handle this issue for single page apps? Thanks! (I'm currently using create-react-app)</p>
| 0debug |
def unique_Element(arr,n):
s = set(arr)
if (len(s) == 1):
return ('YES')
else:
return ('NO') | 0debug |
Fatal Exception: java.lang.StackOverflowError stack size 8MB android.view.View.hasIdentityMatrix : <p>This is a very rare bug that's happening in my app. Users open <code>SettingsActivity</code> and notice the app has frozen, after which it crashes (5 - 10s later?).<br>
I have no idea how to proceed, I've tried debugging but can't reproduce the issue. I've seen other similar questions, but their stack traces had application methods that were the cause of an infinite loop. Here, there is no application code that's responsible (at least, the stack trace doesn't reveal anything)</p>
<p>Stack trace shows only a bunch of Android core library methods (<code>View</code>, <code>ViewGroup</code>, <code>RecyclerView</code>), and has something to do with accessibility.</p>
<p>This perplexes me, since:</p>
<ul>
<li>I'm not using RecyclerView anywhere in <code>SettingsActivity</code>, <code>SettingsFragment</code>, or their layouts</li>
<li>The only place I am using it, works perfectly, as proven by a few screenshots and videos users have sent me</li>
<li>I haven't overriden any accessibility callbacks in any of my activities</li>
<li>I added breakpoints in every method the stack trace shows, but those breakpoints were never hit. In any activity. (<strong>wtf</strong>)</li>
</ul>
<p>Considering the stack trace doesn't show any custom classes/methods part of my codebase, how am I supposed to proceed? Is this a known bug in <code>androidx.recyclerview</code>, for example?</p>
<p>I know for sure that the app crashes in <code>SettingsActivity</code>, since Firebase tracks activities in Crashlytics for you. (the flow was <code>MainActivity -> [AnyActivity] -> SettingsActivity -> <freeze> -> <crash></code>).</p>
<p>Our entire team can't reproduce this issue (using the same exact Play Store version), but it seems like there are around 100 users that are experiencing this crash. All devices that show these fatal exceptions are being used by our team to debug, to no avail.</p>
<h3>Stack trace</h3>
<pre><code>Fatal Exception: java.lang.StackOverflowError: stack size 8MB
at android.view.View.hasIdentityMatrix (View.java:14669)
at android.view.ViewGroup.getChildVisibleRect (ViewGroup.java:6138)
at android.view.ViewGroup.getChildVisibleRect (ViewGroup.java:6189)
at android.view.ViewGroup.getChildVisibleRect (ViewGroup.java:6189)
at android.view.ViewGroup.getChildVisibleRect (ViewGroup.java:6189)
at android.view.ViewGroup.getChildVisibleRect (ViewGroup.java:6189)
at android.view.ViewGroup.getChildVisibleRect (ViewGroup.java:6189)
at android.view.ViewGroup.getChildVisibleRect (ViewGroup.java:6189)
at android.view.ViewGroup.getChildVisibleRect (ViewGroup.java:6189)
at android.view.ViewGroup.getChildVisibleRect (ViewGroup.java:6189)
at android.view.ViewGroup.getChildVisibleRect (ViewGroup.java:6189)
at android.view.ViewGroup.getChildVisibleRect (ViewGroup.java:6121)
at android.view.View.getGlobalVisibleRect (View.java:16064)
at android.view.View.isVisibleToUser (View.java:9065)
at android.view.View.isVisibleToUser (View.java:9023)
at android.view.View.onInitializeAccessibilityNodeInfoInternal (View.java:8814)
at android.view.ViewGroup.onInitializeAccessibilityNodeInfoInternal (ViewGroup.java:3642)
at android.view.View$AccessibilityDelegate.onInitializeAccessibilityNodeInfo (View.java:27387)
at androidx.core.view.AccessibilityDelegateCompat.onInitializeAccessibilityNodeInfo (AccessibilityDelegateCompat.java:275)
at androidx.recyclerview.widget.RecyclerViewAccessibilityDelegate$ItemDelegate.onInitializeAccessibilityNodeInfo (RecyclerViewAccessibilityDelegate.java:124)
at androidx.recyclerview.widget.RecyclerViewAccessibilityDelegate$ItemDelegate.onInitializeAccessibilityNodeInfo (RecyclerViewAccessibilityDelegate.java:131)
at androidx.recyclerview.widget.RecyclerViewAccessibilityDelegate$ItemDelegate.onInitializeAccessibilityNodeInfo (RecyclerViewAccessibilityDelegate.java:131)
at androidx.recyclerview.widget.RecyclerViewAccessibilityDelegate$ItemDelegate.onInitializeAccessibilityNodeInfo (RecyclerViewAccessibilityDelegate.java:131)
at androidx.recyclerview.widget.RecyclerViewAccessibilityDelegate$ItemDelegate.onInitializeAccessibilityNodeInfo (RecyclerViewAccessibilityDelegate.java:131)
at androidx.recyclerview.widget.RecyclerViewAccessibilityDelegate$ItemDelegate.onInitializeAccessibilityNodeInfo (RecyclerViewAccessibilityDelegate.java:131)
at androidx.recyclerview.widget.RecyclerViewAccessibilityDelegate$ItemDelegate.onInitializeAccessibilityNodeInfo (RecyclerViewAccessibilityDelegate.java:131)
at androidx.recyclerview.widget.RecyclerViewAccessibilityDelegate$ItemDelegate.onInitializeAccessibilityNodeInfo (RecyclerViewAccessibilityDelegate.java:131)
at androidx.recyclerview.widget.RecyclerViewAccessibilityDelegate$ItemDelegate.onInitializeAccessibilityNodeInfo (RecyclerViewAccessibilityDelegate.java:131)
at androidx.recyclerview.widget.RecyclerViewAccessibilityDelegate$ItemDelegate.onInitializeAccessibilityNodeInfo (RecyclerViewAccessibilityDelegate.java:131)
at androidx.recyclerview.widget.RecyclerViewAccessibilityDelegate$ItemDelegate.onInitializeAccessibilityNodeInfo (RecyclerViewAccessibilityDelegate.java:131)
at androidx.core.view.AccessibilityDelegateCompat$AccessibilityDelegateAdapter.onInitializeAccessibilityNodeInfo (AccessibilityDelegateCompat.java:86)
at android.view.View.onInitializeAccessibilityNodeInfo (View.java:7776)
at android.view.View.createAccessibilityNodeInfoInternal (View.java:7737)
at android.view.View$AccessibilityDelegate.createAccessibilityNodeInfo (View.java:27485)
at android.view.View.createAccessibilityNodeInfo (View.java:7720)
at android.view.AccessibilityInteractionController$AccessibilityNodePrefetcher.prefetchDescendantsOfRealNode (AccessibilityInteractionController.java:1147)
at android.view.AccessibilityInteractionController$AccessibilityNodePrefetcher.prefetchAccessibilityNodeInfos (AccessibilityInteractionController.java:972)
at android.view.AccessibilityInteractionController.findAccessibilityNodeInfoByAccessibilityIdUiThread (AccessibilityInteractionController.java:336)
at android.view.AccessibilityInteractionController.access$400 (AccessibilityInteractionController.java:67)
at android.view.AccessibilityInteractionController$PrivateHandler.handleMessage (AccessibilityInteractionController.java:1324)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:193)
at android.app.ActivityThread.main (ActivityThread.java:6898)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:858)
</code></pre>
<h3>SettingsActivity</h3>
<pre class="lang-java prettyprint-override"><code>public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
settingsFragment = new SettingsFragment();
getSupportFragmentManager().beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.replace(R.id.settings_container, settingsFragment, "Settings")
.commit();
... // also contains code to init an IAP helper,
// but that doesn't use RecyclerView either (obviously)
}
</code></pre>
<h3>SettingsFragment</h3>
<pre class="lang-java prettyprint-override"><code>public class SettingsFragment extends PreferenceFragmentCompat implements OnPreferenceChangeListener {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
...
addPreferencesFromResource(R.xml.preferences);
...
}
</code></pre>
| 0debug |
Linq query for Nested child litems n-depth c# : <p>Trying to query child item of same object to n-depth and display in the below format. So for each sub cat add tab space.</p>
<pre><code>Cat 1
Sub Cat 1 - 1
Sub Cat 1 - 2
Cat 2
Sub Cat 2 - 1
Sub Cat 2 - 2
Sub Cat 3 - 2 - 2
class NavItem {
public string label { get; set; }
public List<NavItem> childItems { get; set; }
}
</code></pre>
<p>Create item, </p>
<pre><code>var item = new NavItem()
{
label = "Root",
childItems = new List<NavItem>() {
new NavItem() { label = "Cat 1" , childItems = new List<NavItem>() {
new NavItem() { label = "Sub Cat 1 - 1" },
new NavItem() { label = "Sub Cat 1 - 2" },
} },
new NavItem() { label = "Cat 2", childItems = new List<NavItem>() {
new NavItem() { label = "Sub Cat 2 - 1" },
new NavItem() { label = "Sub Cat 2 - 2", childItems = new List<NavItem>() {
new NavItem() { label = "Sub Cat 3 - 2 - 2"}
} },
} },
}
};
</code></pre>
<p>I have below code, which is not complete. it can go only two depth</p>
<pre><code>item.childItems.ForEach(i => {
Console.WriteLine(i.label);
i.childItems.ForEach(i1 =>
{
Console.WriteLine("\t" + i1.label);
});
});
</code></pre>
| 0debug |
C# dictionary keeps changing the values into the last added value. : <p>When I try to add a new name and number from textboxes into a dictionary, and then try to add the content of the dictionary to a listBox all the previous entries are the same. Like if I add "Bob Johnson 42", "Jim Smith 33", "Peter White 21". When I put it in the ListBox it will apear as:
Peter White 21
Peter White 21
Peter White 21 </p>
<p>What am I doing wrong?
Here is the code. </p>
<pre><code>private void button1_Click(object sender, EventArgs e)
{
String name = this.textBox1.Text;
int testNumber = int.Parse(textBox2.Text);
submittedTests.Add(this.textBox1.Text, testNumber);
foreach (var x in submittedTests)
{
listBox1.Items.Add(name + " " + testNumber);
}
}
</code></pre>
| 0debug |
static always_inline int _pte_check (mmu_ctx_t *ctx, int is_64b,
target_ulong pte0, target_ulong pte1,
int h, int rw)
{
target_ulong ptem, mmask;
int access, ret, pteh, ptev;
access = 0;
ret = -1;
#if defined(TARGET_PPC64)
if (is_64b) {
ptev = pte64_is_valid(pte0);
pteh = (pte0 >> 1) & 1;
} else
#endif
{
ptev = pte_is_valid(pte0);
pteh = (pte0 >> 6) & 1;
}
if (ptev && h == pteh) {
#if defined(TARGET_PPC64)
if (is_64b) {
ptem = pte0 & PTE64_PTEM_MASK;
mmask = PTE64_CHECK_MASK;
} else
#endif
{
ptem = pte0 & PTE_PTEM_MASK;
mmask = PTE_CHECK_MASK;
}
if (ptem == ctx->ptem) {
if (ctx->raddr != (target_ulong)-1) {
if ((ctx->raddr & mmask) != (pte1 & mmask)) {
if (loglevel != 0)
fprintf(logfile, "Bad RPN/WIMG/PP\n");
return -3;
}
}
if (ctx->key == 0) {
access = PAGE_READ;
if ((pte1 & 0x00000003) != 0x3)
access |= PAGE_WRITE;
} else {
switch (pte1 & 0x00000003) {
case 0x0:
access = 0;
break;
case 0x1:
case 0x3:
access = PAGE_READ;
break;
case 0x2:
access = PAGE_READ | PAGE_WRITE;
break;
}
}
ctx->raddr = pte1;
ctx->prot = access;
if ((rw == 0 && (access & PAGE_READ)) ||
(rw == 1 && (access & PAGE_WRITE))) {
#if defined (DEBUG_MMU)
if (loglevel != 0)
fprintf(logfile, "PTE access granted !\n");
#endif
ret = 0;
} else {
#if defined (DEBUG_MMU)
if (loglevel != 0)
fprintf(logfile, "PTE access rejected\n");
#endif
ret = -2;
}
}
}
return ret;
}
| 1threat |
Portably detect __VA_OPT__ support? : <p>In C++20, the preprocessor supports <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0306r4.html" rel="noreferrer"><code>__VA_OPT__</code></a> as a way to optionally expand tokens in a variadic macro if the number of arguments is greater than zero. (This obviates the need for the <code>##__VA_ARGS__</code> GCC extension, which is a non-portable and ugly hack.)</p>
<p>Clang SVN has implemented this feature, but they haven't added a feature test macro for it. Can any clever preprocessor hacker figure out a way to detect the presence or absence of <code>__VA_OPT__</code> support without causing a hard error or a portability warning?</p>
| 0debug |
Python Text file scanner : I am relatively new to python and was working on a project to enhance my skills, it was a text file compressor;
I am having problems with the file scanning portion, I want it to read a text file and find a word.
Any help would be much appreciated | 0debug |
What do KilledWorker exceptions mean in Dask? : <p>My tasks are returning with <code>KilledWorker</code> exceptions when using Dask with the dask.distributed scheduler. What do these errors mean?</p>
| 0debug |
variable referenced before assignment error in python : <p>In my code I am testing if a user has AWS access keys:</p>
<pre><code>for response in paginator.paginate(UserName=user_name):
if len(response['AccessKeyMetadata']) and 'AccessKeyId' in response['AccessKeyMetadata'][0].keys():
key1 = response['AccessKeyMetadata'][0]['AccessKeyId']
</code></pre>
<p>Later in my code I test if key1 exists:</p>
<pre><code>if key1:
print("\nAccess Key 1: ", key1)
else:
print("The user does not have any keys.")
</code></pre>
<p>If the user has NO keys at all, the function fails with this error:</p>
<pre><code> File ".\aws_iam_utils.py", line 1430, in rotate_access_keys
if key1:
UnboundLocalError: local variable 'key1' referenced before assignment
</code></pre>
<p>Am I testing if key1 exists correctly? Why am I getting an unbound local error, when it should just print out the statement in the else clause?</p>
| 0debug |
javascript regex to match number square brackets and get the remaining string : I have a string like following
value[0]
1. I want to check if `str contains square brackets`.
2. If yes than get the number which in above case is `0`
3. Get the rest of the string without brackets and number which in above case is `value`
> var matches = this.key.match('/[([0-9]+)]/'); // 1
> if (null != matches) {
> var num = matches[1]; // 2
> }
How to get 3 point accomplished ?
| 0debug |
Best practice to store single value in AWS Lambda : <p>I have a Lambda that is generating and returning a value. This value can expire. Therefore I need to check the values validity before returning.
As generating is quite expensive (taken from another service) I'd like to store the value somehow.</p>
<p>What is the best practice for storing those 2 values (timestamp and a corresponding value)?</p>
<ul>
<li>DynamoDB, but using a database service for 2 values seems to be a lot of overhead. There will never be more items; The same entry will only get updated.</li>
<li>I thought about S3, but this would also imply creating a S3-Bucket and storing one object containing the information, only for this 2 values (but probably the most "lean" way?)</li>
<li>Would love to update Lambdas configuration in order to update the environment variables (but even if this is possible, its probably no best practice?! Also not sure about inconsistencies with Lambda runtimes...)</li>
</ul>
<p>Whats best practice here? Whats the way to go in terms of performance?</p>
| 0debug |
how convert date in excel formating seconds and minutes to cero :
I have a date in excel like this
2017-08-24 08:04:42.560
So I need to convert to this format
any formula for that?
2017-08-24 00:00:00.000
| 0debug |
When i run my autoclicker i cant stop it : If i click on start button i cant click back or stop.
I need stop app.One way to stop app is that you must power off computer :D.
When app is running start button is locked and i cant click on it.
This app is simple AutoClicker.
Exist in java something better to do autoclicker than robot class?
How can i fix it?
Is somewhere error?
Or something to stop the app?
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Robot;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.Color;
public class AutoClicker extends JFrame {
private JPanel contentPane;
private final JLabel m = new JLabel("AutoClicker");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AutoClicker frame = new AutoClicker();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AutoClicker() {
setAlwaysOnTop(false);
setTitle("AutoClicker");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 147, 162);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JCheckBox chckbxOnTop = new JCheckBox("On Top");
boolean onTop = false;
chckbxOnTop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(chckbxOnTop.isSelected()){
setAlwaysOnTop(true);
}
else{
setAlwaysOnTop(false);
}
}
});
chckbxOnTop.setBounds(6, 7, 97, 23);
contentPane.add(chckbxOnTop);
JCheckBox chckbxAutoclicker = new JCheckBox("AutoClicker");
chckbxAutoclicker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(;;){
if(chckbxAutoclicker.isSelected()){
for(;;){
try {
Robot r = new Robot();
r.mousePress(MouseEvent.BUTTON1_MASK);
r.setAutoDelay(1080);
r.mouseRelease(MouseEvent.BUTTON1_MASK);
} catch (AWTException e1) {
e1.printStackTrace();
}
}
}
else {
}
}
}
});
chckbxAutoclicker.setBounds(6, 80, 97, 23);
contentPane.add(chckbxAutoclicker);
m.setForeground(new Color(153, 102, 0));
m.setBounds(16, 92, 120, 31);
contentPane.add(m);
}
}
| 0debug |
window.location.href = 'http://attack.com?user=' + user_input; | 1threat |
Spring boot Test fails saying, Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean : <p>Test Class:-</p>
<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = { WebsocketSourceConfiguration.class,
WebSocketSourceIntegrationTests.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
"websocket.path=/some_websocket_path", "websocket.allowedOrigins=*",
"spring.cloud.stream.default-binder=kafka" })
public class WebSocketSourceIntegrationTests {
private String port = "8080";
@Test
public void testWebSocketStreamSource() throws IOException, InterruptedException {
StandardWebSocketClient webSocketClient = new StandardWebSocketClient();
ClientWebSocketContainer clientWebSocketContainer = new ClientWebSocketContainer(webSocketClient,
"ws://localhost:" + port + "/some_websocket_path");
clientWebSocketContainer.start();
WebSocketSession session = clientWebSocketContainer.getSession(null);
session.sendMessage(new TextMessage("foo"));
System.out.println("Done****************************************************");
}
}
</code></pre>
<p>I have seen same issue <a href="https://stackoverflow.com/questions/46463908/unable-to-start-servletwebserverapplicationcontext-due-to-missing-servletwebserv">here</a> but nothing helped me. May I know what I'm missing ?</p>
<p>I have <code>spring-boot-starter-tomcat</code> as compile time dependency in the dependency Hierarchy.</p>
| 0debug |
Regex - Select First Match from Javascript Code : <p>I'm trying to get the url of a javascript code.
Everything was fine until I noticed that this code randomly shows 3 or more url within the same line, so the PHP function I was using no longer worked for me.</p>
<p>So I am trying to select from the following code only the first URL but I am not good with the regex (its in one line):</p>
<pre><code>"https:\/\/sample.domain.com\/201706\/26\/13912879\/720p_1500k_13912879\/sample_video_name.mp4?rate=190k&burst=1200k&validfrom=1499826300&validto=1499840700&hash=%2BDsIFr8fnCAx2cz%2BAgsQEY9jjb4%3D"},{"defaultQuality":false,"format":"","quality":"480","videoUrl":"https:\/\/sample.domain.com\/201706\/26\/13912879\/480p_750k_13912879\/sample_video_name_2.mp4?rate=108k&burst=1200k&validfrom=1499826300&validto=1499840700&hash=8rL1ttX15bHmwFKINHUUewnEv8A%3D"},{"defaultQuality":false,"format":"","quality":"240","videoUrl":"https:\/\/sample.domain.com\/201706\/26\/13912879\/240p_240k_13912879\/sample_video_name_3.mp4?rate=59k&burst=1200k&validfrom=1499826300&validto=1499840700&hash=Frj6AcBMp8zrHKttan%2BDYEmktTY%3D"
</code></pre>
<p>I tried to use the following code but this one selects me all the url, I just want the first one:</p>
<pre><code>https:([^"]+)
</code></pre>
<p>Example with regexr:
<a href="http://regexr.com/3gb4u" rel="nofollow noreferrer">http://regexr.com/3gb4u</a></p>
| 0debug |
find even or odd number without modulo operator in php : <p><strong>find even or odd number without modulo operator in php</strong></p>
<p>I am having problem to find even or odd numbers without modulo sign.
so that i cant prepare my code.</p>
| 0debug |
Font awesome and bootstrap button with icons syntax : <p>In bootstrap, buttons with icons are implemented using a combination of <code><button></code> and <code><span></code>:</p>
<p><a href="http://getbootstrap.com/components/#glyphicons-examples" rel="noreferrer">http://getbootstrap.com/components/#glyphicons-examples</a></p>
<pre><code><button type="button" class="btn btn-default" aria-label="Left Align">
<span class="glyphicon glyphicon-align-left" aria-hidden="true"></span>
</button>
</code></pre>
<p>In font awesome, buttons are implemented using combination of <code><a></code> and <code><i></code>:</p>
<p><a href="http://fontawesome.io/examples/" rel="noreferrer">http://fontawesome.io/examples/</a></p>
<pre><code><a class="btn btn-danger" href="#">
<i class="fa fa-trash-o fa-lg"></i> Delete</a>
</code></pre>
<p>Is there a better way? Or are the selection of these tags completely arbitrary? </p>
| 0debug |
dbdma_control_write(DBDMA_channel *ch)
{
uint16_t mask, value;
uint32_t status;
mask = (ch->regs[DBDMA_CONTROL] >> 16) & 0xffff;
value = ch->regs[DBDMA_CONTROL] & 0xffff;
value &= (RUN | PAUSE | FLUSH | WAKE | DEVSTAT);
status = ch->regs[DBDMA_STATUS];
status = (value & mask) | (status & ~mask);
if (status & WAKE)
status |= ACTIVE;
if (status & RUN) {
status |= ACTIVE;
status &= ~DEAD;
}
if (status & PAUSE)
status &= ~ACTIVE;
if ((ch->regs[DBDMA_STATUS] & RUN) && !(status & RUN)) {
status &= ~(ACTIVE|DEAD);
}
DBDMA_DPRINTF(" status 0x%08x\n", status);
ch->regs[DBDMA_STATUS] = status;
if (status & ACTIVE)
qemu_bh_schedule(dbdma_bh);
if (status & FLUSH)
ch->flush(&ch->io);
}
| 1threat |
Could not find method externalNativeBuild() for arguments : <p>i'm trying to integrate the ndkBuild functionality into an existing android studio project, using the new android studio 2.2 , in order to enable c++ debugging etc.
i have tried out one of the ndk example projects which android studio 2.2 offers, which works perfectly fine. However, when i try to run the gradle commands in my own project, i get this error message:</p>
<p><em>Error:(73, 0) Could not find method externalNativeBuild() for arguments [build_c6heui1f67l8o1c3ifgpntw6$_run_closure2$_closure9@4329c1c9] on project ':core' of type org.gradle.api.Project.</em> </p>
<p>By following this description
<a href="http://tools.android.com/tech-docs/external-c-builds">http://tools.android.com/tech-docs/external-c-builds</a>
i ended up with a gradle script which includes the following commands:</p>
<pre><code>externalNativeBuild{
ndkBuild{
path "$projectDir/jni/Android.mk"
}
}
externalNativeBuild {
ndkBuild {
arguments "NDK_APPLICATION_MK:=$projectDir/jni/Application.mk"
abiFilters "armeabi-v7a", "armeabi","arm64-v8a","x86"
cppFlags "-frtti -fexceptions"
}
}
</code></pre>
<p>Did i perhaps miss out on something here with the project setup?
I have set the <strong>Android NDK location</strong> properly under </p>
<p><em>File -> Project Structure ... -> SDK Location -> Android NDK location</em></p>
<p>in my android studio. </p>
<p>Anything else i might have forgotton?</p>
<p>Has anyone run into a similar problem before?</p>
<p>Advice would be much appreciated =)</p>
| 0debug |
How to get firestore timestamp : <p>I'm trying to get the timestamp of a document that I created in firestore, but what I get is this:</p>
<p><a href="https://i.stack.imgur.com/I4A6N.png" rel="noreferrer"><img src="https://i.stack.imgur.com/I4A6N.png" alt="enter image description here"></a></p>
<p><strong>myService.ts</strong></p>
<pre><code>getDomiciliarios() {
this.domiciliarios = this.afs.collection('domiciliarios').snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Domiciliario;
const id = a.payload.doc.id;
const date = firebase.firestore.FieldValue.serverTimestamp();
return { id, ...data, date };
});
});
return this.domiciliarios;
}
</code></pre>
<p><strong>myComponent.ts</strong></p>
<pre><code>ngOnInit() {
const domiciliarios = this.fs.getDomiciliarios()
.subscribe(data => this.dataSource.data = data, date => date);
}
</code></pre>
<p><strong>myComponent.html</strong></p>
<pre><code><ng-container matColumnDef="fecha">
<mat-header-cell *matHeaderCellDef mat-sort-header> Fecha </mat-header-cell>
<mat-cell *matCellDef="let domiciliario"> {{ domiciliario.date }} </mat-cell>
</ng-container>
</code></pre>
<p>How can I print that timestamp, should I have previously created it?</p>
| 0debug |
DXF converter in UWP : <p>I need a DXF converter for my UWP. The library can be paid, it does not matter. Have you used a DXF converter with UWP before? </p>
<p>I want to convert DXF to PDF or Image.</p>
<p>Thank you.</p>
| 0debug |
I have to append last n element of LL to font : node* append_LinkedList(node* head,int n)
{
//write your code here
int count=0;
node *temp=head;
while(count<n-1)
{
temp=temp->next;
count++;
}
cout<<temp->data;
return head;
}
next step I am not able to think.after getting nth node pointer what to do next. | 0debug |
Segmentation Fault (Core Dump) C : <p>I've started to study C this week, I'm totally new in programming in C, and when I tryed to do this exercise this error in the console keep showing up.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
float calc(float *sall, float *salb)
{
float hraula, insspc;
int naula;
printf("Digite o valor da hora-aula e o numero de aulas dadas:");
scanf("%f%i", hraula, naula);
printf("Digite a porcentagem do inss retirada do salário:");
scanf("%f",insspc);
*salb = hraula * naula;
*sall = *salb * ((100 - insspc) / 100);
return 0;
}
int main()
{
float salbt, sallq;
calc(&sallq, &salbt);
printf("O salário bruto é: %f R$, liquido: %f R$", salbt, sallq);
return 0;
}
</code></pre>
<p>Well hope someone can help me, thanks!</p>
| 0debug |
why my app closed when i click button on my fragment to go to another fragment page : i can run this code , but when i click button on my checkbalance layout , my app closed ,can someone help me pls, my checkbalance actually is a fragment from my navigation drawer activity,my idea is when i click the button on check balance,it will go to makepayment page
Checkbalance.java
package com.helloworld.basikal;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Created by LENOVO on 8/21/2017.
*/
public class CheckBalance extends Fragment{
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Check Balance");
Button button = (Button) getView().findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), MadePayment.class);
getActivity().startActivity(intent);
}
});
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.checkbalance,container,false);
}
}
Madepayment.java
package com.helloworld.basikal;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by LENOVO on 8/24/2017.
*/
public class MadePayment extends Fragment{
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.madepayment, container, false);
Intent intent = getActivity().getIntent();
return view;
}
}
| 0debug |
static int qemu_rdma_resolve_host(RDMAContext *rdma, Error **errp)
{
int ret;
struct addrinfo *res;
char port_str[16];
struct rdma_cm_event *cm_event;
char ip[40] = "unknown";
struct addrinfo *e;
if (rdma->host == NULL || !strcmp(rdma->host, "")) {
ERROR(errp, "RDMA hostname has not been set");
return -1;
}
rdma->channel = rdma_create_event_channel();
if (!rdma->channel) {
ERROR(errp, "could not create CM channel");
return -1;
}
ret = rdma_create_id(rdma->channel, &rdma->cm_id, NULL, RDMA_PS_TCP);
if (ret) {
ERROR(errp, "could not create channel id");
goto err_resolve_create_id;
}
snprintf(port_str, 16, "%d", rdma->port);
port_str[15] = '\0';
ret = getaddrinfo(rdma->host, port_str, NULL, &res);
if (ret < 0) {
ERROR(errp, "could not getaddrinfo address %s", rdma->host);
goto err_resolve_get_addr;
}
for (e = res; e != NULL; e = e->ai_next) {
inet_ntop(e->ai_family,
&((struct sockaddr_in *) e->ai_addr)->sin_addr, ip, sizeof ip);
DPRINTF("Trying %s => %s\n", rdma->host, ip);
ret = rdma_resolve_addr(rdma->cm_id, NULL, e->ai_addr,
RDMA_RESOLVE_TIMEOUT_MS);
if (!ret) {
goto route;
}
}
ERROR(errp, "could not resolve address %s", rdma->host);
goto err_resolve_get_addr;
route:
qemu_rdma_dump_gid("source_resolve_addr", rdma->cm_id);
ret = rdma_get_cm_event(rdma->channel, &cm_event);
if (ret) {
ERROR(errp, "could not perform event_addr_resolved");
goto err_resolve_get_addr;
}
if (cm_event->event != RDMA_CM_EVENT_ADDR_RESOLVED) {
ERROR(errp, "result not equal to event_addr_resolved %s",
rdma_event_str(cm_event->event));
perror("rdma_resolve_addr");
goto err_resolve_get_addr;
}
rdma_ack_cm_event(cm_event);
ret = rdma_resolve_route(rdma->cm_id, RDMA_RESOLVE_TIMEOUT_MS);
if (ret) {
ERROR(errp, "could not resolve rdma route");
goto err_resolve_get_addr;
}
ret = rdma_get_cm_event(rdma->channel, &cm_event);
if (ret) {
ERROR(errp, "could not perform event_route_resolved");
goto err_resolve_get_addr;
}
if (cm_event->event != RDMA_CM_EVENT_ROUTE_RESOLVED) {
ERROR(errp, "result not equal to event_route_resolved: %s",
rdma_event_str(cm_event->event));
rdma_ack_cm_event(cm_event);
goto err_resolve_get_addr;
}
rdma_ack_cm_event(cm_event);
rdma->verbs = rdma->cm_id->verbs;
qemu_rdma_dump_id("source_resolve_host", rdma->cm_id->verbs);
qemu_rdma_dump_gid("source_resolve_host", rdma->cm_id);
return 0;
err_resolve_get_addr:
rdma_destroy_id(rdma->cm_id);
rdma->cm_id = NULL;
err_resolve_create_id:
rdma_destroy_event_channel(rdma->channel);
rdma->channel = NULL;
return -1;
}
| 1threat |
Save String and Import at Later Date : <p>I'm having a problem with determining how I can save text that users enter into Textboxes and then retrieve that information later on specific dates. For example:</p>
<p>Day 1:</p>
<pre><code>firstNametextbox.text = "John"
lastNametextbox.text = "Smith"
</code></pre>
<p>Day 2:</p>
<pre><code>firstNametextbox.text = "Jim"
lastNametextbox.text = "Smith"
</code></pre>
<p>Day 3:</p>
<pre><code>firstNametextbox.text = "Jacob"
lastNametextbox.text = "Smith"
</code></pre>
<p>On the fourth day I'd like the user to click a button and return just the results from Day 1, on the fifth day return the results from Day 1 and Day 2, etc.</p>
<p>I tried allowing the user to assign a date to the Day using a DateTimePicker and then checking to see if three days had passed. I also tried messing around with the Application Settings so that I could save information but it didn't seem very efficient. Any advice would be greatly appreciated.</p>
| 0debug |
Can I get PyCharm to suppress a particular warning on a single line? : <p>PyCharm provides some helpful warnings on code style, conventions and logical gotchas. It also provides a notification if I try to commit code with warnings (or errors).</p>
<p>Sometimes I consciously ignore these warnings for particular lines of code (for various reasons, typically to account for implementation details of third-party libraries). I want to suppress the warning, but just for that line (if the warning crops up on a different line where I'm not being deliberate, I want to know about it!)</p>
<p>How can I do that in PyCharm? (Following a universal Python convention strongly preferable.)</p>
| 0debug |
static int opt_deinterlace(void *optctx, const char *opt, const char *arg)
{
av_log(NULL, AV_LOG_WARNING, "-%s is deprecated, use -filter:v yadif instead\n", opt);
do_deinterlace = 1;
return 0;
}
| 1threat |
static void dct_unquantize_mpeg1_c(MpegEncContext *s,
DCTELEM *block, int n, int qscale)
{
int i, level, nCoeffs;
const UINT16 *quant_matrix;
if(s->alternate_scan) nCoeffs= 64;
else nCoeffs= s->block_last_index[n]+1;
if (s->mb_intra) {
if (n < 4)
block[0] = block[0] * s->y_dc_scale;
else
block[0] = block[0] * s->c_dc_scale;
quant_matrix = s->intra_matrix;
for(i=1;i<nCoeffs;i++) {
int j= zigzag_direct[i];
level = block[j];
if (level) {
if (level < 0) {
level = -level;
level = (int)(level * qscale * quant_matrix[j]) >> 3;
level = (level - 1) | 1;
level = -level;
} else {
level = (int)(level * qscale * quant_matrix[j]) >> 3;
level = (level - 1) | 1;
}
#ifdef PARANOID
if (level < -2048 || level > 2047)
fprintf(stderr, "unquant error %d %d\n", i, level);
#endif
block[j] = level;
}
}
} else {
i = 0;
quant_matrix = s->non_intra_matrix;
for(;i<nCoeffs;i++) {
int j= zigzag_direct[i];
level = block[j];
if (level) {
if (level < 0) {
level = -level;
level = (((level << 1) + 1) * qscale *
((int) (quant_matrix[j]))) >> 4;
level = (level - 1) | 1;
level = -level;
} else {
level = (((level << 1) + 1) * qscale *
((int) (quant_matrix[j]))) >> 4;
level = (level - 1) | 1;
}
#ifdef PARANOID
if (level < -2048 || level > 2047)
fprintf(stderr, "unquant error %d %d\n", i, level);
#endif
block[j] = level;
}
}
}
}
| 1threat |
Change small cube to a High cube : <p>I want my little cube to change to a bigger one when i click the upper arrow, and change back when i pres the down arrow. I have tried:</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerSkift : MonoBehaviour {
public gameObject myObject1;
public gameObject myObject2;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.UpArrow))
{
myObject1.SetActive (false);
myObject2.SetActive (true);
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
myObject2.SetActive(false);
myObject1.SetActive(true);
}
}
}
</code></pre>
<p>When i try to run it it says:</p>
<pre><code>Assets/PlayerSkift.cs(9,9): error CS0118: `UnityEngine.Component.gameObject' is a `property' but a `type' was expected
</code></pre>
<p>I have no idea what that means, so if you know it, or know how to do it in a other way. Please help.</p>
| 0debug |
Why removing second last element from arraylist remove method doesn't throw ConcurrentModificationException ? : List<Integer> number = new ArrayList<Integer>();
number.add(11);
number.add(45);
number.add(12);
number.add(32);
number.add(36);
number.removeIf(num -> num % 2 == 0);
System.out.println(number);
Why the above code not throws ConcurrentModificationException?
| 0debug |
i get an error "Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR)" : [this is the error occured when i debugging the program][1]
[1]: http://i.stack.imgur.com/HucHf.jpg
Below is the code where error occured ->
public function does_user_exist($email,$password)
{
$query = "Select * from users where email = '$email' and password='$password'";
**$result = mysqli_query(this -> connection, $query);** | 0debug |
How to handle global variables to be tha same for all users in PHP? : <p>I want to create simple multiplayer game with php using global variables that will be shared among all users, without using sockets.</p>
<p>I tried write php server that have on global variable called "connections" and code to handle GET request with url parameter that called "myName".
when the user send the GET request to the php server, "connections" is incremented and sent back to the user as the GET response.</p>
<pre><code><?php
$connections = 0;
if(isset($_GET['myName'])) {
$connections = $connections+ 1;
echo json_encode($connections);
exit();
}
?>
<html>
<head>
</head>
<body>
<form action="Test/testServer.php">
<input type="text" name="myName">
<input type="submit" value="submit">
</form>
</body>
</html>
</code></pre>
<p>I am new to php and perhaps i missing something about how php server is actually work. I expected the "connections" to be the number of connected users that send GET request along all the "server life".</p>
| 0debug |
cURL error 60: SSL certificate in Laravel 5.4 : <p><strong>Full Error</strong></p>
<p><code>RequestException in CurlFactory.php line 187: cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)</code></p>
<p><strong>Scenario</strong></p>
<p>Before anyone points me to these two laracasts answers: <a href="https://laracasts.com/discuss/channels/general-discussion/curl-error-60-ssl-certificate-problem-unable-to-get-local-issuer-certificate" rel="noreferrer">https://laracasts.com/discuss/channels/general-discussion/curl-error-60-ssl-certificate-problem-unable-to-get-local-issuer-certificate</a></p>
<p><a href="https://laracasts.com/discuss/channels/general-discussion/curl-error-60-ssl-certificate-problem-unable-to-get-local-issuer-certificate/replies/52954" rel="noreferrer">https://laracasts.com/discuss/channels/general-discussion/curl-error-60-ssl-certificate-problem-unable-to-get-local-issuer-certificate/replies/52954</a></p>
<p>I've already looked at them and thats why im here,</p>
<p>The problem i have is that i now have the cacert.pem file BUT it doesn't make sense where to put it, the answers indicate to place the file in my xampp directory and change my <code>php.ini</code> file but im not using xampp for anything, im using laravel's artisan server to run my project. If xampp is not in use then where do i place this file & more so why would an accepted answer be to place it in my xampp directory i dont understand</p>
<p><strong>My Exact Question</strong></p>
<p>Where do i place the <code>cacert.pem</code> file to stop this error in laravel 5.4? </p>
| 0debug |
Unhandled Exception: Access violation writing location 0x00000000 : <p>I am doing a simple application to define a structure and place data in tha structure to learn the concept of structures. But when trying to insert data to structure i am getting an access violation. Following is the code portions.</p>
<p>In Test.h file</p>
<pre><code>typedef struct Msg
{
unsigned char* message_id;
unsigned char* message_name;
}Msg_t;
</code></pre>
<p>In Test.cpp file</p>
<pre><code>Msg_t *new_node[10];
const char *src = "E0";
new_node[0]->message_id = (unsigned char *)_strdup(src); //getting access violation error here.
</code></pre>
<p>Why am i getting error? Please help.</p>
| 0debug |
A way to only link fonts react native : <p>I am working with react native and I only want to link my fonts and nothing else.</p>
<p>I am using react-native-maps and it specifically says in the docs "Do not use <code>react-native link</code>"</p>
<p>Everywhere I look I see that people say to do <code>react-native link</code> in order to link fonts but I am wonder in if there is proper syntax for just linking fonts like:</p>
<p><code>react-native link ./assets/fonts</code> or something? That way it will not also link all my other libraries</p>
| 0debug |
INotifyPropertyChanged binding selected checkboxes in MVVM : <p>I am trying to rewrite my CheckBoxList from Code Behind to MVVM pattern in WPF C#. The thing is that now I have a problem to get all selected checkboxes. I have implemented INotifyPropertyChanged interface. Project is building correctly, when I set the break point I can notice that I received always false value for my checkboxes, even if they are selected. I assume that maybe I did something wrong with data binding. Please, does anybody can help? I am totally newbie in MVVM.</p>
<p><strong>INotifyPropertyChanged Implementation</strong> </p>
<pre><code> public class ObservableObject : INotifyPropertyChanged
{
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string strPropertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(strPropertyName));
}
#endregion
}
}
</code></pre>
<p><strong>Model</strong></p>
<pre><code> public class SharedModel : ObservableObject
{
public bool IsSelected { get; set; }
public string Name { get; set; }
public string Method { get; set; }
}
</code></pre>
<p><strong>ViewModel</strong></p>
<pre><code> class TestViewModel : ObservableObject
{
private bool _fIsSelected;
public bool IsSelected
{
get => _fIsSelected;
set
{
_fIsSelected = value;
OnPropertyChanged("IsSelected");
}
}
public ObservableCollection<SharedModel> List { get; set; } = new ObservableCollection<SharedModel>
{
new SharedModel
{
Name = "A1",
Method = Test(),
},
new SharedModel
{
Name = "A2",
Method = TestOne()
}
};
public string GetSelectedCheckboxes()
{
var command =
from item in List
where item.IsSelected
select item.Method;
return string.Join("\r&", new NewList<string>(command).ToArray());
}
</code></pre>
<p>Checkboxlist in XAML</p>
<pre><code><StackPanel Margin="0,0,769,510">
<ListBox Name="ListBox"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ItemsSource="{Binding List}"
SelectionMode="Multiple" Background="{x:Null}" Margin="0,133,590,470" Foreground="White" BorderBrush="{x:Null}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal"
MinWidth="170" MaxWidth="170"
Margin="0,0, 0, 0" >
<CheckBox x:Name="TestCheckbox"
Tag="{Binding Method}" IsChecked="{Binding IsSelected}" />
<ContentPresenter
Content="{Binding Name}"
Margin="5,0, 15, 0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</code></pre>
<p><strong>Test View</strong></p>
<pre><code>public partial class TestView : UserControl
{
public TestView()
{
InitializeComponent();
DataContext = new TestViewModel();
}
</code></pre>
| 0debug |
No error being thrown but data not inserting into db (PHP PDO) : <p>I have a PHP function to insert a new user into a MySQL database using PDO but for some reason the data doesnt end up inserting, it doesn't throw an error and i can insert data manualy just fine but cant seem to figure out the issue?</p>
<pre><code>public function createNewUser($username, $password, $firstname, $lastname)
{
try
{
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$sqlQuery = "INSERT INTO users(u_username, u_password, u_firstname, u_lastname, u_datecreated) VALUES (?, ?, ?, ?, ?)";
$statement = $this->_dbHandle->prepare($sqlQuery)->execute([$username, $hashedPassword, $firstname, $lastname, date(SQL_DATE)]);
print "INSERTED USER";
}
catch (PDOException $e)
{
echo $e->getMessage();
die();
}
}
</code></pre>
| 0debug |
why am i getting the following error? : **I have the following error while executing a sql code**
Msg 102, Level 15, State 1, Server WIN-ILO9GLLB9J0, Line 9
Incorrect syntax near 'name'.
Msg 102, Level 15, State 1, Server WIN-ILO9GLLB9J0, Line 10
Incorrect syntax near 'name'.
Msg 102, Level 15, State 1, Server WIN-ILO9GLLB9J0, Line 11
Incorrect syntax near 'name'.
Msg 102, Level 15, State 1, Server WIN-ILO9GLLB9J0, Line 12
Incorrect syntax near 'name'.
Msg 102, Level 15, State 1, Server WIN-ILO9GLLB9J0, Line 13
Incorrect syntax near 'name'.
**my code is like this:**
CREATE TABLE city(
id number(5) ,
name varchar2(17) ,
countrycode varchar2(3) ,
district varchar2(20) ,
population number(20)
);
INSERT INTO city(id,'name', 'countrycode','district',population) values(3878,'Scottsdale', 'USA', 'Arizona', 202705 );
INSERT INTO city(id,'name','countrycode','district',population) values(3965, 'Corona' ,'USA', 'California' ,124966);
INSERT INTO city(id,'name','countrycode','district',population) values(3973,'Concord', 'USA','California',121780);
INSERT INTO city(id,'name','countrycode','district',population) values(3977,'Cedar', 'Rapids', 'USA', 'Iowa' ,120758 );
INSERT INTO city(id,'name','countrycode','district',population) values(3982,'Coral Springs', 'USA', 'Florida', 117549 );
SELECT * from city where (population > 100000);
| 0debug |
comparing two integers and insert a comparison sign <,>= between the two numbers : I would like to compare two integers and add a comparison sign between them. I do not use any logical, relational and bitwise operators and no if then else or while loop . I found the max and min of these two numbers . But how can I preserve the order and still insert the comparison sign. Any ideas ?
thanks
Eg:
4 6 was entered by user output must be 4 < 6
10 2 was entered by user output must be 10 > 2
2 2 was enetered by user output must be 10=10 | 0debug |
static void av_estimate_timings_from_pts(AVFormatContext *ic, offset_t old_offset)
{
AVPacket pkt1, *pkt = &pkt1;
AVStream *st;
int read_size, i, ret;
int64_t end_time;
int64_t filesize, offset, duration;
if (ic->cur_st && ic->cur_st->parser)
av_free_packet(&ic->cur_pkt);
ic->cur_st = NULL;
flush_packet_queue(ic);
for(i=0;i<ic->nb_streams;i++) {
st = ic->streams[i];
if (st->parser) {
av_parser_close(st->parser);
st->parser= NULL;
}
}
url_fseek(&ic->pb, 0, SEEK_SET);
read_size = 0;
for(;;) {
if (read_size >= DURATION_MAX_READ_SIZE)
break;
for(i = 0;i < ic->nb_streams; i++) {
st = ic->streams[i];
if (st->start_time == AV_NOPTS_VALUE)
break;
}
if (i == ic->nb_streams)
break;
ret = av_read_packet(ic, pkt);
if (ret != 0)
break;
read_size += pkt->size;
st = ic->streams[pkt->stream_index];
if (pkt->pts != AV_NOPTS_VALUE) {
if (st->start_time == AV_NOPTS_VALUE)
st->start_time = pkt->pts;
}
av_free_packet(pkt);
}
filesize = ic->file_size;
offset = filesize - DURATION_MAX_READ_SIZE;
if (offset < 0)
offset = 0;
url_fseek(&ic->pb, offset, SEEK_SET);
read_size = 0;
for(;;) {
if (read_size >= DURATION_MAX_READ_SIZE)
break;
for(i = 0;i < ic->nb_streams; i++) {
st = ic->streams[i];
if (st->duration == AV_NOPTS_VALUE)
break;
}
if (i == ic->nb_streams)
break;
ret = av_read_packet(ic, pkt);
if (ret != 0)
break;
read_size += pkt->size;
st = ic->streams[pkt->stream_index];
if (pkt->pts != AV_NOPTS_VALUE) {
end_time = pkt->pts;
duration = end_time - st->start_time;
if (duration > 0) {
if (st->duration == AV_NOPTS_VALUE ||
st->duration < duration)
st->duration = duration;
}
}
av_free_packet(pkt);
}
fill_all_stream_timings(ic);
url_fseek(&ic->pb, old_offset, SEEK_SET);
for(i=0; i<ic->nb_streams; i++){
st= ic->streams[i];
st->cur_dts= st->first_dts;
}
}
| 1threat |
how use strings with $ (not var) in PHP : <p>I place to the php line a large piece of html code with javascript inserts (with jQuery) in which $ symbols is present.</p>
<pre><code><?php
$site = <<<SITE_CODE
setTimeout(function(){$(g_utils._f().menu.current_id).trigger('click')}, g_utils.effects.animation(g_utils._f().animation.events.loading, 'delay2'));
SITE_CODE;
echo $site;
?>
</code></pre>
<p>PHP takes this as a variable and produces an error.</p>
<blockquote>
<p>Parse error: syntax error, unexpected '(', expecting T_VARIABLE or '$'
in D:\site\index.php on line 328</p>
</blockquote>
<p>Tell me how to get rid of this problem?</p>
| 0debug |
int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,
uint8_t *buf, int nb_sectors, bool enc,
Error **errp)
{
union {
uint64_t ll[2];
uint8_t b[16];
} ivec;
int i;
int ret;
for(i = 0; i < nb_sectors; i++) {
ivec.ll[0] = cpu_to_le64(sector_num);
ivec.ll[1] = 0;
if (qcrypto_cipher_setiv(s->cipher,
ivec.b, G_N_ELEMENTS(ivec.b),
errp) < 0) {
return -1;
}
if (enc) {
ret = qcrypto_cipher_encrypt(s->cipher,
buf, buf,
512,
errp);
} else {
ret = qcrypto_cipher_decrypt(s->cipher,
buf, buf,
512,
errp);
}
if (ret < 0) {
return -1;
}
sector_num++;
buf += 512;
}
return 0;
}
| 1threat |
Unable to write procedure about a^b in c : Hello guys i need to write procedure about two numbers for eg.. a^b but i can´t use pow statement... any ideas? I am lost...
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
void multiplied ( int *b, int *n)
{int i,vys;
while (i<=n)
{
vys=*b**b;
i++;
}
return vys;
}
main(void)
{
int b=0,n=0,vys;
printf("Give numbers b and n but they must be in interval <0,10>!\n");
scanf("%d %d",&b ,&n);
if ((b < 0 || b>10) || (n<0 || n>10))
{
printf("Numbers are not in interval <0,10>!\n");}
else
{printf("Number is in interval so i continue...\n");
sleep(2);
mocnina(&b , &n);
printf("%d",vys);
}}
| 0debug |
How is the best combination for Laravel VueJs? : <p>actually i just learn about Vue.js and i have some knowledge using Laravel. I want to combine both of them, im searching for tutorials on internet and i found 2 kind of combination.</p>
<p>the first one is they separate Laravel and Vue, and the second one they combine both of them in Laravel Directory. Which one is the best for use guys? and can you guys tell me what is the benefits of each other? thank you so much.</p>
| 0debug |
static void notdirty_mem_write(void *opaque, target_phys_addr_t ram_addr,
uint64_t val, unsigned size)
{
int dirty_flags;
dirty_flags = cpu_physical_memory_get_dirty_flags(ram_addr);
if (!(dirty_flags & CODE_DIRTY_FLAG)) {
#if !defined(CONFIG_USER_ONLY)
tb_invalidate_phys_page_fast(ram_addr, size);
dirty_flags = cpu_physical_memory_get_dirty_flags(ram_addr);
#endif
}
switch (size) {
case 1:
stb_p(qemu_get_ram_ptr(ram_addr), val);
break;
case 2:
stw_p(qemu_get_ram_ptr(ram_addr), val);
break;
case 4:
stl_p(qemu_get_ram_ptr(ram_addr), val);
break;
default:
abort();
}
dirty_flags |= (0xff & ~CODE_DIRTY_FLAG);
cpu_physical_memory_set_dirty_flags(ram_addr, dirty_flags);
if (dirty_flags == 0xff)
tlb_set_dirty(cpu_single_env, cpu_single_env->mem_io_vaddr);
}
| 1threat |
static const char *srt_to_ass(AVCodecContext *avctx, char *out, char *out_end,
const char *in, int x1, int y1, int x2, int y2)
{
char c, *param, buffer[128], tmp[128];
int len, tag_close, sptr = 1, line_start = 1, an = 0, end = 0;
SrtStack stack[16];
stack[0].tag[0] = 0;
strcpy(stack[0].param[PARAM_SIZE], "{\\fs}");
strcpy(stack[0].param[PARAM_COLOR], "{\\c}");
strcpy(stack[0].param[PARAM_FACE], "{\\fn}");
if (x1 >= 0 && y1 >= 0) {
if (x2 >= 0 && y2 >= 0 && (x2 != x1 || y2 != y1))
out += snprintf(out, out_end-out,
"{\\an1}{\\move(%d,%d,%d,%d)}", x1, y1, x2, y2);
else
out += snprintf(out, out_end-out, "{\\an1}{\\pos(%d,%d)}", x1, y1);
}
for (; out < out_end && !end && *in; in++) {
switch (*in) {
case '\r':
break;
case '\n':
if (line_start) {
end = 1;
break;
}
while (out[-1] == ' ')
out--;
out += snprintf(out, out_end-out, "\\N");
line_start = 1;
break;
case ' ':
if (!line_start)
*out++ = *in;
break;
case '{':
an += sscanf(in, "{\\an%*1u}%c", &c) == 1;
if ((an != 1 && sscanf(in, "{\\%*[^}]}%n%c", &len, &c) > 0) ||
sscanf(in, "{%*1[CcFfoPSsYy]:%*[^}]}%n%c", &len, &c) > 0) {
in += len - 1;
} else
*out++ = *in;
break;
case '<':
tag_close = in[1] == '/';
if (sscanf(in+tag_close+1, "%127[^>]>%n%c", buffer, &len,&c) >= 2) {
if ((param = strchr(buffer, ' ')))
*param++ = 0;
if ((!tag_close && sptr < FF_ARRAY_ELEMS(stack)) ||
( tag_close && sptr > 0 && !strcmp(stack[sptr-1].tag, buffer))) {
int i, j, unknown = 0;
in += len + tag_close;
if (!tag_close)
memset(stack+sptr, 0, sizeof(*stack));
if (!strcmp(buffer, "font")) {
if (tag_close) {
for (i=PARAM_NUMBER-1; i>=0; i--)
if (stack[sptr-1].param[i][0])
for (j=sptr-2; j>=0; j--)
if (stack[j].param[i][0]) {
out += snprintf(out, out_end-out,
stack[j].param[i]);
break;
}
} else {
while (param) {
if (!strncmp(param, "size=", 5)) {
unsigned font_size;
param += 5 + (param[5] == '"');
if (sscanf(param, "%u", &font_size) == 1) {
snprintf(stack[sptr].param[PARAM_SIZE],
sizeof(stack[0].param[PARAM_SIZE]),
"{\\fs%u}", font_size);
}
} else if (!strncmp(param, "color=", 6)) {
param += 6 + (param[6] == '"');
snprintf(stack[sptr].param[PARAM_COLOR],
sizeof(stack[0].param[PARAM_COLOR]),
"{\\c&H%X&}",
html_color_parse(avctx, param));
} else if (!strncmp(param, "face=", 5)) {
param += 5 + (param[5] == '"');
len = strcspn(param,
param[-1] == '"' ? "\"" :" ");
av_strlcpy(tmp, param,
FFMIN(sizeof(tmp), len+1));
param += len;
snprintf(stack[sptr].param[PARAM_FACE],
sizeof(stack[0].param[PARAM_FACE]),
"{\\fn%s}", tmp);
}
if ((param = strchr(param, ' ')))
param++;
}
for (i=0; i<PARAM_NUMBER; i++)
if (stack[sptr].param[i][0])
out += snprintf(out, out_end-out,
stack[sptr].param[i]);
}
} else if (!buffer[1] && strspn(buffer, "bisu") == 1) {
out += snprintf(out, out_end-out,
"{\\%c%d}", buffer[0], !tag_close);
} else {
unknown = 1;
snprintf(tmp, sizeof(tmp), "</%s>", buffer);
}
if (tag_close) {
sptr--;
} else if (unknown && !strstr(in, tmp)) {
in -= len + tag_close;
*out++ = *in;
} else
av_strlcpy(stack[sptr++].tag, buffer,
sizeof(stack[0].tag));
break;
}
}
default:
*out++ = *in;
break;
}
if (*in != ' ' && *in != '\r' && *in != '\n')
line_start = 0;
}
out = FFMIN(out, out_end-3);
while (!strncmp(out-2, "\\N", 2))
out -= 2;
while (out[-1] == ' ')
out--;
out += snprintf(out, out_end-out, "\r\n");
return in;
}
| 1threat |
static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
{
int fd;
int result = 0;
int64_t total_size = 0;
bool nocow = false;
PreallocMode prealloc;
char *buf = NULL;
Error *local_err = NULL;
strstart(filename, "file:", &filename);
total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
BDRV_SECTOR_SIZE);
nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
&local_err);
g_free(buf);
if (local_err) {
error_propagate(errp, local_err);
result = -EINVAL;
goto out;
}
fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
0644);
if (fd < 0) {
result = -errno;
error_setg_errno(errp, -result, "Could not create file");
goto out;
}
if (nocow) {
#ifdef __linux__
int attr;
if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
attr |= FS_NOCOW_FL;
ioctl(fd, FS_IOC_SETFLAGS, &attr);
}
#endif
}
if (ftruncate(fd, total_size) != 0) {
result = -errno;
error_setg_errno(errp, -result, "Could not resize file");
goto out_close;
}
switch (prealloc) {
#ifdef CONFIG_POSIX_FALLOCATE
case PREALLOC_MODE_FALLOC:
result = -posix_fallocate(fd, 0, total_size);
if (result != 0) {
error_setg_errno(errp, -result,
"Could not preallocate data for the new file");
}
break;
#endif
case PREALLOC_MODE_FULL:
{
int64_t num = 0, left = total_size;
buf = g_malloc0(65536);
while (left > 0) {
num = MIN(left, 65536);
result = write(fd, buf, num);
if (result < 0) {
result = -errno;
error_setg_errno(errp, -result,
"Could not write to the new file");
break;
}
left -= result;
}
fsync(fd);
g_free(buf);
break;
}
case PREALLOC_MODE_OFF:
break;
default:
result = -EINVAL;
error_setg(errp, "Unsupported preallocation mode: %s",
PreallocMode_lookup[prealloc]);
break;
}
out_close:
if (qemu_close(fd) != 0 && result == 0) {
result = -errno;
error_setg_errno(errp, -result, "Could not close the new file");
}
out:
return result;
}
| 1threat |
Keras RNN with LSTM cells for predicting multiple output time series based on multiple intput time series : <p>I would like to model RNN with LSTM cells in order to predict multiple output time series based on multiple input time series. To be specific, I have 4 output time series, y1[t], y2[t], y3[t], y4[t], each has a length 3,000 (t=0,...,2999). I also have 3 input time series, x1[t], x2[t], x3[t], and each has a length 3,000 sec (t=0,...,2999). The goal is to predict y1[t],.. y4[t] using all the input time series up to this current time point i.e.:</p>
<pre><code> y1[t] = f1(x1[k],x2[k],x3[k], k = 0,...,t)
y2[t] = f2(x1[k],x2[k],x3[k], k = 0,...,t)
y3[t] = f3(x1[k],x2[k],x3[k], k = 0,...,t)
y4[t] = f3(x1[k],x2[k],x3[k], k = 0,...,t)
</code></pre>
<p>For a model to have a long term memory, I created a stateful RNN model by following. <a href="http://philipperemy.github.io/keras-stateful-lstm/" rel="noreferrer">keras-stateful-lstme</a>. The main difference between my case and <a href="http://philipperemy.github.io/keras-stateful-lstm/" rel="noreferrer">keras-stateful-lstme</a> is that I have:</p>
<ul>
<li>more than 1 output time series</li>
<li>more than 1 input time series</li>
<li>the goal is the prediction of continuous time series</li>
</ul>
<p>My code is running. However the model's prediction result is bad even with a simple data. So I would like to ask you if I am getting anything wrong.</p>
<p>Here is my code with a toy example.</p>
<p>In toy example, our input time series are simple cosign and sign waves:</p>
<pre><code>import numpy as np
def random_sample(len_timeseries=3000):
Nchoice = 600
x1 = np.cos(np.arange(0,len_timeseries)/float(1.0 + np.random.choice(Nchoice)))
x2 = np.cos(np.arange(0,len_timeseries)/float(1.0 + np.random.choice(Nchoice)))
x3 = np.sin(np.arange(0,len_timeseries)/float(1.0 + np.random.choice(Nchoice)))
x4 = np.sin(np.arange(0,len_timeseries)/float(1.0 + np.random.choice(Nchoice)))
y1 = np.random.random(len_timeseries)
y2 = np.random.random(len_timeseries)
y3 = np.random.random(len_timeseries)
for t in range(3,len_timeseries):
## the output time series depend on input as follows:
y1[t] = x1[t-2]
y2[t] = x2[t-1]*x3[t-2]
y3[t] = x4[t-3]
y = np.array([y1,y2,y3]).T
X = np.array([x1,x2,x3,x4]).T
return y, X
def generate_data(Nsequence = 1000):
X_train = []
y_train = []
for isequence in range(Nsequence):
y, X = random_sample()
X_train.append(X)
y_train.append(y)
return np.array(X_train),np.array(y_train)
</code></pre>
<p>Please notice that y1 at time point t is simply the value of x1 at t - 2.
Please also notice that y3 at time point t is simply the value of x1 in the two previous step.</p>
<p>Using these functions, I generated 100 sets of time series y1,y2,y3,x1,x2,x3,x4. Half of them go to training data and the remaining half go to testing data.</p>
<pre><code>Nsequence = 100
prop = 0.5
Ntrain = Nsequence*prop
X, y = generate_data(Nsequence)
X_train = X[:Ntrain,:,:]
X_test = X[Ntrain:,:,:]
y_train = y[:Ntrain,:,:]
y_test = y[Ntrain:,:,:]
</code></pre>
<p>X, y are both 3 dimensional and each contains:</p>
<pre><code>#X.shape = (N sequence, length of time series, N input features)
#y.shape = (N sequence, length of time series, N targets)
print X.shape, y.shape
> (100, 3000, 4) (100, 3000, 3)
</code></pre>
<p>The example of the time series y1, .. y4 and x1, .., x3 are shown as below:</p>
<p><a href="https://i.stack.imgur.com/u100N.png" rel="noreferrer"><img src="https://i.stack.imgur.com/u100N.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/PtOvt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PtOvt.png" alt="enter image description here"></a></p>
<p>I standardize these data as:</p>
<pre><code>def standardize(X_train,stat=None):
## X_train is 3 dimentional e.g. (Nsample,len_timeseries, Nfeature)
## standardization is done with respect to the 3rd dimention
if stat is None:
featmean = np.array([np.nanmean(X_train[:,:,itrain]) for itrain in range(X_train.shape[2])]).reshape(1,1,X_train.shape[2])
featstd = np.array([np.nanstd(X_train[:,:,itrain]) for itrain in range(X_train.shape[2])]).reshape(1,1,X_train.shape[2])
stat = {"featmean":featmean,"featstd":featstd}
else:
featmean = stat["featmean"]
featstd = stat["featstd"]
X_train_s = (X_train - featmean)/featstd
return X_train_s, stat
X_train_s, X_stat = standardize(X_train,stat=None)
X_test_s, _ = standardize(X_test,stat=X_stat)
y_train_s, y_stat = standardize(y_train,stat=None)
y_test_s, _ = standardize(y_test,stat=y_stat)
</code></pre>
<p><strong>Create a stateful RNN model with 10 LSTM hidden neurons</strong></p>
<pre><code>from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
def create_stateful_model(hidden_neurons):
# create and fit the LSTM network
model = Sequential()
model.add(LSTM(hidden_neurons,
batch_input_shape=(1, 1, X_train.shape[2]),
return_sequences=False,
stateful=True))
model.add(Dropout(0.5))
model.add(Dense(y_train.shape[2]))
model.add(Activation("linear"))
model.compile(loss='mean_squared_error', optimizer="rmsprop",metrics=['mean_squared_error'])
return model
model = create_stateful_model(10)
</code></pre>
<p>Now following code is used to train and validate the RNN model:</p>
<pre><code>def get_R2(y_pred,y_test):
## y_pred_s_batch: (Nsample, len_timeseries, Noutput)
## the relative percentage error is computed for each output
overall_mean = np.nanmean(y_test)
SSres = np.nanmean( (y_pred - y_test)**2 ,axis=0).mean(axis=0)
SStot = np.nanmean( (y_test - overall_mean)**2 ,axis=0).mean(axis=0)
R2 = 1 - SSres / SStot
print "<R2 testing> target 1:",R2[0],"target 2:",R2[1],"target 3:",R2[2]
return R2
def reshape_batch_input(X_t,y_t=None):
X_t = np.array(X_t).reshape(1,1,len(X_t)) ## (1,1,4) dimention
if y_t is not None:
y_t = np.array([y_t]) ## (1,3)
return X_t,y_t
def fit_stateful(model,X_train,y_train,X_test,y_test,nb_epoch=8):
'''
reference: http://philipperemy.github.io/keras-stateful-lstm/
X_train: (N_time_series, len_time_series, N_features) = (10,000, 3,600 (max), 2),
y_train: (N_time_series, len_time_series, N_output) = (10,000, 3,600 (max), 4)
'''
max_len = X_train.shape[1]
print "X_train.shape(Nsequence =",X_train.shape[0],"len_timeseries =",X_train.shape[1],"Nfeats =",X_train.shape[2],")"
print "y_train.shape(Nsequence =",y_train.shape[0],"len_timeseries =",y_train.shape[1],"Ntargets =",y_train.shape[2],")"
print('Train...')
for epoch in range(nb_epoch):
print('___________________________________')
print "epoch", epoch+1, "out of ",nb_epoch
## ---------- ##
## training ##
## ---------- ##
mean_tr_acc = []
mean_tr_loss = []
for s in range(X_train.shape[0]):
for t in range(max_len):
X_st = X_train[s][t]
y_st = y_train[s][t]
if np.any(np.isnan(y_st)):
break
X_st,y_st = reshape_batch_input(X_st,y_st)
tr_loss, tr_acc = model.train_on_batch(X_st,y_st)
mean_tr_acc.append(tr_acc)
mean_tr_loss.append(tr_loss)
model.reset_states()
##print('accuracy training = {}'.format(np.mean(mean_tr_acc)))
print('<loss (mse) training> {}'.format(np.mean(mean_tr_loss)))
## ---------- ##
## testing ##
## ---------- ##
y_pred = predict_stateful(model,X_test)
eva = get_R2(y_pred,y_test)
return model, eva, y_pred
def predict_stateful(model,X_test):
y_pred = []
max_len = X_test.shape[1]
for s in range(X_test.shape[0]):
y_s_pred = []
for t in range(max_len):
X_st = X_test[s][t]
if np.any(np.isnan(X_st)):
## the rest of y is NA
y_s_pred.extend([np.NaN]*(max_len-len(y_s_pred)))
break
X_st,_ = reshape_batch_input(X_st)
y_st_pred = model.predict_on_batch(X_st)
y_s_pred.append(y_st_pred[0].tolist())
y_pred.append(y_s_pred)
model.reset_states()
y_pred = np.array(y_pred)
return y_pred
model, train_metric, y_pred = fit_stateful(model,
X_train_s,y_train_s,
X_test_s,y_test_s,nb_epoch=15)
</code></pre>
<p>The output is the following:</p>
<pre><code>X_train.shape(Nsequence = 15 len_timeseries = 3000 Nfeats = 4 )
y_train.shape(Nsequence = 15 len_timeseries = 3000 Ntargets = 3 )
Train...
___________________________________
epoch 1 out of 15
<loss (mse) training> 0.414115458727
<R2 testing> target 1: 0.664464304688 target 2: -0.574523052322 target 3: 0.526447813052
___________________________________
epoch 2 out of 15
<loss (mse) training> 0.394549429417
<R2 testing> target 1: 0.361516087033 target 2: -0.724583671831 target 3: 0.795566178787
___________________________________
epoch 3 out of 15
<loss (mse) training> 0.403199136257
<R2 testing> target 1: 0.09610702779 target 2: -0.468219774909 target 3: 0.69419269042
___________________________________
epoch 4 out of 15
<loss (mse) training> 0.406423777342
<R2 testing> target 1: 0.469149270848 target 2: -0.725592048946 target 3: 0.732963522766
___________________________________
epoch 5 out of 15
<loss (mse) training> 0.408153116703
<R2 testing> target 1: 0.400821776652 target 2: -0.329415365214 target 3: 0.2578432553
___________________________________
epoch 6 out of 15
<loss (mse) training> 0.421062678099
<R2 testing> target 1: -0.100464591586 target 2: -0.232403824523 target 3: 0.570606489959
___________________________________
epoch 7 out of 15
<loss (mse) training> 0.417774856091
<R2 testing> target 1: 0.320094445321 target 2: -0.606375769083 target 3: 0.349876223119
___________________________________
epoch 8 out of 15
<loss (mse) training> 0.427440851927
<R2 testing> target 1: 0.489543715713 target 2: -0.445328806611 target 3: 0.236463139804
___________________________________
epoch 9 out of 15
<loss (mse) training> 0.422931671143
<R2 testing> target 1: -0.31006468223 target 2: -0.322621276474 target 3: 0.122573123871
___________________________________
epoch 10 out of 15
<loss (mse) training> 0.43609803915
<R2 testing> target 1: 0.459111316554 target 2: -0.313382405804 target 3: 0.636854743292
___________________________________
epoch 11 out of 15
<loss (mse) training> 0.433844655752
<R2 testing> target 1: -0.0161015052703 target 2: -0.237462995323 target 3: 0.271788109459
___________________________________
epoch 12 out of 15
<loss (mse) training> 0.437297314405
<R2 testing> target 1: -0.493665758658 target 2: -0.234236263092 target 3: 0.047264439493
___________________________________
epoch 13 out of 15
<loss (mse) training> 0.470605045557
<R2 testing> target 1: 0.144443089961 target 2: -0.333210874982 target 3: -0.00432615142135
___________________________________
epoch 14 out of 15
<loss (mse) training> 0.444566756487
<R2 testing> target 1: -0.053982119103 target 2: -0.0676577449316 target 3: -0.12678037186
___________________________________
epoch 15 out of 15
<loss (mse) training> 0.482106208801
<R2 testing> target 1: 0.208482181828 target 2: -0.402982670798 target 3: 0.366757778713
</code></pre>
<p>As you can see, the training loss is NOT decreasing!!</p>
<p>As the target time series 1 and 3 have very simple relations with the input time series (y1[t] = x1[t-2] , y3[t] = x4[t-3]), I would expect perfect prediction performance. However, testing R2 at every epoch shows that that is not the case. R2 at the final epoch is just about 0.2 and 0.36. Clearly, the algorithm is not converging. I am very puzzled with this result. Please do let me know what I am missing, and why the algorithm is not converging. </p>
| 0debug |
need this to return what is entered : <pre><code>import java.util.Scanner;
public class Bigger{
public static void main(String [] args)
{
// declare variables
Scanner keyboardIn = new Scanner(System.in);
String userName = new String();
String fName = new String();
int numberLetters = 0;
int bigLetters=0;
char firstLetter;
// get user name from the user
System.out.print("Please enter your user name: ");
userName = keyboardIn.nextLine();
// get second name from the user
System.out.print("Please enter your second name: ");
fName = keyboardIn.nextLine();
// use an appropriate method to find the number of letters
numberLetters = userName.length();
bigLetters = fName.length();
if(numberLetters > bigLetters)
{
System.out.print("String 1 Is the longest string ");
}
else
{
System.out.print("String 2 Is the longest string ");
}
}
}
</code></pre>
<p>I need this to print out the actual string with the actual letters so if Denmark is the bigger string i need it to print this out to the user. How do i do this?</p>
<p>Regards,</p>
<p>Mark</p>
| 0debug |
static int mm_probe(AVProbeData *p)
{
if (p->buf_size < MM_PREAMBLE_SIZE)
return 0;
if (AV_RL16(&p->buf[0]) != MM_TYPE_HEADER)
return 0;
if (AV_RL32(&p->buf[2]) != MM_HEADER_LEN_V && AV_RL32(&p->buf[2]) != MM_HEADER_LEN_AV)
return 0;
return AVPROBE_SCORE_MAX / 2;
}
| 1threat |
void ff_put_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels,
int line_size)
{
const DCTELEM *p;
uint8_t *pix;
p = block;
pix = pixels;
__asm__ volatile (
"movq %3, %%mm0 \n\t"
"movq 8%3, %%mm1 \n\t"
"movq 16%3, %%mm2 \n\t"
"movq 24%3, %%mm3 \n\t"
"movq 32%3, %%mm4 \n\t"
"movq 40%3, %%mm5 \n\t"
"movq 48%3, %%mm6 \n\t"
"movq 56%3, %%mm7 \n\t"
"packuswb %%mm1, %%mm0 \n\t"
"packuswb %%mm3, %%mm2 \n\t"
"packuswb %%mm5, %%mm4 \n\t"
"packuswb %%mm7, %%mm6 \n\t"
"movq %%mm0, (%0) \n\t"
"movq %%mm2, (%0, %1) \n\t"
"movq %%mm4, (%0, %1, 2) \n\t"
"movq %%mm6, (%0, %2) \n\t"
:: "r"(pix), "r"((x86_reg)line_size), "r"((x86_reg)line_size * 3),
"m"(*p)
: "memory");
pix += line_size * 4;
p += 32;
__asm__ volatile (
"movq (%3), %%mm0 \n\t"
"movq 8(%3), %%mm1 \n\t"
"movq 16(%3), %%mm2 \n\t"
"movq 24(%3), %%mm3 \n\t"
"movq 32(%3), %%mm4 \n\t"
"movq 40(%3), %%mm5 \n\t"
"movq 48(%3), %%mm6 \n\t"
"movq 56(%3), %%mm7 \n\t"
"packuswb %%mm1, %%mm0 \n\t"
"packuswb %%mm3, %%mm2 \n\t"
"packuswb %%mm5, %%mm4 \n\t"
"packuswb %%mm7, %%mm6 \n\t"
"movq %%mm0, (%0) \n\t"
"movq %%mm2, (%0, %1) \n\t"
"movq %%mm4, (%0, %1, 2) \n\t"
"movq %%mm6, (%0, %2) \n\t"
:: "r"(pix), "r"((x86_reg)line_size), "r"((x86_reg)line_size * 3), "r"(p)
: "memory");
}
| 1threat |
Why 0/0 is NaN but 0/0.00 isn't : <p>Using <code>DataTable.Compute</code>, and have built some cases to test:</p>
<pre><code>dt.Compute("0/0", null); //returns NaN when converted to double
dt.Compute("0/0.00", null); //results in DivideByZero exception
</code></pre>
<p>I have changed my code to handle both. But curious to know what's going on here?</p>
| 0debug |
Spring Security: How to use multiple URL patterns in FilterRegistrationBean? : <p>I have a bean</p>
<pre><code>@Bean
public FilterRegistrationBean animalsFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new AnimalsFilter());
registration.addUrlPatterns(
"/api/cat",
"/api/cat/**",
"/api/dog"
);
...
return registration;
}
</code></pre>
<p>In that bean, I use two patterns for <code>/api/cat**</code> URLs. The problem is that when I try to call endpoints with complex postfix (<code>/api/cat/1/feed</code>), my filter does not intercept the request. But it's OK when I call <code>/api/cat</code> and <code>/api/got</code> endpoints -- filter works as expected and intercepts requests. </p>
<p>How can I use multiple URL patterns for my case (<code>/api/cat</code>, <code>/api/cat/**</code>)?</p>
<p><em>PS</em></p>
<p>I have tried to use next pattern combinations:</p>
<pre><code>1) /api/cat, /api/cat**, /api/dog
2) /api/cat, /api/cat/**, /api/dog
3) /api/cat**, /api/dog
</code></pre>
| 0debug |
int is_adx(const unsigned char *buf,size_t bufsize)
{
int offset;
if (buf[0]!=0x80) return 0;
offset = (read_long(buf)^0x80000000)+4;
if (bufsize<offset || memcmp(buf+offset-6,"(c)CRI",6)) return 0;
return offset;
}
| 1threat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.