problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
Given a key value string values, how to encode a key and not the content (Python 3) : <p>Given a key: value (name="My name is Bill"), in Python 3, I am trying to encode the key (that's name). Standard approaches like name.encode etc end up encoding the content. Need to encode it to bytes as next step </p>
| 0debug
|
void *cpu_physical_memory_map(target_phys_addr_t addr,
target_phys_addr_t *plen,
int is_write)
{
return address_space_map(&address_space_memory, addr, plen, is_write);
}
| 1threat
|
static int mcf_fec_can_receive(void *opaque)
{
mcf_fec_state *s = (mcf_fec_state *)opaque;
return s->rx_enabled;
}
| 1threat
|
static void do_acpitable_option(const char *optarg)
{
if (acpi_table_add(optarg) < 0) {
fprintf(stderr, "Wrong acpi table provided\n");
exit(1);
}
}
| 1threat
|
db.execute('SELECT * FROM products WHERE product_id = ' + product_input)
| 1threat
|
How to chain match and replace in JavaScript : str="abc { return false;}"
I just want to get the word "false" from the string "str", as follows,
str.match(/return \w+;/g).replace(/return/,"")
It 's wrong !
How can I correct this expression to get the desired word?
| 0debug
|
Material UI doesn't select a SelectField on hitting 'tab' : <p>Using <a href="http://www.material-ui.com/" rel="noreferrer">Material UI</a> for some components in my app.
I added a <code><SelectField /></code> <a href="http://www.material-ui.com/#/components/select-field" rel="noreferrer">select field</a> in a form. </p>
<p>Is there a way to make it work like a normal HTML <code><select></code> element, so that: </p>
<ul>
<li>When you hit <code>tab</code> on the keyboard, it highlights it when it's supposed to</li>
<li>When you hit <code>space</code> on the keyboard, it opens the dropdown</li>
</ul>
<p>Thanks in advance for your help. </p>
| 0debug
|
static void do_eject(int argc, const char **argv)
{
BlockDriverState *bs;
const char **parg;
int force;
parg = argv + 1;
if (!*parg) {
fail:
help_cmd(argv[0]);
return;
}
force = 0;
if (!strcmp(*parg, "-f")) {
force = 1;
parg++;
}
if (!*parg)
goto fail;
bs = bdrv_find(*parg);
if (!bs) {
term_printf("device not found\n");
return;
}
eject_device(bs, force);
}
| 1threat
|
Should I use React.PureComponent everywhere? : <p>React says pure render can optimize performance.
And now React has PureComponent.
Should I use React.PureComponent everywhere?
Or when to use React.PureComponent and where is the most proper postion to use React.PureComponent?</p>
| 0debug
|
Does Microsoft provide a swagger file for Graph? : <p>I've crawled though as much documentation as I can find but I'm unable to find a swagger file for <a href="https://graph.microsoft.io/" rel="noreferrer">https://graph.microsoft.io/</a></p>
<p>There appear to be a couple of variations on this API and I've seen references to the Office 365 Graph API and Azure Graph API but I believe that Microsoft Graph is that latest unified version and provides the features I'm after.</p>
<p>I'd like to use the with Microsoft Flow and I was surprised that it wasn't integrated as an API out of the box. To register a Custom API with Flow however you need to provide a swagger file, hence the question.</p>
| 0debug
|
I am trying to build a tree in php from an xml file : I am trying to read this xml file, but the code I am trying to make should work for any xml-file: [xml-file][1]
I am using these two [functions][2] to turn the xml-file into an array and turn that array into a tree. I am trying to keep the parent child relationship of the xml file. All I am getting back from the second function is an array with all the tags in the xml-file.
Can someone please help me?
[1]: http://i.stack.imgur.com/4g6pt.png
[2]: http://i.stack.imgur.com/ADO3n.png
| 0debug
|
Java: 2-dimensional char Array : <p>i've been trying to programm a game called Sokoban the last few days. The levels of the game are simple .txt files you can swap. I've already read the .txt file by using BufferedReader but have problems with saving it to an 2-dimensional char array because the number of rows and columns are different each level. Someone told me to make use of charAt but how do i do that.</p>
<p>Sokobanlevel format (<a href="http://www.sokoban-online.de/help/sokoban/level-format.html" rel="nofollow noreferrer">http://www.sokoban-online.de/help/sokoban/level-format.html</a>)</p>
<p>Hope you can help me. Thanks.</p>
<pre><code>String file = "...";
BufferedReader br = Files.newBufferedReader();
String line = null;
int rows = file.length;
int cols = file[0].length;
char[][] room = new char [rows][cols];
while ((line = br.readLine()) != null) {
System.out.println(room[rows][cols]);
}
</code></pre>
| 0debug
|
Notice "Undifined Variable" : <p>I am running a PHP script, and keep getting errors like:
<a href="http://i.stack.imgur.com/89eot.png" rel="nofollow">this is my error</a></p>
<p><a href="http://i.stack.imgur.com/YTYKT.png" rel="nofollow">this is script</a></p>
| 0debug
|
Unpacking tuples of pixels : I've been trying to solve this textbook question for a while but am a bit stuck.
Question:
We have provided a module image with a procedure file2image(filename)
that reads in an image stored in a file in the .png format. Import this procedure and invoke it,
providing as argument the name of a file containing an image in this format, assigning the returned
value to variable data
The value of data is a list of lists, and data[y][x] is the intensity of pixel (x,y). Pixel
(0,0) is at the bottom-left of the image, and pixel (width-1, height-1) is at the top-right.
The intensity of a pixel is a number between 0 (black) and 255 (white).
Use a comprehension to assign to a list pts the set of complex numbers x+yi such that the
image intensity of pixel (x, y) is less than 120.
Here is the relevant method that was provided
def file2image(path):
""" Reads an image into a list of lists of pixel values (tuples with
three values). This is a color image. """
(w, h, p, m) = png.Reader(filename = path).asRGBA() # force RGB and alpha
return [_flat2boxed(r) for r in p]
I'm really unsure how to parse the 3 values as a comprehension, anyone has a guess?
| 0debug
|
NOTE or WARNING from package check when README.md includes images : <p>I have a package with a <code>README.Rmd</code> that I pass to <code>rmarkdown::render()</code>
producing <code>README.md</code> and a directory <code>README_files</code>, which contains images in <code>README.md</code>. This looks like the tree below.</p>
<p><code>README_files</code> is <a href="https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Package-subdirectories" rel="noreferrer">not a standard package directory</a>, so if it isn't in <code>.Rbuildignore</code>, checking the package with <code>R CMD check</code> shows a note:</p>
<p><code>* checking top-level files ...
NOTE Non-standard file/directory found at top level: README_files</code></p>
<p>But including the directory in <code>.Rbuildignore</code> leads to a warning, if and only if checking the package <code>--as-cran</code>. IIUC Pandoc tries to generate HTML from <code>README.md</code>, but the images are unavailable, in the ignored <code>README_files</code> directory.</p>
<pre><code>Conversion of ‘README.md’ failed:
pandoc: Could not fetch README_files/unnamed-chunk-14-1.png
README_files/unnamed-chunk-14-1.png: openBinaryFile: does not exist (No such file or directory)
</code></pre>
<p>Is there any way to get a clean check <code>--as-cran</code> here?</p>
<p><code>
├── README_files
│ └── figure-markdown_github
│ ├── unnamed-chunk-14-1.png
│ ├── unnamed-chunk-15-1.png
│ ├── unnamed-chunk-16-1.png
│ ├── unnamed-chunk-26-1.png
│ └── unnamed-chunk-27-1.png
├── README.md
├── README.Rmd
</code></p>
| 0debug
|
static void usbredir_interrupt_packet(void *priv, uint32_t id,
struct usb_redir_interrupt_packet_header *interrupt_packet,
uint8_t *data, int data_len)
{
USBRedirDevice *dev = priv;
uint8_t ep = interrupt_packet->endpoint;
DPRINTF("interrupt-in status %d ep %02X len %d id %u\n",
interrupt_packet->status, ep, data_len, id);
if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_INT) {
ERROR("received int packet for non interrupt endpoint %02X\n", ep);
free(data);
return;
}
if (ep & USB_DIR_IN) {
if (dev->endpoint[EP2I(ep)].interrupt_started == 0) {
DPRINTF("received int packet while not started ep %02X\n", ep);
free(data);
return;
}
bufp_alloc(dev, data, data_len, interrupt_packet->status, ep);
} else {
int len = interrupt_packet->length;
AsyncURB *aurb = async_find(dev, id);
if (!aurb) {
return;
}
if (aurb->interrupt_packet.endpoint != interrupt_packet->endpoint) {
ERROR("return int packet mismatch, please report this!\n");
len = USB_RET_NAK;
}
if (aurb->packet) {
aurb->packet->result = usbredir_handle_status(dev,
interrupt_packet->status, len);
usb_packet_complete(&dev->dev, aurb->packet);
}
async_free(dev, aurb);
}
}
| 1threat
|
static int load_input_picture(MpegEncContext *s, AVFrame *pic_arg){
AVFrame *pic=NULL;
int64_t pts;
int i;
const int encoding_delay= s->max_b_frames;
int direct=1;
if(pic_arg){
pts= pic_arg->pts;
pic_arg->display_picture_number= s->input_picture_number++;
if(pts != AV_NOPTS_VALUE){
if(s->user_specified_pts != AV_NOPTS_VALUE){
int64_t time= pts;
int64_t last= s->user_specified_pts;
if(time <= last){
av_log(s->avctx, AV_LOG_ERROR, "Error, Invalid timestamp=%"PRId64", last=%"PRId64"\n", pts, s->user_specified_pts);
return -1;
}
}
s->user_specified_pts= pts;
}else{
if(s->user_specified_pts != AV_NOPTS_VALUE){
s->user_specified_pts=
pts= s->user_specified_pts + 1;
av_log(s->avctx, AV_LOG_INFO, "Warning: AVFrame.pts=? trying to guess (%"PRId64")\n", pts);
}else{
pts= pic_arg->display_picture_number;
}
}
}
if(pic_arg){
if(encoding_delay && !(s->flags&CODEC_FLAG_INPUT_PRESERVED)) direct=0;
if(pic_arg->linesize[0] != s->linesize) direct=0;
if(pic_arg->linesize[1] != s->uvlinesize) direct=0;
if(pic_arg->linesize[2] != s->uvlinesize) direct=0;
if(direct){
i= ff_find_unused_picture(s, 1);
pic= (AVFrame*)&s->picture[i];
pic->reference= 3;
for(i=0; i<4; i++){
pic->data[i]= pic_arg->data[i];
pic->linesize[i]= pic_arg->linesize[i];
}
ff_alloc_picture(s, (Picture*)pic, 1);
}else{
i= ff_find_unused_picture(s, 0);
pic= (AVFrame*)&s->picture[i];
pic->reference= 3;
ff_alloc_picture(s, (Picture*)pic, 0);
if( pic->data[0] + INPLACE_OFFSET == pic_arg->data[0]
&& pic->data[1] + INPLACE_OFFSET == pic_arg->data[1]
&& pic->data[2] + INPLACE_OFFSET == pic_arg->data[2]){
}else{
int h_chroma_shift, v_chroma_shift;
avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
for(i=0; i<3; i++){
int src_stride= pic_arg->linesize[i];
int dst_stride= i ? s->uvlinesize : s->linesize;
int h_shift= i ? h_chroma_shift : 0;
int v_shift= i ? v_chroma_shift : 0;
int w= s->width >>h_shift;
int h= s->height>>v_shift;
uint8_t *src= pic_arg->data[i];
uint8_t *dst= pic->data[i];
if(!s->avctx->rc_buffer_size)
dst +=INPLACE_OFFSET;
if(src_stride==dst_stride)
memcpy(dst, src, src_stride*h);
else{
while(h--){
memcpy(dst, src, w);
dst += dst_stride;
src += src_stride;
}
}
}
}
}
copy_picture_attributes(s, pic, pic_arg);
pic->pts= pts;
}
for(i=1; i<MAX_PICTURE_COUNT ; i++)
s->input_picture[i-1]= s->input_picture[i];
s->input_picture[encoding_delay]= (Picture*)pic;
return 0;
}
| 1threat
|
how can merge two Expression<Func<T, T> : i have two expression like this :
Expression<Func<T, T> exp1 = x => new T { Id = 1 , Name = "string"}
Expression<Func<T, T> exp1 = x => new T { Age = 21 }
how can merge them :
result :
Expression<Func<T, T> exp1 = x => new T { Id = 1 , Name = "string" , Age = 21}
| 0debug
|
static uint32_t nabm_readb (void *opaque, uint32_t addr)
{
PCIAC97LinkState *d = opaque;
AC97LinkState *s = &d->ac97;
AC97BusMasterRegs *r = NULL;
uint32_t index = addr - s->base[1];
uint32_t val = ~0U;
switch (index) {
case CAS:
dolog ("CAS %d\n", s->cas);
val = s->cas;
s->cas = 1;
break;
case PI_CIV:
case PO_CIV:
case MC_CIV:
r = &s->bm_regs[GET_BM (index)];
val = r->civ;
dolog ("CIV[%d] -> %#x\n", GET_BM (index), val);
break;
case PI_LVI:
case PO_LVI:
case MC_LVI:
r = &s->bm_regs[GET_BM (index)];
val = r->lvi;
dolog ("LVI[%d] -> %#x\n", GET_BM (index), val);
break;
case PI_PIV:
case PO_PIV:
case MC_PIV:
r = &s->bm_regs[GET_BM (index)];
val = r->piv;
dolog ("PIV[%d] -> %#x\n", GET_BM (index), val);
break;
case PI_CR:
case PO_CR:
case MC_CR:
r = &s->bm_regs[GET_BM (index)];
val = r->cr;
dolog ("CR[%d] -> %#x\n", GET_BM (index), val);
break;
case PI_SR:
case PO_SR:
case MC_SR:
r = &s->bm_regs[GET_BM (index)];
val = r->sr & 0xff;
dolog ("SRb[%d] -> %#x\n", GET_BM (index), val);
break;
default:
dolog ("U nabm readb %#x -> %#x\n", addr, val);
break;
}
return val;
}
| 1threat
|
What's difference between NSPhotoLibraryAddUsageDescription and NSPhotoLibraryUsageDescription? : <p>My app get crashed today while updating on Xcode9, testing on iOS11.
After adding <code>NSPhotoLibraryAddUsageDescription</code> then it works, even i already had <code>NSPhotoLibraryUsageDescription</code>.</p>
<p>Ive read about them, one supported since iOS6, one iOS11 but Apple didn't mention what's difference between them.
<a href="https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW73" rel="noreferrer">https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW73</a></p>
<p>If i keep the new one (<code>NSPhotoLibraryAddUsageDescription</code>), will it work for iOS 8 also or i have to keep both of them?</p>
| 0debug
|
static uint32_t phys_map_node_alloc(void)
{
unsigned i;
uint32_t ret;
ret = next_map.nodes_nb++;
assert(ret != PHYS_MAP_NODE_NIL);
assert(ret != next_map.nodes_nb_alloc);
for (i = 0; i < P_L2_SIZE; ++i) {
next_map.nodes[ret][i].skip = 1;
next_map.nodes[ret][i].ptr = PHYS_MAP_NODE_NIL;
}
return ret;
}
| 1threat
|
IntelliJ: activate Maven profile when running Junit tests : <p>I have declared some properties that are specific to Maven profiles. A part of my pom.xml:</p>
<pre><code><profiles>
<profile>
<id>release</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<my.properties.file>foo.xml</my.properties.file>
</properties>
</profile>
<profile>
<id>ci</id>
<properties>
<my.properties.file>bar.xml</my.properties.file>
</properties>
</profile>
</profiles>
</code></pre>
<p>I encounter some problem to use the "ci" Maven profile when I start Junit tests via IntelliJ IDEA 2016.<br>
I activate my profile via the "Maven Projects" panel, then I start tests. The problem is the "my.properties.file" property value is equal to "foo.xml", not "bar.xml".</p>
<p>I have no problem with command-line (I can use the "-Pci" flag). How can I tell IntelliJ to use the "ci" profile? Thx.</p>
| 0debug
|
int nbd_init(int fd, QIOChannelSocket *sioc, NBDExportInfo *info,
Error **errp)
{
unsigned long sectors = info->size / BDRV_SECTOR_SIZE;
if (info->size / BDRV_SECTOR_SIZE != sectors) {
error_setg(errp, "Export size %" PRIu64 " too large for 32-bit kernel",
info->size);
return -E2BIG;
}
trace_nbd_init_set_socket();
if (ioctl(fd, NBD_SET_SOCK, (unsigned long) sioc->fd) < 0) {
int serrno = errno;
error_setg(errp, "Failed to set NBD socket");
return -serrno;
}
trace_nbd_init_set_block_size(BDRV_SECTOR_SIZE);
if (ioctl(fd, NBD_SET_BLKSIZE, (unsigned long)BDRV_SECTOR_SIZE) < 0) {
int serrno = errno;
error_setg(errp, "Failed setting NBD block size");
return -serrno;
}
trace_nbd_init_set_size(sectors);
if (info->size % BDRV_SECTOR_SIZE) {
trace_nbd_init_trailing_bytes(info->size % BDRV_SECTOR_SIZE);
}
if (ioctl(fd, NBD_SET_SIZE_BLOCKS, sectors) < 0) {
int serrno = errno;
error_setg(errp, "Failed setting size (in blocks)");
return -serrno;
}
if (ioctl(fd, NBD_SET_FLAGS, (unsigned long) info->flags) < 0) {
if (errno == ENOTTY) {
int read_only = (info->flags & NBD_FLAG_READ_ONLY) != 0;
trace_nbd_init_set_readonly();
if (ioctl(fd, BLKROSET, (unsigned long) &read_only) < 0) {
int serrno = errno;
error_setg(errp, "Failed setting read-only attribute");
return -serrno;
}
} else {
int serrno = errno;
error_setg(errp, "Failed setting flags");
return -serrno;
}
}
trace_nbd_init_finish();
return 0;
}
| 1threat
|
Jenkins High CPU Usage Khugepageds : <p><a href="https://i.stack.imgur.com/MCvXn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MCvXn.png" alt="enter image description here"></a></p>
<p>So the picture above shows a command <code>khugepageds</code> that is using <code>98</code> to <code>100</code> <code>%</code> of CPU at times.</p>
<p>I tried finding how does <code>jenkins</code> use this command or what to do about it but was not successful. </p>
<p>I did the following </p>
<ul>
<li><code>pkill</code> jenkins </li>
<li>service jenkins stop</li>
<li>service jenkins start</li>
</ul>
<p>When i <code>pkill</code> ofcourse the usage goes down but once restart its back up again.</p>
<p>Anyone had this issue before?</p>
| 0debug
|
How to Display ajax responseText? : <p>Hi friends How do I get only the main message here is to show my j44?</p>
<pre><code>error: function (xhr, status, errorThrown) {
alert(xhr.responseText);
}
</code></pre>
<p><a href="https://i.stack.imgur.com/gxTid.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gxTid.jpg" alt="enter image description here"></a></p>
| 0debug
|
List that shows the students that study more than two subjects (I need this query) : TABLES IN SQL SERVER
create table Estudiante
(
id int primary key not null,
nombre varchar(50)
)
insert into Estudiante (id, nombre)
values
('1','Maria'),
('2','Juan'),
('3','Yarlin'),
('4','Ana'),
('5','Marcos'),
('6','Juana'),
('7','Esther'),
('8','Luisa')
create table Materia
(
id int primary key not null,
nombre varchar(50),
estado varchar(10)
)
insert into Materia (id, nombre, estado)
values
('1','Filosofía','activo'),
('2','Bases de datos','activo'),
('3','Programación','activo'),
('4','Literatura','activo'),
('5','Teología','activo')
create table MateriaProfesor
(
id int primary key not null,
idMateria int foreign key references Materia,
idProfesor int foreign key references Profesor
)
insert into MateriaProfesor (id, idMateria, idProfesor)
values
('11','2','1'),
('12','1','2'),
('13','2','1'),
('14','3','4'),
('15','4','3'),
('16','5','2')
create table MateriaEstudiante
(
id int primary key not null,
idMateria int foreign key references Materia(id),
idEstudiate int foreign key references Estudiante(id),
Fecha date
)
insert into MateriaEstudiante (id, idMateria, idEstudiate, Fecha)
values
('20','4','3','10/11/2017'),
('21','5','2','10/11/2017'),
('22','3','8','10/11/2017'),
('23','5','4','11/11/2017'),
('24','1','5','11/11/2017'),
('25','1','3','11/11/2017')
| 0debug
|
Video don`t open on browser of cell phone : (Using WordPress 4.7.3)
I have a video on my header background and it run normally on browse of desktop but when I open in browse of cell phone, the video disappear. I checked the medias queries in order to know if it is the problem, but apparently no.
Site URL: http://ratts.herokuapp.com/
Any idea what it is?
| 0debug
|
REST API Security Issues : <p>I have an html5 webapp that fetches data using jquery from rest java api. I have two questions:</p>
<ol>
<li>How can I encrypt data on server and decrypt it locally with different key for each user. Where can I store this key in client side? Does it needed, or it is just enough to secure the rest service call with some authentication method?</li>
<li>Is there any standard way to prevent other rest clients (except browsers) to hit this rest api?</li>
</ol>
| 0debug
|
Which Design pattern should i use to maintain pre initialized set of objects? : <p>I have some pre initialized objects of some class. These objects are heavy weight objects and each correspond to some configuration options specified by user. There will be exactly one instance corresponding to one configuration and same will be used every time.</p>
<p>My question is, which design pattern suits best to handle this kind of situation?</p>
| 0debug
|
String equals in andriod studio :
Was just wondering why I get "Cannot resolve symbol 'equals'" on the string.equals. Im using andriod studio.
public class Transaction {
String type;
double amount;
if(type.equals("Deposit"){
};
}
| 0debug
|
static ssize_t mcf_fec_receive(NetClientState *nc, const uint8_t *buf, size_t size)
{
mcf_fec_state *s = qemu_get_nic_opaque(nc);
mcf_fec_bd bd;
uint32_t flags = 0;
uint32_t addr;
uint32_t crc;
uint32_t buf_addr;
uint8_t *crc_ptr;
unsigned int buf_len;
size_t retsize;
DPRINTF("do_rx len %d\n", size);
if (!s->rx_enabled) {
return -1;
}
size += 4;
crc = cpu_to_be32(crc32(~0, buf, size));
crc_ptr = (uint8_t *)&crc;
if (size > FEC_MAX_FRAME_SIZE) {
size = FEC_MAX_FRAME_SIZE;
flags |= FEC_BD_TR | FEC_BD_LG;
}
if (size > (s->rcr >> 16)) {
flags |= FEC_BD_LG;
}
addr = s->rx_descriptor;
retsize = size;
while (size > 0) {
mcf_fec_read_bd(&bd, addr);
if ((bd.flags & FEC_BD_E) == 0) {
fprintf(stderr, "mcf_fec: Lost end of frame\n");
break;
}
buf_len = (size <= s->emrbr) ? size: s->emrbr;
bd.length = buf_len;
size -= buf_len;
DPRINTF("rx_bd %x length %d\n", addr, bd.length);
if (size < 4)
buf_len += size - 4;
buf_addr = bd.data;
cpu_physical_memory_write(buf_addr, buf, buf_len);
buf += buf_len;
if (size < 4) {
cpu_physical_memory_write(buf_addr + buf_len, crc_ptr, 4 - size);
crc_ptr += 4 - size;
}
bd.flags &= ~FEC_BD_E;
if (size == 0) {
bd.flags |= flags | FEC_BD_L;
DPRINTF("rx frame flags %04x\n", bd.flags);
s->eir |= FEC_INT_RXF;
} else {
s->eir |= FEC_INT_RXB;
}
mcf_fec_write_bd(&bd, addr);
if ((bd.flags & FEC_BD_W) != 0) {
addr = s->erdsr;
} else {
addr += 8;
}
}
s->rx_descriptor = addr;
mcf_fec_enable_rx(s);
mcf_fec_update(s);
return retsize;
}
| 1threat
|
Cloud connectivity for MQTT and AMQP? : <p>What is the difference between MQTT and AMQP in terms of cloud connectivity?
I need to compare these two protocols in terms of connecting to the cloud and I found more evidence that AMQP works better but I am still need to find out the differences.</p>
| 0debug
|
Doesn't exit after the "exit" command : <p>I'm programming and I'm having an issue.</p>
<pre><code>if exist savefile.climax (
echo It appears you have one...
echo Checking your data...
(
set /p name=
set /p level=
)<savefile.climax
) else (
echo Oh man, you don't have one.
echo Would you like to create it?
choice /c yn /n /m "[Y]es or [N]o?"
if %errorlevel% == 1 goto creation
if %errorlevel% == 2 exit
)
</code></pre>
<p>And as you can see, if the errorlevel is 2 the program should exit, but it doesn't. It keeps going on to the creation code. How could I fix this issue?</p>
| 0debug
|
IOException was unhandled C# : <pre><code>static void Main(string[] args)
{
File.Create("Script.txt");
execute();
Console.ReadKey();
}
static void execute()
{
if (File.Exists("Script.txt"))
{
string[] codex = System.IO.File.ReadAllLines("Script.txt");
foreach (string i in codex)
{
Console.WriteLine("{0} ", i);
}
}
else
{
Console.WriteLine("The path does not exists.");
}
}
</code></pre>
<p>I tried this code but I get this error.
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll</p>
| 0debug
|
Automatically use secret when pulling from private registry : <p>Is it possible to globally (or at least per namespace), configure kubernetes to always use an image pull secret when connecting to a private repo?
There are two use cases: </p>
<ol>
<li>when a user specifies a container in our private registry in a deployment</li>
<li>when a user points a Helm chart at our private repo (and so we have no control over the image pull secret tag).</li>
</ol>
<p>I know it is possible to do this on a <a href="https://kubernetes.io/docs/concepts/containers/images/#using-a-private-registry" rel="noreferrer">service account basis</a> but without writing a controller to add this to every new service account created it would get a bit of a mess.</p>
<p>Is there are way to set this globally so if kube tries to pull from registry X it uses secret Y?</p>
<p>Thanks</p>
| 0debug
|
Python Iteration Homework : <p>I have 2 questions I need to ask for help with. One question I don't entirely understand so if someone could help me to that would be great. </p>
<p>Question One (the one I don't entirely understand):</p>
<blockquote>
<p>One definition of e is</p>
</blockquote>
<p><a href="http://i.stack.imgur.com/DAd4A.png" rel="nofollow">Formula for e</a></p>
<blockquote>
<p>This can be calculated as my_e = 1/math.factorial(0) + 1/math.factorial(1) + 1/math.factorial(2) + 1/math.factorial(3) + …</p>
<p>Let n be the input number of the math.factorial() function. n successively takes on 0, 1, 2, 3 and so on. Find the smallest n such that the absolute value of (my_e – math.e) is less than or equal to 10-10. That is, abs(my_e - math.e) <= (10 ** -10).</p>
</blockquote>
<p>I just don't entirely understand what I am being asked to do. Clarification would be great. Thanks!</p>
<p>Question 2:</p>
<blockquote>
<p>Ask the user to type in a series of integers. Sum them up and print out the sum and the number of integers the user has entered.</p>
</blockquote>
<p><a href="http://i.stack.imgur.com/MDzXx.png" rel="nofollow">My code</a></p>
<p>So what should happen is after I enter the numbers I want to enter and hit the enter key, it should calculate and print out "sum = 25 count = 3". The screenshot shows what error message I am getting.</p>
<p>Any help you have is welcomed and greatly appreciated.</p>
| 0debug
|
Ruby on rails toggling favourite button using jquery and ajax comes with "rendering head :no_content Completed 204 No Content' : I am trying to create a favourite button where users will be able to use toggle button to 'favourite' a post and 'unfavourite' same depending on what they like. So far if I 'unfavourite' the post it seems to work but whenever i do otherwise the link does not change. I used jquery and ajax.
class FavouritesController < ApplicationController
before_action :authenticate_user!
def create
@favourite = current_user.favourites.build(favourite_params)
if @favourite.save
@post = @favourite.post
respond_to :js
else
flash[:alert] = "something went wrong..."
end
end
def destroy
@favourite = Favourite.find(params[:id])
@school = @favourite.post
if @favourite.destroy
respond_to :js
else
flash[:alert] = "Something Went Wrong..."
end
end
private
def favourite_params
params.permit :user_id, :post_id
end
end
HERE ARE THE MODELS
class Post < ApplicationRecord
belongs_to :user
has_many :favourites
def is_favourited user
Favourite.find_by(user_id: user.id, school_id: id)
end
end
FAVOURITE MODEL
class Favourite < ApplicationRecord
belongs_to :user
belongs_to :post
end
CREATED J.S IN THE FAVOURITE VIEW FOLDER IE VIEWS/FAVOURITES/created.js.erb
$('#favourite').html('<%= j render "posts/favourite", {is_favourited:
@is_favourited, post: @post} %>');
console.log("Added to your favourite List");
CREATED J.S IN THE FAVOURITE VIEW FOLDER IE VIEWS/FAVOURITES/destroy.js.erb
/destroy.js.erb
$('#favourite').html('<%= j render "posts/favourite", {is_favourited:
@is_favourited, post: @post} %>');
console.log("Added to your favourite List");
FAVOURITE PARTIAL FILE IN THE POSTS FOLDER IE VIEWS/POSTS/_favourite.html.erb
<% if @is_favourited.present? %>
<%= link_to "favourited", favourite_path(@is_favourited), method: :delete, remote: true, id: 'favourited' %>
<% else %>
<%= link_to "favourite", post_favourites_path(@post), method: :post, remote: true, id: 'favourite' %>
<% end %>
ON THE SHOW PAGE OF THE POST I RENDERED THE PARTIAL LIKE THIS
<%= render 'favourite' %>
| 0debug
|
static void icp_set_cppr(struct icp_state *icp, int server, uint8_t cppr)
{
struct icp_server_state *ss = icp->ss + server;
uint8_t old_cppr;
uint32_t old_xisr;
old_cppr = CPPR(ss);
ss->xirr = (ss->xirr & ~CPPR_MASK) | (cppr << 24);
if (cppr < old_cppr) {
if (XISR(ss) && (cppr <= ss->pending_priority)) {
old_xisr = XISR(ss);
ss->xirr &= ~XISR_MASK;
qemu_irq_lower(ss->output);
ics_reject(icp->ics, old_xisr);
}
} else {
if (!XISR(ss)) {
icp_resend(icp, server);
}
}
}
| 1threat
|
static void hevc_await_progress(HEVCContext *s, HEVCFrame *ref,
const Mv *mv, int y0, int height)
{
int y = FFMAX(0, (mv->y >> 2) + y0 + height + 9);
if (s->threads_type == FF_THREAD_FRAME )
ff_thread_await_progress(&ref->tf, y, 0);
}
| 1threat
|
3 x 3 cell with large center layout with flexbox simple implementation ideas needed : <p>With CSS Grid, it's pretty easy to implement something like this <a href="https://codepen.io/anon/pen/VOLPRV" rel="nofollow noreferrer">3 x 3 cell with large center with css grid</a></p>
<pre><code>.container {
display: grid;
grid-template-columns: 60px 1fr 60px;
grid-template-rows: 60px 1fr 60px;
}
</code></pre>
<p>Is there a simple way to implement this using flexbox?</p>
<p><a href="https://codepen.io/anon/pen/WBvRWr" rel="nofollow noreferrer">simple flexbox implementation?</a></p>
| 0debug
|
static int pci_pbm_init_device(SysBusDevice *dev)
{
APBState *s;
int pci_mem_config, pci_mem_data, apb_config, pci_ioport;
s = FROM_SYSBUS(APBState, dev);
apb_config = cpu_register_io_memory(apb_config_read,
apb_config_write, s);
sysbus_init_mmio(dev, 0x40ULL, apb_config);
pci_ioport = cpu_register_io_memory(pci_apb_ioread,
pci_apb_iowrite, s);
sysbus_init_mmio(dev, 0x10000ULL, pci_ioport);
pci_mem_config = cpu_register_io_memory(pci_apb_config_read,
pci_apb_config_write, s);
sysbus_init_mmio(dev, 0x10ULL, pci_mem_config);
pci_mem_data = cpu_register_io_memory(pci_apb_read,
pci_apb_write, &s->host_state);
sysbus_init_mmio(dev, 0x10000000ULL, pci_mem_data);
return 0;
}
| 1threat
|
Java - SQL - Getting everything from the database and outputting it : <p>I'm trying to get everything I have in my database <em>(see below for a picture of it)</em> and output it out the the user.</p>
<p><a href="http://i.stack.imgur.com/G6PmK.png" rel="nofollow">PICTURE OF HOW MY DATABASE LOOKS!</a></p>
<h2>For example:</h2>
<p>ID: 1
Name: bob
Area: 1
Date: 3/11
Message: hi</p>
<p>ID: 2
Name: larry
Area: 3
Date: 6/9
Message: hello</p>
<p>etc.</p>
<p>Any ideas?</p>
<p>Thanks!</p>
| 0debug
|
Need a parameter based 'Ranking Algorithm' like University ranking : <p><strong>I need a ranking algorithm which is recognized and generally accepted.</strong>
I am trying to develop a simple algorithm to rating Doctor for my thesis paper. My algorithm is work with different parameter/criteria like patient review, he/her qualification, research paper and some other quality of doctor. Finally based on those parameter/criteria rate the doctor. Where I used Bayesian method, Normalization and other calculation. For this i need a similar algorithm to comparison with my algorithm and also can correction my algorithm.<br>
I search for long time but unfortunately i don't find any similar algorithm.
So i badly need help of your to find the perfect algorithm.<br>
Thanks in advance.</p>
| 0debug
|
Is it possible to restrict typescript object to contain only properties defined by its class ? : <p>Here is my code</p>
<pre><code>async getAll(): Promise<GetAllUserData[]> {
return await dbQuery(); // dbQuery returns User[]
}
class User {
id: number;
name: string;
}
class GetAllUserData{
id: number;
}
</code></pre>
<p><code>getAll</code> function returns <code>User[]</code>, and each element of array has the <code>name</code> property, event if it's return type is <code>GetAllUserData[]</code>.</p>
<p>I want to know if it is possible <code>out of the box</code> in typescript to restrict an object only to properties specified by it's type.</p>
| 0debug
|
void ppc_store_sr (CPUPPCState *env, int srnum, target_ulong value)
{
LOG_MMU("%s: reg=%d " TARGET_FMT_lx " " TARGET_FMT_lx "\n", __func__,
srnum, value, env->sr[srnum]);
#if defined(TARGET_PPC64)
if (env->mmu_model & POWERPC_MMU_64) {
uint64_t rb = 0, rs = 0;
rb |= ((uint32_t)srnum & 0xf) << 28;
rb |= 1 << 27;
rb |= (uint32_t)srnum;
rs |= (value & 0xfffffff) << 12;
rs |= ((value >> 27) & 0xf) << 9;
ppc_store_slb(env, rb, rs);
} else
#endif
if (env->sr[srnum] != value) {
env->sr[srnum] = value;
#if !defined(FLUSH_ALL_TLBS) && 0
{
target_ulong page, end;
page = (16 << 20) * srnum;
end = page + (16 << 20);
for (; page != end; page += TARGET_PAGE_SIZE)
tlb_flush_page(env, page);
}
#else
tlb_flush(env, 1);
#endif
}
}
| 1threat
|
How to try Android development as an older programmer in 2020? : <p>Given a person who has been programming for embedded industrial systems for a few decades now. </p>
<p><strong>How can I make it easy for an older programmer to try mobile development (Android)?</strong></p>
<p>I’m asking because the amount of information on Android development is so overwhelming, and so much of it has been obsolete, I don’t even know where to begin. Would that person start with Eclipse or Android Studio? Plain Java or Kotlin? </p>
<p><strong>In other words</strong>, what is the quickest way to get an Android IDE set up to print “hello world” on a real device in 2020?</p>
| 0debug
|
Is it possible to PASTE image into Jupyter Notebook? : <p>It is possible to include images in Jupyter notebook with various markup.</p>
<p>But is it possible to AUTOMATE this? I.e. I have image in clipboard, then I just press <code>Ctrl-V</code> and Jupyter server automatically takes this image, creates file in appropriate place and inserts markup for it.</p>
<p>I saw such things in Stackoverflow and JIRA.</p>
| 0debug
|
map.end() error "iterator not dereferenceable" c++ : <pre><code>//Works
cout << "map[0] value is " << doubleStatsMap.begin()->first<< endl;
//gives error
cout << "map[last value is " << doubleStatsMap.end()->first << endl;
</code></pre>
<p>Im simply trying to get the value of the last element of my map. It works correctly with
"map.begin->first"
but is giving "map/set iterator not dereferencable" for the
"map.end()->first".
It cant be empty as the map has a beginning thus it has an end. Everything I've read says this should work. Any suggestions greatly appreciated!</p>
| 0debug
|
UI design - simple struct - how to implement : <p>How can I create the next (and simple) structure?
Is it just a tableView? or is it require assets ?
(I'm asking about the squares only, not about the text and icon at each row)
<a href="https://i.stack.imgur.com/O9vKf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O9vKf.png" alt="rounded square with 3 rows"></a></p>
| 0debug
|
How to debug java source code when I implement a custom Detector for Lint? : <p>I am a Android developer.
I have already design my own lint rules by implementing new XXXDetector and XXXIssueRegistry, here is my source code snip:</p>
<p>My XXXIssueRegistry file:</p>
<pre><code>public class MyIssueRegistry extends IssueRegistry {
@Override
public List<Issue> getIssues() {
System.out.println("!!!!!!!!!!!!! ljf MyIssueRegistry lint rules works");
return Arrays.asList(AttrPrefixDetector.ISSUE,
LoggerUsageDetector.ISSUE);
}
}
</code></pre>
<p>My XXXDetector file:</p>
<pre><code>public class LoggerUsageDetector extends Detector
implements Detector.ClassScanner {
public static final Issue ISSUE = Issue.create("LogUtilsNotUsed",
"You must use our `LogUtils`",
"Logging should be avoided in production for security and performance reasons. Therefore, we created a LogUtils that wraps all our calls to Logger and disable them for release flavor.",
Category.MESSAGES,
9,
Severity.ERROR,
new Implementation(LoggerUsageDetector.class,
Scope.CLASS_FILE_SCOPE));
@Override
public List<String> getApplicableCallNames() {
return Arrays.asList("v", "d", "i", "w", "e", "wtf");
}
@Override
public List<String> getApplicableMethodNames() {
return Arrays.asList("v", "d", "i", "w", "e", "wtf");
}
@Override
public void checkCall(@NonNull ClassContext context,
@NonNull ClassNode classNode,
@NonNull MethodNode method,
@NonNull MethodInsnNode call) {
String owner = call.owner;
if (owner.startsWith("android/util/Log")) {
context.report(ISSUE,
method,
call,
context.getLocation(call),
"You must use our `LogUtils`");
}
}
}
</code></pre>
<p>Now I can run my custom lint rules by runnig command:</p>
<pre><code>$gradle lint
</code></pre>
<p>And I will get output message like I expected in console.</p>
<p>But I want to debug my XXXDetector source file. How can I do that?
If I click "debug" or "run" or "build" , my custom lint rules will NOT run! So I have to run it in console, which don't support debug.
How can I solve this?</p>
| 0debug
|
static int av_encode(AVFormatContext **output_files,
int nb_output_files,
AVFormatContext **input_files,
int nb_input_files,
AVStreamMap *stream_maps, int nb_stream_maps)
{
int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
AVFormatContext *is, *os;
AVCodecContext *codec, *icodec;
AVOutputStream *ost, **ost_table = NULL;
AVInputStream *ist, **ist_table = NULL;
AVInputFile *file_table;
AVFormatContext *stream_no_data;
int key;
file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
if (!file_table)
goto fail;
j = 0;
for(i=0;i<nb_input_files;i++) {
is = input_files[i];
file_table[i].ist_index = j;
file_table[i].nb_streams = is->nb_streams;
j += is->nb_streams;
}
nb_istreams = j;
ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
if (!ist_table)
goto fail;
for(i=0;i<nb_istreams;i++) {
ist = av_mallocz(sizeof(AVInputStream));
if (!ist)
goto fail;
ist_table[i] = ist;
}
j = 0;
for(i=0;i<nb_input_files;i++) {
is = input_files[i];
for(k=0;k<is->nb_streams;k++) {
ist = ist_table[j++];
ist->st = is->streams[k];
ist->file_index = i;
ist->index = k;
ist->discard = 1;
if (ist->st->codec.rate_emu) {
ist->start = av_gettime();
ist->frame = 0;
}
}
}
nb_ostreams = 0;
for(i=0;i<nb_output_files;i++) {
os = output_files[i];
nb_ostreams += os->nb_streams;
}
if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
fprintf(stderr, "Number of stream maps must match number of output streams\n");
exit(1);
}
for(i=0;i<nb_stream_maps;i++) {
int fi = stream_maps[i].file_index;
int si = stream_maps[i].stream_index;
if (fi < 0 || fi > nb_input_files - 1 ||
si < 0 || si > file_table[fi].nb_streams - 1) {
fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
exit(1);
}
}
ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
if (!ost_table)
goto fail;
for(i=0;i<nb_ostreams;i++) {
ost = av_mallocz(sizeof(AVOutputStream));
if (!ost)
goto fail;
ost_table[i] = ost;
}
n = 0;
for(k=0;k<nb_output_files;k++) {
os = output_files[k];
for(i=0;i<os->nb_streams;i++) {
int found;
ost = ost_table[n++];
ost->file_index = k;
ost->index = i;
ost->st = os->streams[i];
if (nb_stream_maps > 0) {
ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
stream_maps[n-1].stream_index;
if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {
fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
ost->file_index, ost->index);
exit(1);
}
} else {
found = 0;
for(j=0;j<nb_istreams;j++) {
ist = ist_table[j];
if (ist->discard &&
ist->st->codec.codec_type == ost->st->codec.codec_type) {
ost->source_index = j;
found = 1;
}
}
if (!found) {
for(j=0;j<nb_istreams;j++) {
ist = ist_table[j];
if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
ost->source_index = j;
found = 1;
}
}
if (!found) {
fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
ost->file_index, ost->index);
exit(1);
}
}
}
ist = ist_table[ost->source_index];
ist->discard = 0;
}
}
for(i=0;i<nb_ostreams;i++) {
ost = ost_table[i];
ist = ist_table[ost->source_index];
codec = &ost->st->codec;
icodec = &ist->st->codec;
if (ost->st->stream_copy) {
codec->codec_id = icodec->codec_id;
codec->codec_type = icodec->codec_type;
codec->codec_tag = icodec->codec_tag;
codec->bit_rate = icodec->bit_rate;
switch(codec->codec_type) {
case CODEC_TYPE_AUDIO:
codec->sample_rate = icodec->sample_rate;
codec->channels = icodec->channels;
break;
case CODEC_TYPE_VIDEO:
codec->frame_rate = icodec->frame_rate;
codec->frame_rate_base = icodec->frame_rate_base;
codec->width = icodec->width;
codec->height = icodec->height;
break;
default:
av_abort();
}
} else {
switch(codec->codec_type) {
case CODEC_TYPE_AUDIO:
if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
goto fail;
if (codec->channels == icodec->channels &&
codec->sample_rate == icodec->sample_rate) {
ost->audio_resample = 0;
} else {
if (codec->channels != icodec->channels &&
icodec->codec_id == CODEC_ID_AC3) {
icodec->channels = codec->channels;
if (codec->sample_rate == icodec->sample_rate)
ost->audio_resample = 0;
else {
ost->audio_resample = 1;
ost->resample = audio_resample_init(codec->channels, icodec->channels,
codec->sample_rate,
icodec->sample_rate);
if(!ost->resample)
{
printf("Can't resample. Aborting.\n");
av_abort();
}
}
icodec->channels = codec->channels;
} else {
ost->audio_resample = 1;
ost->resample = audio_resample_init(codec->channels, icodec->channels,
codec->sample_rate,
icodec->sample_rate);
if(!ost->resample)
{
printf("Can't resample. Aborting.\n");
av_abort();
}
}
}
ist->decoding_needed = 1;
ost->encoding_needed = 1;
break;
case CODEC_TYPE_VIDEO:
if (codec->width == icodec->width &&
codec->height == icodec->height &&
frame_topBand == 0 &&
frame_bottomBand == 0 &&
frame_leftBand == 0 &&
frame_rightBand == 0)
{
ost->video_resample = 0;
ost->video_crop = 0;
} else if ((codec->width == icodec->width -
(frame_leftBand + frame_rightBand)) &&
(codec->height == icodec->height -
(frame_topBand + frame_bottomBand)))
{
ost->video_resample = 0;
ost->video_crop = 1;
ost->topBand = frame_topBand;
ost->leftBand = frame_leftBand;
} else {
ost->video_resample = 1;
ost->video_crop = 0;
if( avpicture_alloc( &ost->pict_tmp, PIX_FMT_YUV420P,
codec->width, codec->height ) )
goto fail;
ost->img_resample_ctx = img_resample_full_init(
ost->st->codec.width, ost->st->codec.height,
ist->st->codec.width, ist->st->codec.height,
frame_topBand, frame_bottomBand,
frame_leftBand, frame_rightBand);
}
ost->encoding_needed = 1;
ist->decoding_needed = 1;
break;
default:
av_abort();
}
if (ost->encoding_needed &&
(codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
char logfilename[1024];
FILE *f;
int size;
char *logbuffer;
snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
pass_logfilename ?
pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
if (codec->flags & CODEC_FLAG_PASS1) {
f = fopen(logfilename, "w");
if (!f) {
perror(logfilename);
exit(1);
}
ost->logfile = f;
} else {
f = fopen(logfilename, "r");
if (!f) {
perror(logfilename);
exit(1);
}
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
logbuffer = av_malloc(size + 1);
if (!logbuffer) {
fprintf(stderr, "Could not allocate log buffer\n");
exit(1);
}
size = fread(logbuffer, 1, size, f);
fclose(f);
logbuffer[size] = '\0';
codec->stats_in = logbuffer;
}
}
}
}
for(i=0;i<nb_output_files;i++) {
dump_format(output_files[i], i, output_files[i]->filename, 1);
}
fprintf(stderr, "Stream mapping:\n");
for(i=0;i<nb_ostreams;i++) {
ost = ost_table[i];
fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
ist_table[ost->source_index]->file_index,
ist_table[ost->source_index]->index,
ost->file_index,
ost->index);
}
for(i=0;i<nb_ostreams;i++) {
ost = ost_table[i];
if (ost->encoding_needed) {
AVCodec *codec;
codec = avcodec_find_encoder(ost->st->codec.codec_id);
if (!codec) {
fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
ost->file_index, ost->index);
exit(1);
}
if (avcodec_open(&ost->st->codec, codec) < 0) {
fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
ost->file_index, ost->index);
exit(1);
}
}
}
for(i=0;i<nb_istreams;i++) {
ist = ist_table[i];
if (ist->decoding_needed) {
AVCodec *codec;
codec = avcodec_find_decoder(ist->st->codec.codec_id);
if (!codec) {
fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
ist->st->codec.codec_id, ist->file_index, ist->index);
exit(1);
}
if (avcodec_open(&ist->st->codec, codec) < 0) {
fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
ist->file_index, ist->index);
exit(1);
}
}
}
for(i=0;i<nb_istreams;i++) {
ist = ist_table[i];
is = input_files[ist->file_index];
ist->pts = 0;
ist->next_pts = 0;
}
for(i=0;i<nb_input_files;i++) {
file_table[i].buffer_size_max = 2048;
}
for(i=0;i<nb_output_files;i++) {
os = output_files[i];
if (av_write_header(os) < 0) {
fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
ret = -EINVAL;
goto fail;
}
}
#ifndef CONFIG_WIN32
if ( !using_stdin )
fprintf(stderr, "Press [q] to stop encoding\n");
#endif
term_init();
stream_no_data = 0;
key = -1;
for(; received_sigterm == 0;) {
int file_index, ist_index;
AVPacket pkt;
double pts_min;
redo:
if (!using_stdin) {
key = read_key();
if (key == 'q')
break;
}
file_index = -1;
pts_min = 1e10;
for(i=0;i<nb_ostreams;i++) {
double pts;
ost = ost_table[i];
os = output_files[ost->file_index];
ist = ist_table[ost->source_index];
pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
if (!file_table[ist->file_index].eof_reached &&
pts < pts_min) {
pts_min = pts;
file_index = ist->file_index;
}
}
if (file_index < 0) {
break;
}
if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
break;
is = input_files[file_index];
if (av_read_frame(is, &pkt) < 0) {
file_table[file_index].eof_reached = 1;
continue;
}
if (!pkt.size) {
stream_no_data = is;
} else {
stream_no_data = 0;
}
if (do_pkt_dump) {
av_pkt_dump(stdout, &pkt, do_hex_dump);
}
if (pkt.stream_index >= file_table[file_index].nb_streams)
goto discard_packet;
ist_index = file_table[file_index].ist_index + pkt.stream_index;
ist = ist_table[ist_index];
if (ist->discard)
goto discard_packet;
if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
fprintf(stderr, "Error while decoding stream #%d.%d\n",
ist->file_index, ist->index);
av_free_packet(&pkt);
goto redo;
}
discard_packet:
av_free_packet(&pkt);
print_report(output_files, ost_table, nb_ostreams, 0);
}
for(i=0;i<nb_istreams;i++) {
ist = ist_table[i];
if (ist->decoding_needed) {
output_packet(ist, i, ost_table, nb_ostreams, NULL);
}
}
term_exit();
print_report(output_files, ost_table, nb_ostreams, 1);
for(i=0;i<nb_output_files;i++) {
os = output_files[i];
av_write_trailer(os);
}
for(i=0;i<nb_ostreams;i++) {
ost = ost_table[i];
if (ost->encoding_needed) {
av_freep(&ost->st->codec.stats_in);
avcodec_close(&ost->st->codec);
}
}
for(i=0;i<nb_istreams;i++) {
ist = ist_table[i];
if (ist->decoding_needed) {
avcodec_close(&ist->st->codec);
}
}
ret = 0;
fail1:
av_free(file_table);
if (ist_table) {
for(i=0;i<nb_istreams;i++) {
ist = ist_table[i];
av_free(ist);
}
av_free(ist_table);
}
if (ost_table) {
for(i=0;i<nb_ostreams;i++) {
ost = ost_table[i];
if (ost) {
if (ost->logfile) {
fclose(ost->logfile);
ost->logfile = NULL;
}
fifo_free(&ost->fifo);
av_free(ost->pict_tmp.data[0]);
if (ost->video_resample)
img_resample_close(ost->img_resample_ctx);
if (ost->audio_resample)
audio_resample_close(ost->resample);
av_free(ost);
}
}
av_free(ost_table);
}
return ret;
fail:
ret = -ENOMEM;
goto fail1;
}
| 1threat
|
static void prop_get_fdt(Object *obj, Visitor *v, const char *name,
void *opaque, Error **errp)
{
sPAPRDRConnector *drc = SPAPR_DR_CONNECTOR(obj);
Error *err = NULL;
int fdt_offset_next, fdt_offset, fdt_depth;
void *fdt;
if (!drc->fdt) {
visit_type_null(v, NULL, errp);
return;
}
fdt = drc->fdt;
fdt_offset = drc->fdt_start_offset;
fdt_depth = 0;
do {
const char *name = NULL;
const struct fdt_property *prop = NULL;
int prop_len = 0, name_len = 0;
uint32_t tag;
tag = fdt_next_tag(fdt, fdt_offset, &fdt_offset_next);
switch (tag) {
case FDT_BEGIN_NODE:
fdt_depth++;
name = fdt_get_name(fdt, fdt_offset, &name_len);
visit_start_struct(v, name, NULL, 0, &err);
if (err) {
error_propagate(errp, err);
return;
}
break;
case FDT_END_NODE:
g_assert(fdt_depth > 0);
visit_check_struct(v, &err);
visit_end_struct(v);
if (err) {
error_propagate(errp, err);
return;
}
fdt_depth--;
break;
case FDT_PROP: {
int i;
prop = fdt_get_property_by_offset(fdt, fdt_offset, &prop_len);
name = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
visit_start_list(v, name, &err);
if (err) {
error_propagate(errp, err);
return;
}
for (i = 0; i < prop_len; i++) {
visit_type_uint8(v, NULL, (uint8_t *)&prop->data[i], &err);
if (err) {
error_propagate(errp, err);
return;
}
}
visit_end_list(v);
break;
}
default:
error_setg(&error_abort, "device FDT in unexpected state: %d", tag);
}
fdt_offset = fdt_offset_next;
} while (fdt_depth != 0);
}
| 1threat
|
static int dfa_probe(AVProbeData *p)
{
if (p->buf_size < 4 || AV_RL32(p->buf) != MKTAG('D', 'F', 'I', 'A'))
return 0;
return AVPROBE_SCORE_MAX;
}
| 1threat
|
LDAP queries using UWP on Windows 10 IoT : <p>After several hours of searching it appears that there is no way to query a local LDAP directory (Microsoft Active Directory or otherwise) from a UWP app.</p>
<p>This seems like a rather bizarre hole in the UWP offering, and so I'm hopeful that I'm just missing the obvious.</p>
<p>What (if anything) is the functional equivalent of System.DirectoryServices in the Universal Windows Platform world?</p>
| 0debug
|
Right to Left in react-native : <p>By using this code(in below),The App has been RTL but location of Right & Left changed(So things must be shown in Right are turned to Left).I did it via <a href="https://facebook.github.io/react-native/blog/2016/08/19/right-to-left-support-for-react-native-apps.html" rel="noreferrer">tutorial</a>.</p>
<pre><code>ReactNative.I18nManager.allowRTL(true);
</code></pre>
<p>And another problem is when Mobile's language is LTR, Location of Images & designs turns into another side(for e.g changes from Right to Left) because App has only one LTR language. Is there any way for showing RTL & LTR like each other??</p>
| 0debug
|
Why the Loaded event of UserControl has not called, while making the UserControl visible dynamically from collapsed state : <p>I am having an usercontrol.Intially i am collapsing the visibilty of that control.Once I make the control visible , the loaded event of the control is not getting called</p>
| 0debug
|
Angular 1.x/2 Hybrid, karma tests not bootstrapping ng1 app : <p>I currently have a Hybrid Angular app (2.4.9 and 1.5.0) using angular-cli. Currently, when running our application, we are able to bootstrap the 1.5 app correctly:</p>
<pre class="lang-js prettyprint-override"><code>// main.ts
import ...
platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
angular.element(document).ready(() => {
const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document.body, ['myApp'], {strictDi: true});
});
});
</code></pre>
<p>However, in our <code>test.ts</code> file:</p>
<pre class="lang-js prettyprint-override"><code>// test.ts
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import ...;
declare var __karma__: any;
declare var require: any;
__karma__.loaded = function () {};
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
// I'm assuming that I need to call 'boostrapModule()' somehow here...
platformBrowserDynamicTesting()
);
const context = require.context('./', true, /\.spec\.ts$/);
context.keys().map(context);
__karma__.start();
</code></pre>
<p>I'm not exactly sure how to bootstrap our 1.5 application into the test environment, all I've gotten is <code>Module 'myApp' is not available!</code>, and my Google skills have failed trying to find an example.</p>
| 0debug
|
Python - merge sub lists that match certain pattern in another list? : <p>Don't know how to name such pattern, but by examples I think it is easier to explain.</p>
<p>For example let say I have this list:</p>
<pre><code>lst = [1, 2, 3, 5, 6, 7, 8, 10, 11, 15]
</code></pre>
<p>So Now I need to merge part of list that goes by increment of one (meaning only first and last items ar kept), but if there only two items in such increment, there is nothing to merge, because they are both first and last items of such pattern.</p>
<p>So by running some method that handles this, it should separate it in this:</p>
<pre><code>merged = [(1, 3), (5, 8)]
original = [10, 11, 15]
</code></pre>
<p>Note on original list. It has those three items only, because <code>2</code>, <code>6</code> and <code>7</code> are merged (they match that pattern). <code>10</code> and <code>11</code> goes by one increment, but there are only two numbers, so there is nothing to merge. And <code>15</code> does not match any pattern at all.</p>
<p>I thought of using some comparison of first and second items on iteration, but algorithm got complicated and I was not able to properly merge/detach those items.</p>
<p>P.S.</p>
<p>And the reason for this is I have a module that generates excel reports. And it is possible to specify formulas how some rows need to be computed (on excel side).</p>
<p>Now current functionality returns specific (when separate part of sheet are used in one formula) rows numbers. So for example formula could end up something like: <code>"sum(A1, A2, A3, A5)"</code>. And if there lots of rows, actual expression could become very big. But if I could simplify it by having that same formula for exmaple <code>"sum(A1:A3, A5)"</code> it would not be so big.</p>
| 0debug
|
static int hpet_init(SysBusDevice *dev)
{
HPETState *s = FROM_SYSBUS(HPETState, dev);
int i, iomemtype;
HPETTimer *timer;
if (hpet_cfg.count == UINT8_MAX) {
hpet_cfg.count = 0;
}
if (hpet_cfg.count == 8) {
fprintf(stderr, "Only 8 instances of HPET is allowed\n");
return -1;
}
s->hpet_id = hpet_cfg.count++;
for (i = 0; i < HPET_NUM_IRQ_ROUTES; i++) {
sysbus_init_irq(dev, &s->irqs[i]);
}
if (s->num_timers < HPET_MIN_TIMERS) {
s->num_timers = HPET_MIN_TIMERS;
} else if (s->num_timers > HPET_MAX_TIMERS) {
s->num_timers = HPET_MAX_TIMERS;
}
for (i = 0; i < HPET_MAX_TIMERS; i++) {
timer = &s->timer[i];
timer->qemu_timer = qemu_new_timer(vm_clock, hpet_timer, timer);
timer->tn = i;
timer->state = s;
}
s->capability = 0x8086a001ULL;
s->capability |= (s->num_timers - 1) << HPET_ID_NUM_TIM_SHIFT;
s->capability |= ((HPET_CLK_PERIOD) << 32);
isa_reserve_irq(RTC_ISA_IRQ);
qdev_init_gpio_in(&dev->qdev, hpet_handle_rtc_irq, 1);
iomemtype = cpu_register_io_memory(hpet_ram_read,
hpet_ram_write, s,
DEVICE_NATIVE_ENDIAN);
sysbus_init_mmio(dev, 0x400, iomemtype);
return 0;
}
| 1threat
|
What is the max number of rows one should pull at once from a database? : <p>I have a process that iterates through thousands of database tables and aggregates data, and I want to set a threshold limit <code>N</code> where if the row count is larger than N my process will dump the data to a file.</p>
<p>I'm wondering what would be a good limit for N?</p>
| 0debug
|
static av_cold void alloc_temp(HYuvContext *s)
{
int i;
if (s->bitstream_bpp<24) {
for (i=0; i<3; i++) {
s->temp[i]= av_malloc(s->width + 16);
}
} else {
s->temp[0]= av_mallocz(4*s->width + 16);
}
}
| 1threat
|
Finding an object in array and taking values from that to present in a select list : <p>I have a string value (e.g. "Table 1") that I need to use to find a specific object in an array that looks like so:</p>
<pre><code>[
{
lookups: [],
rows: [{data: {a: 1, b: 2}}, {data: {a: 3, b: 4}}],
title: "Table 1",
columns: [{name: "a"}, {name: "b"}]
},
{
lookups: [],
rows: [{data: {c: 5, d: 6}}, {data: {c: 7, d: 8}}],
title: "Table 2",
columns: [{name: "c"}, {name: "d"}]
}
]
</code></pre>
<p>Once I have found that object I then need to take the values from the columns key and display them in a select list.</p>
<p>I know how to do the second part, but it is getting access to the object in the first place that I am having trouble with. I am trying to do this within a React component render.</p>
<p>Any help with this would be greatly appreciated.</p>
<p>Thanks for your time.</p>
| 0debug
|
adding firebase to flutter project and getting FAILURE: Build failed with an exception error : <p>for [this flutter library][1] as <code>barcode scanner</code> i should to adding <code>firebase</code> to project, but after doing that i get this error and i cant fix that yet</p>
<blockquote>
<p>Launching lib\main.dart on WAS LX1A in debug mode... Initializing
gradle... Resolving dependencies...
* Error running Gradle: ProcessException: Process "E:\Projects\Flutter\barcode_scanner\android\gradlew.bat" exited
abnormally:</p>
<p>FAILURE: Build failed with an exception.</p>
<ul>
<li><p>Where: Build file 'E:\Projects\Flutter\barcode_scanner\android\app\build.gradle' line:
14</p></li>
<li><p>What went wrong: A problem occurred evaluating project ':app'.</p>
<blockquote>
<p>ASCII</p>
</blockquote></li>
<li><p>Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.</p></li>
<li><p>Get more help at <a href="https://help.gradle.org" rel="noreferrer">https://help.gradle.org</a></p></li>
</ul>
<p>BUILD FAILED in 6s Command:
E:\Projects\Flutter\barcode_scanner\android\gradlew.bat app:properties</p>
<p>Finished with error: Please review your Gradle project setup in the
android/ folder.</p>
</blockquote>
<p>line 14 is:</p>
<pre><code>apply plugin: 'com.android.application'
</code></pre>
<p>I'm not sure whats problem and this is my implementation about that</p>
<p><code>pabspec.yaml</code> content:</p>
<pre><code>version: 1.0.0+1
environment:
sdk: '>=2.0.0-dev.28.0 <3.0.0'
dependencies:
flutter:
sdk: flutter
firebase_core: ^0.4.0
...
...
</code></pre>
<p><code>android/build.gradle</code> content:</p>
<pre><code>buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.google.gms:google-services:4.3.0'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p><code>android/app/build.gradle</code> content:</p>
<pre><code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 28
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "barcodescanner.pishguy.barcode_scanner"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
dependencies {
testImplementation 'junit:junit:4.12'
implementation 'com.google.firebase:firebase-core:17.0.1'
androidTestImplementation 'androidx.test:runner:1.3.0-alpha01'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0-alpha01'
}
apply plugin: 'com.google.gms.google-services'
</code></pre>
<p>running <code>flutter</code> command:</p>
<pre><code>E:\Projects\Flutter\barcode_scanner>flutter pub get
Running "flutter pub get" in barcode_scanner... 2.7s
[1]: https://github.com/facundomedica/fast_qr_reader_view
</code></pre>
| 0debug
|
How to create Cocoa GUI application with SwiftPM : <p>I want to split my codebase into a library which I want to upload to github and an GUI application. I hope that using recently introduced SwiftPM is a good idea.</p>
<p>But all examples I've been able to find show creating a console application with <code>swift package init --type executable</code>.</p>
<p>I want to know how to create a skeleton for macOS Cocoa Application with all the pregenerated stuff like assets, storyboard and so on?</p>
<p>It would be great to have access to such useful thing as:</p>
<pre><code>swift package build
swift package test
swift package update
...
</code></pre>
<p>Any ideas?</p>
<p>Thank you!</p>
| 0debug
|
I have installed extension for sorting product by quantity, it show above mention error? : <p>Fatal error: Uncaught Error: Call to a member function setStoreId() on boolean in /home/zohaibs4/public_html/includes/src/__default.php:7032 </p>
| 0debug
|
My PWA web app keep showing old version after a new release on Safari (but works fine on chrome)? : <p>I added PWA and service worker to my existing web app based on Angular 5. Everything looks fine on first release. However, when I try to release updates, something strange is happening.</p>
<p>On PC using Chrome, I don't have problem. After each release, I got an alert asking me to update for a new version, which is great.</p>
<p>However, this alert is missing on iOS, which is probably okay because iOS doesn't support auto update yet as I understand it. If I use Chrome on iOS, I can get the new version after manually refresh it (sometimes it takes a few refreshes). However, Safari browser doesn't normally show the new version. If I keeps refreshing the page, the new version comes up eventually, but it falls back again after I close and reopen it. As I play around, the only way I get to the new version is to manually clear the Safari cache first. This is not acceptable to regular user.</p>
<p>I understand iOS has limited support of PWA, but is this the most what we can get on iOS? Without the auto update, how can an iOS user know of the new release and update it? </p>
| 0debug
|
How to have text in center and image around it as shown in screenshot? (Image attached) : <p>I am converting an Illustrator design into HTML and CSS using Bootstrap framework. I am stuck on the part of design shown below: </p>
<p><a href="https://i.stack.imgur.com/GlHjD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GlHjD.png" alt="Illustrator Design"></a></p>
<p>I want the text surrounded by image as shown above.I can have these images separately and also one single image as I can export these from Illustrator according to the requirements. I can also export SVG image if required.What would be the best approach to achieve this task.</p>
| 0debug
|
JavaScript Mini-Max Sum - Returns 0 : <p>I'm trying to resolve the Mini-Max Sum Challenge from HackerRank. Why my code returns 0?
<a href="https://www.hackerrank.com/challenges/mini-max-sum/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/mini-max-sum/problem</a></p>
<p>Been trying different codes and still doesn't work.</p>
<pre><code>function miniMaxSum(arr) {
let maxSum = 0;
let minSum = 0;
arr.sort();
for (let i = 0; i < arr.leight; ++i) {
minSum += arr[i];
}
for (let i = 1; i < arr.leight; ++i) {
maxSum += arr[i];
}
console.log(minSum, maxSum)
}
</code></pre>
<p>I expect a output like 10 14, but the actual output is 0 0.</p>
| 0debug
|
onFocus bubble in React : <p>jsfiddle : <a href="https://jsfiddle.net/leiming/5e6rtgwd/" rel="noreferrer">https://jsfiddle.net/leiming/5e6rtgwd/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Sample extends React.Component {
onInputFocus(event) {
console.log('react input focus')
}
onSpanFocus(event) {
console.log('react span focus')
// event.stopPropagation()
}
render() {
return ( <span onFocus = {this.onSpanFocus}>
react input: <input type="text"
onFocus = {this.onInputFocus} />
</span> )
}
}
ReactDOM.render( < Sample / > ,
document.getElementById('container')
);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
<div>
<span onfocus="(function(){console.log('normal span')})()">
normal input:<input type="text" onfocus="(function(){console.log('normal input focus')})()">
</span>
</div></code></pre>
</div>
</div>
</p>
<p>jsfiddle : <a href="https://jsfiddle.net/leiming/5e6rtgwd/" rel="noreferrer">https://jsfiddle.net/leiming/5e6rtgwd/</a></p>
<p>Using React, <code>onFocus</code> in <code><input/></code> will bubble which is not same as usual HTML5.</p>
<p>Could anyone give me the refer doc why focus bubbles with React?</p>
| 0debug
|
static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
{
ARMCPU *cpu = ARM_CPU(cs);
CPUARMState *env = &cpu->env;
MemTxAttrs attrs = {};
AddressSpace *as;
attrs.secure = is_secure;
as = arm_addressspace(cs, attrs);
addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
if (fi->s1ptw) {
return 0;
}
if (regime_translation_big_endian(env, mmu_idx)) {
return address_space_ldl_be(as, addr, attrs, NULL);
} else {
return address_space_ldl_le(as, addr, attrs, NULL);
}
}
| 1threat
|
c; how to write a program that makes the user input a lot of strings as much and count the occurences? : I need to write a program that makes the user input a string, then the program asks the user to continue to input more strings or not. After that, the program should count all the occurrences of the words in all the strings the user input.
This code only counts the ocurrence of the last string, how should I change it?
```
#include <stdio.h>
#include <string.h>
#define MAXSTRLEN 100
int main(void)
{
int count = 0, c = 0, i, j = 0, k, space = 0;
char p[50][100], str1[20], ptr1[50][100];
char* ptr;
char str[MAXSTRLEN], Y_or_N;
printf("Write a sentence.\n");
while (1)
{
gets(str);
printf("Continue or not? (y or n): ");
scanf("%c", &Y_or_N);
getchar();
if (Y_or_N == 'n')
break;
}
for (i = 0; str[i] != '\0'; i++)
{
if ('A' <= str[i] && str[i] <= 'Z')
str[i] = str[i] + 32;
}
for (i = 0; i < strlen(str); i++)
{
if ((str[i] == ' ') || (str[i] == ',' && str[i + 1] == ' ') || (str[i] == '.'))
{
space++;
}
}
for (i = 0, j = 0, k = 0; j < strlen(str); j++)
{
if ((str[j] == ' ') || (str[j] == 44) || (str[j] == 46))
{
p[i][k] = '\0';
i++;
k = 0;
}
else
p[i][k++] = str[j];
}
k = 0;
for (i = 0; i <= space; i++)
{
for (j = 0; j <= space; j++)
{
if (i == j)
{
strcpy(ptr1[k], p[i]);
k++;
count++;
break;
}
else
{
if (strcmp(ptr1[j], p[i]) != 0)
continue;
else
break;
}
}
}
for (i = 0; i < count; i++)
{
for (j = 0; j <= space; j++)
{
if (strcmp(ptr1[i], p[j]) == 0)
c++;
}
printf("%s : %d times.\n", ptr1[i], c);
c = 0;
}
}
```
| 0debug
|
Using Android Studio, how can I create a value which will increase its value by 1 every time a button is clicked? : <p>I am currently working on an app for a project in University and am seeking to find out how to increase a variable value by 1 when a button is clicked. The app I am building is a sports app, and my idea is that when a button titled "Goal" is pressed that the value of "Goal" will be increased by 1.</p>
<p>I am also going to be putting this information into a Firebase real-time database so if you have any knowledge on how I could also do this would be very helpful. Thanks very much.</p>
| 0debug
|
String equation seperation :
String Str = new String("(300+23)*(43-21)/(84+7)");
System.out.println("Return Value :" );
String[] a=Str.split(Str);
String a="("
String b="300"
String c="+"
I want to convert this single string to an array giving output as above till the end of the equation using split method any suggestions
The above code doesn't works for it
| 0debug
|
static void test_validate_fail_list(TestInputVisitorData *data,
const void *unused)
{
UserDefOneList *head = NULL;
Error *err = NULL;
Visitor *v;
v = validate_test_init(data, "[ { 'string': 'string0', 'integer': 42 }, { 'string': 'string1', 'integer': 43 }, { 'string': 'string2', 'integer': 44, 'extra': 'ggg' } ]");
visit_type_UserDefOneList(v, NULL, &head, &err);
error_free_or_abort(&err);
g_assert(!head);
}
| 1threat
|
static void kvm_arm_machine_init_done(Notifier *notifier, void *data)
{
KVMDevice *kd, *tkd;
memory_listener_unregister(&devlistener);
QSLIST_FOREACH_SAFE(kd, &kvm_devices_head, entries, tkd) {
if (kd->kda.addr != -1) {
if (kvm_vm_ioctl(kvm_state, KVM_ARM_SET_DEVICE_ADDR,
&kd->kda) < 0) {
fprintf(stderr, "KVM_ARM_SET_DEVICE_ADDRESS failed: %s\n",
strerror(errno));
abort();
}
}
memory_region_unref(kd->mr);
g_free(kd);
}
}
| 1threat
|
Difference between hyperledger composer and hyperledger fabric? : <p>I am java developer and new to hyperledger. I am interested in learning it and need to know where to start . fabric vs composer?</p>
| 0debug
|
static int usbredir_handle_iso_data(USBRedirDevice *dev, USBPacket *p,
uint8_t ep)
{
int status, len;
if (!dev->endpoint[EP2I(ep)].iso_started &&
!dev->endpoint[EP2I(ep)].iso_error) {
struct usb_redir_start_iso_stream_header start_iso = {
.endpoint = ep,
.pkts_per_urb = 32,
.no_urbs = 3,
};
usbredirparser_send_start_iso_stream(dev->parser, 0, &start_iso);
usbredirparser_do_write(dev->parser);
DPRINTF("iso stream started ep %02X\n", ep);
dev->endpoint[EP2I(ep)].iso_started = 1;
}
if (ep & USB_DIR_IN) {
struct buf_packet *isop;
isop = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq);
if (isop == NULL) {
DPRINTF2("iso-token-in ep %02X, no isop\n", ep);
status = dev->endpoint[EP2I(ep)].iso_error;
dev->endpoint[EP2I(ep)].iso_error = 0;
return usbredir_handle_status(dev, status, 0);
}
DPRINTF2("iso-token-in ep %02X status %d len %d\n", ep, isop->status,
isop->len);
status = isop->status;
if (status != usb_redir_success) {
bufp_free(dev, isop, ep);
return usbredir_handle_status(dev, status, 0);
}
len = isop->len;
if (len > p->len) {
ERROR("received iso data is larger then packet ep %02X\n", ep);
bufp_free(dev, isop, ep);
return USB_RET_NAK;
}
memcpy(p->data, isop->data, len);
bufp_free(dev, isop, ep);
return len;
} else {
if (dev->endpoint[EP2I(ep)].iso_started) {
struct usb_redir_iso_packet_header iso_packet = {
.endpoint = ep,
.length = p->len
};
usbredirparser_send_iso_packet(dev->parser, 0, &iso_packet,
p->data, p->len);
usbredirparser_do_write(dev->parser);
}
status = dev->endpoint[EP2I(ep)].iso_error;
dev->endpoint[EP2I(ep)].iso_error = 0;
DPRINTF2("iso-token-out ep %02X status %d len %d\n", ep, status,
p->len);
return usbredir_handle_status(dev, status, p->len);
}
}
| 1threat
|
Syntax error in MySQL INSERT INTO statement : <p>there is some problem with my code. Everytime I try to insert something into the database, I get the syntax error.</p>
<p>Here is my database structure:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE `notes` (
`id` int(12) NOT NULL,
`type` varchar(15) NOT NULL,
`title` varchar(43) NOT NULL,
`text` varchar(43) NOT NULL,
`group` varchar(32) NOT NULL,
`uid` int(64) NOT NULL,
`creator` int(64) NOT NULL,
`insert_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `notes`
ADD PRIMARY KEY (`id`);
ALTER TABLE `notes`
MODIFY `id` int(12) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=79;
</code></pre>
<p>And thats my code</p>
<pre class="lang-php prettyprint-override"><code><?php
session_start();
require '../config.php';
$notetype = $_POST['type'];
$notetitle = $_POST['title'];
$notetext = $_POST['text'];
$notegroup = $_POST['group'];
$noteuid = $_POST['uid'];
$notecreator = $_POST['creator'];
$notetbname = $note['tbname'];
$conn = new mysqli($databaseconfig['ip'], $databaseconfig['user'], $databaseconfig['pass'], $databaseconfig['dbname']);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO $notetbname (type, title, text, group, uid, creator)
VALUES ('$notetype', '$notetitle', '$notetext', '$notegroup', $noteuid, $notecreator);";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</code></pre>
<p>This is what I get as error message:</p>
<pre class="lang-sql prettyprint-override"><code>Error: INSERT INTO notes (type, title, text, group, uid, creator) VALUES ('player', 'Hello there', 'Good morning everybody', 'Cop', 3325, 103);
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'group, uid, creator) VALUES ('player', 'Hello there', 'Good morning everybody'' at line 1
</code></pre>
| 0debug
|
How can I use tensorboard with tf.estimator.Estimator : <p>I am considering to move my code base to <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator" rel="noreferrer">tf.estimator.Estimator</a>, but I cannot find an example on how to use it in combination with tensorboard summaries.</p>
<p>MWE:</p>
<pre><code>import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.INFO)
# Declare list of features, we only have one real-valued feature
def model(features, labels, mode):
# Build a linear model and predict values
W = tf.get_variable("W", [1], dtype=tf.float64)
b = tf.get_variable("b", [1], dtype=tf.float64)
y = W*features['x'] + b
loss = tf.reduce_sum(tf.square(y - labels))
# Summaries to display for TRAINING and TESTING
tf.summary.scalar("loss", loss)
tf.summary.image("X", tf.reshape(tf.random_normal([10, 10]), [-1, 10, 10, 1])) # dummy, my inputs are images
# Training sub-graph
global_step = tf.train.get_global_step()
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = tf.group(optimizer.minimize(loss), tf.assign_add(global_step, 1))
return tf.estimator.EstimatorSpec(mode=mode, predictions=y,loss= loss,train_op=train)
estimator = tf.estimator.Estimator(model_fn=model, model_dir='/tmp/tf')
# define our data set
x=np.array([1., 2., 3., 4.])
y=np.array([0., -1., -2., -3.])
input_fn = tf.contrib.learn.io.numpy_input_fn({"x": x}, y, 4, num_epochs=1000)
for epoch in range(10):
# train
estimator.train(input_fn=input_fn, steps=100)
# evaluate our model
estimator.evaluate(input_fn=input_fn, steps=10)
</code></pre>
<p>How can I display my two summaries in tensorboard? Do I have to register a hook in which I use a <code>tf.summary.FileWriter</code> or something else?</p>
| 0debug
|
int do_subchannel_work_passthrough(SubchDev *sch)
{
int ret;
SCSW *s = &sch->curr_status.scsw;
if (s->ctrl & SCSW_FCTL_CLEAR_FUNC) {
sch_handle_clear_func(sch);
ret = 0;
} else if (s->ctrl & SCSW_FCTL_HALT_FUNC) {
sch_handle_halt_func(sch);
ret = 0;
} else if (s->ctrl & SCSW_FCTL_START_FUNC) {
ret = sch_handle_start_func_passthrough(sch);
} else {
return -ENODEV;
}
return ret;
}
| 1threat
|
easy_install pip fails on MAC OSX : <p>I am running OSX Sierra 10.12.6 on a macbook pro</p>
<p>There's known bug in pip 10.0.0b1 that causes a Trap: 5 when you try to install anything. This also prevents you from updating pip itself to 10.0.0b2, which supposedly fixes this bug.</p>
<p>So - I uninstalled pip, thinking I'd go back to easy_install to get the latest - BUT NOOOO! (sound of grinding teeth here ...)</p>
<p>This is what I get:</p>
<p>(** start console output)</p>
<p>sudo easy_install pip
Password:</p>
<p>Searching for pip
Reading <a href="https://pypi.python.org/simple/pip/" rel="noreferrer">https://pypi.python.org/simple/pip/</a></p>
<p>Download error on <a href="https://pypi.python.org/simple/pip/" rel="noreferrer">https://pypi.python.org/simple/pip/</a>: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) -- Some packages may not be found!</p>
<p>Couldn't find index page for 'pip' (maybe misspelled?)</p>
<p>Scanning index of all packages (this may take a while)</p>
<p>Reading <a href="https://pypi.python.org/simple/" rel="noreferrer">https://pypi.python.org/simple/</a></p>
<p>Download error on <a href="https://pypi.python.org/simple/" rel="noreferrer">https://pypi.python.org/simple/</a>: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) -- Some packages may not be found!</p>
<p>No local packages or download links found for pip</p>
<p>error: Could not find suitable distribution for Requirement.parse('pip')**</p>
<p>(** end console output)</p>
<p>I'm trying to avoid uninstalling and reinstalling everything pythonic.
The output above seems to indicate a problem with SSL/TLS versions, but it doesn't tell me enough to figure what.</p>
<p>Any help? I can't believe that MAC OSX doesn't support the proper SSL/TLS versions. I think that message is a red herring (or a 'frog with no legs' if you get that reference)</p>
<p>TIA</p>
| 0debug
|
static void eth_receive(void *opaque, const uint8_t *buf, size_t size)
{
mv88w8618_eth_state *s = opaque;
uint32_t desc_addr;
mv88w8618_rx_desc desc;
int i;
for (i = 0; i < 4; i++) {
desc_addr = s->cur_rx[i];
if (!desc_addr)
continue;
do {
eth_rx_desc_get(desc_addr, &desc);
if ((desc.cmdstat & MP_ETH_RX_OWN) && desc.buffer_size >= size) {
cpu_physical_memory_write(desc.buffer + s->vlan_header,
buf, size);
desc.bytes = size + s->vlan_header;
desc.cmdstat &= ~MP_ETH_RX_OWN;
s->cur_rx[i] = desc.next;
s->icr |= MP_ETH_IRQ_RX;
if (s->icr & s->imr)
qemu_irq_raise(s->irq);
eth_rx_desc_put(desc_addr, &desc);
return;
}
desc_addr = desc.next;
} while (desc_addr != s->rx_queue[i]);
}
}
| 1threat
|
void commit_start(const char *job_id, BlockDriverState *bs,
BlockDriverState *base, BlockDriverState *top, int64_t speed,
BlockdevOnError on_error, const char *backing_file_str,
Error **errp)
{
CommitBlockJob *s;
BlockReopenQueue *reopen_queue = NULL;
int orig_overlay_flags;
int orig_base_flags;
BlockDriverState *iter;
BlockDriverState *overlay_bs;
Error *local_err = NULL;
int ret;
assert(top != bs);
if (top == base) {
error_setg(errp, "Invalid files for merge: top and base are the same");
return;
}
overlay_bs = bdrv_find_overlay(bs, top);
if (overlay_bs == NULL) {
error_setg(errp, "Could not find overlay image for %s:", top->filename);
return;
}
s = block_job_create(job_id, &commit_job_driver, bs, 0, BLK_PERM_ALL,
speed, BLOCK_JOB_DEFAULT, NULL, NULL, errp);
if (!s) {
return;
}
orig_base_flags = bdrv_get_flags(base);
orig_overlay_flags = bdrv_get_flags(overlay_bs);
if (!(orig_base_flags & BDRV_O_RDWR)) {
reopen_queue = bdrv_reopen_queue(reopen_queue, base, NULL,
orig_base_flags | BDRV_O_RDWR);
}
if (!(orig_overlay_flags & BDRV_O_RDWR)) {
reopen_queue = bdrv_reopen_queue(reopen_queue, overlay_bs, NULL,
orig_overlay_flags | BDRV_O_RDWR);
}
if (reopen_queue) {
bdrv_reopen_multiple(bdrv_get_aio_context(bs), reopen_queue, &local_err);
if (local_err != NULL) {
error_propagate(errp, local_err);
goto fail;
}
}
assert(bdrv_chain_contains(top, base));
for (iter = top; iter != backing_bs(base); iter = backing_bs(iter)) {
block_job_add_bdrv(&s->common, "intermediate node", iter, 0,
BLK_PERM_ALL, &error_abort);
}
if (bs != overlay_bs) {
block_job_add_bdrv(&s->common, "overlay of top", overlay_bs, 0,
BLK_PERM_ALL, &error_abort);
}
s->base = blk_new(0, BLK_PERM_ALL);
ret = blk_insert_bs(s->base, base, errp);
if (ret < 0) {
goto fail;
}
s->top = blk_new(0, BLK_PERM_ALL);
ret = blk_insert_bs(s->top, top, errp);
if (ret < 0) {
goto fail;
}
s->active = bs;
s->base_flags = orig_base_flags;
s->orig_overlay_flags = orig_overlay_flags;
s->backing_file_str = g_strdup(backing_file_str);
s->on_error = on_error;
trace_commit_start(bs, base, top, s);
block_job_start(&s->common);
return;
fail:
if (s->base) {
blk_unref(s->base);
}
if (s->top) {
blk_unref(s->top);
}
block_job_unref(&s->common);
}
| 1threat
|
Array of objects initialization - Java Android : I want to create an array of objects as mentioned in this answer:
https://stackoverflow.com/questions/5364278/creating-an-array-of-objects-in-java
i.e initialize one at a time like
A[] a = new A[4];
a[0] = new A();
My class definition:
public class Question {
private int mAnswer;
private String mQuestion;
private String[] mOptions;
public Question(String question, int answer, String[] option){
mQuestion = question;
mAnswer = answer;
mOptions = option;
}
public int getmAnswer() {
return mAnswer;
}
public String getmQuestion() {
return mQuestion;
}
public String[] getmOptions() {
return mOptions;
}
};
My Java Activity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import static android.R.attr.x;
public class HomeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
String[] options1 = {"ABCD", "EFGH", "IJKL", "MNOP"};
String[] options2 = {"Bangalore", "Delhi", "Mumbai", "Pune"};
String[] options3 = {"Business", "Work", "Nothing", "Study"};
Question[] ques = new Question[3];
ques[0] = new Question("What is your name?", 2, options1);
ques[1] = new Question("Where are you from?", 3, options2);
ques[2] = new Question("What do you do?", 4, options3);
}
But the initializations :
ques[0] = new Question("What is your name?", 2, options1);
ques[1] = new Question("Where are you from?", 3, options2);
ques[2] = new Question("What do you do?", 4, options3);
give me an error. These lines get underlined RED giving me all of the following errors for each line:
-Identifier expected
-Invalid method declaration; return type required
-Missing method body, or declare abstract
-Parameter expected
-Unexpected token
-Unknown class: 'ques'
I have no idea where I am going wrong. I'm a beginner in Android and Java.
Any help would be appreciated.
Thanks.
| 0debug
|
Transfer content of one array to another, removing duplicates : <p>I have an array of about 1000 words. I want to transfer them to another array while removing any duplicates. How can I do this in C# ? </p>
| 0debug
|
Incrementing Click Redux Function in an array : <p>I am working with some svg elements and i have built an increment button.</p>
<p>The increment button takes the the <code>path d</code> values converts it into an array and sums <code>5</code> from the third element of the array. If the element is <code>'L'</code> or <code>'M'</code> it does nothing</p>
<p>Here the click function in the redux, it takes the values of the incrementing action state</p>
<pre><code> const a = action.index;
let string = state[a].d;
</code></pre>
<p>It converts in an array</p>
<pre><code>let array = string.split(" ");
</code></pre>
<p>and then it does all the calculation i said in the loop</p>
<p>See the full redux function</p>
<pre><code> switch(action.type) {
case 'INCREMENT_COORDINATES' :
console.log("incrementing coordinaates")
const a = action.index;
let string = state[a].d;
let array = string.split(" ");
let max = array.length;
let i = 3;
let click = () => {
i++;
if ( i === max ) i = 3;
if (array[i] !== 'M' && array[i] !== 'L') array[i] = parseInt(array[i]) + 5;
array.join(' ');
};
return [
...state.slice(0,a), // before the one we are updating
{...state[a], d: click()}, // updating the with the click function
...state.slice(a + 1), // after the one we are updating
]
default:
return state;
}
</code></pre>
<p>See the video demo while i debug it <a href="http://www.fastswf.com/uSBU68E" rel="noreferrer">http://www.fastswf.com/uSBU68E</a></p>
<p>As you can see the code does the right calculation and it sums <code>5</code> from the fourth element and it is returning the number <code>331</code>. So all good!But the problem is that i need to return it as <code>'331'</code>, a new element of the array to continue the loop.</p>
<p>I have built a demo which is perfectly working and doing what i want to achieve, using the same code! So i don't understand what i am doing wrong when i apply it in my redux function.</p>
<p>See the <a href="http://jsbin.com/tumesug/edit?js,console,output" rel="noreferrer">jsBin</a> perfectly working as i want.</p>
| 0debug
|
Why is correct id is not inserting into table : I want the following code to insert the cars id in customer_payment table but it only select 477 id. I don't know why. As it can be seen in image bellow only product_id 477 is inserted not any other if I select 500 it still inserts 477. Please help me on this help will be appreciated. Thank you
[enter image description here][1]
include 'admin/db.php';
if(isset($_GET['payment_here'])){
//select product id from cart
$select_cart = "select * from cart";
$runcart = mysqli_query($conn, $select_cart);
$cartwhile=mysqli_fetch_assoc($runcart);
$carssid = $cartwhile['P_ID'];
$cusid = $cartwhile['C_ID'];
//select id from cars
$scars = "select * from cars where id=$carssid";
$scarsrun = mysqli_query($conn, $scars);
$showcars = mysqli_fetch_assoc($scarsrun);
$carsdealer = $showcars['dealer'];
//select customer id from customer table
//$selectcust = "select * from customer_register where id=$cusid";
//insert data into customer payment table
echo $insertpay = "insert into customer_payment
(Product_id, customer_id, dealer)
values ( $carssid," . $_SESSION['customer_id'] . ", '$carsdealer')";
$run_inserts = mysqli_query($conn, $insertpay);
/*
if($run_inserts){
echo "<script>window.location.href = 'checkout.php'</script>";
}
*/
}
?>
[1]: http://i.stack.imgur.com/gQccg.jpg
| 0debug
|
static struct dirent *local_readdir(FsContext *ctx, V9fsFidOpenState *fs)
{
struct dirent *entry;
again:
entry = readdir(fs->dir.stream);
if (!entry) {
return NULL;
}
if (ctx->export_flags & V9FS_SM_MAPPED) {
entry->d_type = DT_UNKNOWN;
} else if (ctx->export_flags & V9FS_SM_MAPPED_FILE) {
if (local_is_mapped_file_metadata(ctx, entry->d_name)) {
goto again;
}
entry->d_type = DT_UNKNOWN;
}
return entry;
}
| 1threat
|
Indexoutboundexception error for arraylist : Can someone help me explain why this piece of code is throwing an indexoutbound error
public static Hull merging(Hull HullA, Hull HullB) {
Hull finalHull = new Hull();
int i=0;
int j=0;
if (HullA.list.get(i) >= HullB.list.get(j))
{
finalHull.list.add(HullA.list.get(i));
i++;
}else
{
finalHull.list.add(HullB.list.get(j));
j++;
}
return finalHull;
}
| 0debug
|
SwiftUI: Forcing an Update : <p>Normally, we're restricted from discussing Apple prerelease stuff, but I've already seen plenty of SwiftUI discussions, so I suspect that it's OK; just this once.</p>
<p>I am in the process of driving into the weeds on one of the tutorials (I do that).</p>
<p>I am adding a pair of buttons below the swipeable screens in the "Interfacing With UIKit" tutorial: <a href="https://developer.apple.com/tutorials/swiftui/interfacing-with-uikit" rel="noreferrer">https://developer.apple.com/tutorials/swiftui/interfacing-with-uikit</a></p>
<p>These are "Next" and "Prev" buttons. When at one end or the other, the corresponding button hides. I have that working fine.</p>
<p>The problem that I'm having, is accessing the UIPageViewController instance represented by the PageViewController.</p>
<p>I have the currentPage property changing (by making the PageViewController a delegate of the UIPageViewController), but I need to force the UIPageViewController to change programmatically.</p>
<p>I know that I can "brute force" the display by redrawing the PageView body, reflecting a new currentPage, but I'm not exactly sure how to do that.</p>
<pre><code>struct PageView<Page: View>: View {
var viewControllers: [UIHostingController<Page>]
@State var currentPage = 0
init(_ views: [Page]) {
self.viewControllers = views.map { UIHostingController(rootView: $0) }
}
var body: some View {
VStack {
PageViewController(controllers: viewControllers, currentPage: $currentPage)
HStack(alignment: .center) {
Spacer()
if 0 < currentPage {
Button(action: {
self.prevPage()
}) {
Text("Prev")
}
Spacer()
}
Text(verbatim: "Page \(currentPage)")
if currentPage < viewControllers.count - 1 {
Spacer()
Button(action: {
self.nextPage()
}) {
Text("Next")
}
}
Spacer()
}
}
}
func nextPage() {
if currentPage < viewControllers.count - 1 {
currentPage += 1
}
}
func prevPage() {
if 0 < currentPage {
currentPage -= 1
}
}
}
</code></pre>
<p>I know the answer should be obvious, but I'm having difficulty figuring out how to programmatically refresh the VStack or body.</p>
| 0debug
|
Pygame: Rect that is different sized than image : this is my first post on here just created my first account. :D
I am a beginner coder and learned python just 2 weeks ago, but I wanted to try something new and found [this tutorial](https://www.youtube.com/watch?v=VO8rTszcW4s&list=PLsk-HSGFjnaH5yghzu7PcOzm9NhsW0Urw&index=1) on the web. I used it and tweaked it a little. My goal is to create a zelda clone, meaning my game will be Tile-Based
Now for the problem.
All my sprites are not in 1:1 Ratio. The rect`s size i created is TILESIZE * TILESIZE (=64 height, 64 width). Now the rect sticks to the top, but I need it to stick to the bottom center of my sprite. I tried nummerous ways and asked my workmates, but they can´t help me either. Can you guys help me, but detailed so I can learn out of my mistake?
All my code files (PasteBin links, I´m german I hope I did this right with posting PasteBin Links):
```main.py | https://pastebin.com/7Y20ARH0```
```sprites.py | https://pastebin.com/F0BnAVZv | Inside here is my Player and the collision detection, so this is where you want to look for I assume```
```tilemap.py | https://pastebin.com/S4eNPbZe | Probably unrelevant, thought I´d rather post it anyways ^^```
```settings.py | https://pastebin.com/gNRrqp0v```
I appreciate every bit of help, but I can also understand if you don´t want to look trough this mess ^^
| 0debug
|
static int kvm_sclp_service_call(S390CPU *cpu, struct kvm_run *run,
uint16_t ipbh0)
{
CPUS390XState *env = &cpu->env;
uint64_t sccb;
uint32_t code;
int r = 0;
cpu_synchronize_state(CPU(cpu));
if (env->psw.mask & PSW_MASK_PSTATE) {
enter_pgmcheck(cpu, PGM_PRIVILEGED);
return 0;
}
sccb = env->regs[ipbh0 & 0xf];
code = env->regs[(ipbh0 & 0xf0) >> 4];
r = sclp_service_call(sccb, code);
if (r < 0) {
enter_pgmcheck(cpu, -r);
}
setcc(cpu, r);
return 0;
}
| 1threat
|
Is it safe to compile againts later JDK? : <p>I have some big projects running on Java 6. But I plan to start building them in Java 8 since a lot of build tools have moved away from Java 6.</p>
<p>Is it safe for me to simply compile them with Java 8 and then deploy them in a web container running Java 8? If not, what are the considerations?</p>
<p>FYI, they don't have a proper automated test suite in place.</p>
| 0debug
|
Duplicate 'Content' items were included. The .NET SDK includes 'Content' items from your project directory by default : <p>Whenever I add a javascript or css file to my asp.net core project and I execute <code>dotnet run</code> in my bash terminal, I get the following error:</p>
<blockquote>
<p>/usr/share/dotnet/sdk/1.0.1/Sdks/Microsoft.NET.Sdk/build/Microsoft</p>
<p>.NET.Sdk.DefaultItems.targets(188,5): error : Duplicate 'Content'
items were included. The .NET SDK includes 'Content' items from your
project directory by default. You can either remove these items from
your project file, or set the 'EnableDefaultContentItems' property to
'false' if you want to explicitly include them in your project file.
For more information, see <a href="https://aka.ms/sdkimplicititems" rel="noreferrer">https://aka.ms/sdkimplicititems</a>. The
duplicate items were: 'wwwroot/css/BasicQuotation.css';
'wwwroot/js/BasicQuotation.js'
[/mnt/c/Dev/myproject/MyProject/MyProject.csproj]</p>
<p>The build failed. Please fix the build errors and run again.</p>
</blockquote>
<p>I can fix this by removing the <code>ItemGroup</code> from my csproj file, but I don't think that's very productive.</p>
<p>This happens in the default Visual Studio 2017 ASP.NET Core Web Application (.NET Core) template. I add the files to my project by right clicking the wwwroot > js folder and then select <code>Add > New Item > JavaScript File</code></p>
<p>This is my .csproj file:</p>
<pre><code><Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback>
</PropertyGroup>
<PropertyGroup>
<UserSecretsId>aspnet-MyProject-7e1906d8-5dbd-469a-b237-d7a563081253</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<Compile Remove="wwwroot\lib\jquery-validation\**" />
<Content Remove="wwwroot\lib\jquery-validation\**" />
<EmbeddedResource Remove="wwwroot\lib\jquery-validation\**" />
<None Remove="wwwroot\lib\jquery-validation\**" />
</ItemGroup>
<ItemGroup>
<Content Include="wwwroot\css\BasicQuotation.css" />
<Content Include="wwwroot\js\BasicQuotation.js" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0" />
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Data\Commands\" />
<Folder Include="Data\Queries\" />
<Folder Include="wwwroot\images\" />
</ItemGroup>
</Project>
</code></pre>
| 0debug
|
Scanning integers in C in xCode : so I am trying to scan some integers in C (so taking in the user's first and last name, departure and arrival locations) but I am getting this error that the type of declaration I've made is inconsistent. I'm a little new to C still so bear with me as this may be a trivial thing. Thanks in advance.
Here's what I am trying to do:
#include <stdio.h>
int main (void) {
char lastName, firstName, depart, arrive;
printf("Please enter passenger's last name: ");
scanf("%s", &lastName);
printf("Please enter passenger's first name: ");
scanf("%s", &firstName);
printf("Which airport are you departing from? ");
scanf("%s", &depart);
printf("Which airport will you be heading to? ");
scanf("%s", &arrive);
printf("LAST NAME: %s FIRST NAME: %s FROM: %s TO: %s", lastName,
firstName, depart, arrive);
return 0;
}
| 0debug
|
Cross Domain Image upload Angular+laravel : <p>I have been struggling with image upload on server. I am using <a href="https://github.com/danialfarid/ng-file-upload">ngFileUpload</a> on front end. But I always get </p>
<p>"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource"</p>
<p>Angular Code for file Upload : </p>
<pre><code> var uploadFile = function (file) {
if (file) {
if (!file.$error) {
Upload.upload({
url: baseUrl+'upload',
file: file
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
//console.log(evt.total);
}).success(function (data, status, headers, config) {
$timeout(function() {
console.log(data);
console.log(status);
if(status==200)
{
logo_path = data.logo_path;
}
});
});
}
}
};
</code></pre>
<p>On Laravel i have configured CORS like this : </p>
<pre><code>public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: http://localhost:8001/");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);
return $response;
}
</code></pre>
<p>The Normal cross domain POST request works fine. i.e $http.post(). I have tried many different variations of headers on angular but none helps. Also the OPTIONS request returns 200 OK but still preflight response failure message is displayed. Can anyone help me with how to further debug this issue?</p>
| 0debug
|
static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
{
Vp3DecodeContext *s = avctx->priv_data;
int visible_width, visible_height, colorspace;
int offset_x = 0, offset_y = 0;
AVRational fps, aspect;
s->theora = get_bits_long(gb, 24);
av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
if (s->theora < 0x030200)
{
s->flipped_image = 1;
av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n");
}
visible_width = s->width = get_bits(gb, 16) << 4;
visible_height = s->height = get_bits(gb, 16) << 4;
if(av_image_check_size(s->width, s->height, 0, avctx)){
av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n", s->width, s->height);
s->width= s->height= 0;
return -1;
}
if (s->theora >= 0x030200) {
visible_width = get_bits_long(gb, 24);
visible_height = get_bits_long(gb, 24);
offset_x = get_bits(gb, 8);
offset_y = get_bits(gb, 8);
}
fps.num = get_bits_long(gb, 32);
fps.den = get_bits_long(gb, 32);
if (fps.num && fps.den) {
av_reduce(&avctx->time_base.num, &avctx->time_base.den,
fps.den, fps.num, 1<<30);
}
aspect.num = get_bits_long(gb, 24);
aspect.den = get_bits_long(gb, 24);
if (aspect.num && aspect.den) {
av_reduce(&avctx->sample_aspect_ratio.num,
&avctx->sample_aspect_ratio.den,
aspect.num, aspect.den, 1<<30);
}
if (s->theora < 0x030200)
skip_bits(gb, 5);
colorspace = get_bits(gb, 8);
skip_bits(gb, 24);
skip_bits(gb, 6);
if (s->theora >= 0x030200)
{
skip_bits(gb, 5);
avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
return AVERROR_INVALIDDATA;
}
skip_bits(gb, 3);
}
if ( visible_width <= s->width && visible_width > s->width-16
&& visible_height <= s->height && visible_height > s->height-16
&& !offset_x && (offset_y == s->height - visible_height))
avcodec_set_dimensions(avctx, visible_width, visible_height);
else
avcodec_set_dimensions(avctx, s->width, s->height);
if (colorspace == 1) {
avctx->color_primaries = AVCOL_PRI_BT470M;
} else if (colorspace == 2) {
avctx->color_primaries = AVCOL_PRI_BT470BG;
}
if (colorspace == 1 || colorspace == 2) {
avctx->colorspace = AVCOL_SPC_BT470BG;
avctx->color_trc = AVCOL_TRC_BT709;
}
return 0;
}
| 1threat
|
static void dxva2_uninit(AVCodecContext *s)
{
InputStream *ist = s->opaque;
DXVA2Context *ctx = ist->hwaccel_ctx;
ist->hwaccel_uninit = NULL;
ist->hwaccel_get_buffer = NULL;
ist->hwaccel_retrieve_data = NULL;
if (ctx->decoder_service)
IDirectXVideoDecoderService_Release(ctx->decoder_service);
av_buffer_unref(&ctx->hw_frames_ctx);
av_buffer_unref(&ctx->hw_device_ctx);
av_frame_free(&ctx->tmp_frame);
av_freep(&ist->hwaccel_ctx);
av_freep(&s->hwaccel_context);
}
| 1threat
|
int spapr_tce_dma_read(VIOsPAPRDevice *dev, uint64_t taddr, void *buf,
uint32_t size)
{
#ifdef DEBUG_TCE
fprintf(stderr, "spapr_tce_dma_write taddr=0x%llx size=0x%x\n",
(unsigned long long)taddr, size);
#endif
if (dev->flags & VIO_PAPR_FLAG_DMA_BYPASS) {
cpu_physical_memory_read(taddr, buf, size);
return 0;
}
while (size) {
uint64_t tce;
uint32_t lsize;
uint64_t txaddr;
if (taddr >= dev->rtce_window_size) {
#ifdef DEBUG_TCE
fprintf(stderr, "spapr_tce_dma_read out of bounds\n");
#endif
return H_DEST_PARM;
}
tce = dev->rtce_table[taddr >> SPAPR_VIO_TCE_PAGE_SHIFT].tce;
lsize = MIN(size, ((~taddr) & SPAPR_VIO_TCE_PAGE_MASK) + 1);
if (!(tce & 1)) {
return H_DEST_PARM;
}
txaddr = (tce & ~SPAPR_VIO_TCE_PAGE_MASK) |
(taddr & SPAPR_VIO_TCE_PAGE_MASK);
#ifdef DEBUG_TCE
fprintf(stderr, " -> write to txaddr=0x%llx, size=0x%x\n",
(unsigned long long)txaddr, lsize);
#endif
cpu_physical_memory_read(txaddr, buf, lsize);
buf += lsize;
taddr += lsize;
size -= lsize;
}
return H_SUCCESS;
}
| 1threat
|
What is the difference between `declare namespace` and `declare module` : <p>After reading <a href="https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html" rel="noreferrer">this manual</a> and this quote:</p>
<blockquote>
<p>It’s important to note that in TypeScript 1.5, the nomenclature has
changed. “Internal modules” are now “namespaces”. “External modules”
are now simply “modules”</p>
</blockquote>
<p>I was under impression that <code>declare module</code> is no longer used and is replaced by <code>declare namespace</code>, however when exploring <code>node_modules\@types\node\index.d.ts</code> I can see that both <code>declare module</code> and <code>declare namespace</code> is used:</p>
<pre><code>declare namespace NodeJS {
export var Console: {
prototype: Console;
new(stdout: WritableStream, stderr?: WritableStream): Console;
}
...
declare module "buffer" {
export var INSPECT_MAX_BYTES: number;
var BuffType: typeof Buffer;
var SlowBuffType: typeof SlowBuffer;
export { BuffType as Buffer, SlowBuffType as SlowBuffer };
}
</code></pre>
<p>Why so? What's the difference?</p>
<p>External modules (ES6 modules) <strong>do not</strong> come into play here as I understand.</p>
| 0debug
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.