problem stringlengths 26 131k | labels class label 2 classes |
|---|---|
Why does the exit() function in C "never fail"? : <p>I was reading Head First C and it said "<code>exit()</code> is the only function that is guaranteed never to return a value and never to fail."</p>
<ol>
<li><p>Are there other functions in C that are supposed to not return anything that might?</p></li>
<li><p>Why is it that <code>exit()</code> never ever fails?</p></li>
</ol>
| 0debug |
static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
{
CPUState *cpu = current_cpu;
CPUClass *cc = CPU_GET_CLASS(cpu);
CPUArchState *env = cpu->env_ptr;
target_ulong pc, cs_base;
target_ulong vaddr;
CPUWatchpoint *wp;
uint32_t cpu_flags;
if (cpu->watchpoint_hit) {
cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
return;
}
vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);
QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
if (cpu_watchpoint_address_matches(wp, vaddr, len)
&& (wp->flags & flags)) {
if (flags == BP_MEM_READ) {
wp->flags |= BP_WATCHPOINT_HIT_READ;
} else {
wp->flags |= BP_WATCHPOINT_HIT_WRITE;
}
wp->hitaddr = vaddr;
wp->hitattrs = attrs;
if (!cpu->watchpoint_hit) {
if (wp->flags & BP_CPU &&
!cc->debug_check_watchpoint(cpu, wp)) {
wp->flags &= ~BP_WATCHPOINT_HIT;
continue;
}
cpu->watchpoint_hit = wp;
tb_lock();
tb_check_watchpoint(cpu);
if (wp->flags & BP_STOP_BEFORE_ACCESS) {
cpu->exception_index = EXCP_DEBUG;
cpu_loop_exit(cpu);
} else {
cpu_get_tb_cpu_state(env, &pc, &cs_base, &cpu_flags);
tb_gen_code(cpu, pc, cs_base, cpu_flags, 1);
cpu_loop_exit_noexc(cpu);
}
}
} else {
wp->flags &= ~BP_WATCHPOINT_HIT;
}
}
}
| 1threat |
static int encode_bitstream(FlashSVContext *s, const AVFrame *p, uint8_t *buf,
int buf_size, int block_width, int block_height,
uint8_t *previous_frame, int *I_frame)
{
PutBitContext pb;
int h_blocks, v_blocks, h_part, v_part, i, j;
int buf_pos, res;
int pred_blocks = 0;
init_put_bits(&pb, buf, buf_size * 8);
put_bits(&pb, 4, block_width / 16 - 1);
put_bits(&pb, 12, s->image_width);
put_bits(&pb, 4, block_height / 16 - 1);
put_bits(&pb, 12, s->image_height);
flush_put_bits(&pb);
buf_pos = 4;
h_blocks = s->image_width / block_width;
h_part = s->image_width % block_width;
v_blocks = s->image_height / block_height;
v_part = s->image_height % block_height;
for (j = 0; j < v_blocks + (v_part ? 1 : 0); j++) {
int y_pos = j * block_height;
int cur_blk_height = (j < v_blocks) ? block_height : v_part;
for (i = 0; i < h_blocks + (h_part ? 1 : 0); i++) {
int x_pos = i * block_width;
int cur_blk_width = (i < h_blocks) ? block_width : h_part;
int ret = Z_OK;
uint8_t *ptr = buf + buf_pos;
res = copy_region_enc(p->data[0], s->tmpblock,
s->image_height - (y_pos + cur_blk_height + 1),
x_pos, cur_blk_height, cur_blk_width,
p->linesize[0], previous_frame);
if (res || *I_frame) {
unsigned long zsize = 3 * block_width * block_height;
ret = compress2(ptr + 2, &zsize, s->tmpblock,
3 * cur_blk_width * cur_blk_height, 9);
if (ret != Z_OK)
av_log(s->avctx, AV_LOG_ERROR,
"error while compressing block %dx%d\n", i, j);
bytestream_put_be16(&ptr, zsize);
buf_pos += zsize + 2;
av_dlog(s->avctx, "buf_pos = %d\n", buf_pos);
} else {
pred_blocks++;
bytestream_put_be16(&ptr, 0);
buf_pos += 2;
}
}
}
if (pred_blocks)
*I_frame = 0;
else
*I_frame = 1;
return buf_pos;
}
| 1threat |
Python Json.loads to list not dict :
Hi all I'm a new python developer and I am running into an issue that Google had not been able to address for me for me.
I understand that "json.loads(var.text)" will return a dict, and in some cases it will for me.
Say the data looks like this:
{
"PROJECT_ID": 3351040882,
"common.ALLTYPES_DESCRIPTION": "",
"servermain.PROJECT_TITLE": "",
}
This data will load as a dict!
Here is a sample of the data that is loading as a list.
[
{
"PROJECT_ID": 3351040882,
"common.ALLTYPES_NAME": "AdvancedTags",
"common.ALLTYPES_DESCRIPTION": "",
"servermain.ALIAS_MAPPED_TO": "_AdvancedTags",
"servermain.ALIAS_SCAN_RATE_MILLISECONDS": 0
},
{
"PROJECT_ID": 3351040882,
"common.ALLTYPES_NAME": "Channel1__CommunicationSerialization",
"common.ALLTYPES_DESCRIPTION": "",
"servermain.ALIAS_MAPPED_TO": "Channel1._CommunicationSerialization",
"servermain.ALIAS_SCAN_RATE_MILLISECONDS": 0
},
]
From my research I understand the second output is a list of dicts, is there some simple function to load a list to a dict?
| 0debug |
How to set cookie in vuejs? : <p>What is the best practice for setting a cookie in vuejs?
I use SSR, so I guess I can’t use localStorage.</p>
<p>What is the best approach here?</p>
| 0debug |
static void virtio_set_status(struct subchannel_id schid,
unsigned long dev_addr)
{
unsigned char status = dev_addr;
run_ccw(schid, CCW_CMD_WRITE_STATUS, &status, sizeof(status));
}
| 1threat |
static void virtio_pci_vector_mask(PCIDevice *dev, unsigned vector)
{
VirtIOPCIProxy *proxy = container_of(dev, VirtIOPCIProxy, pci_dev);
VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
VirtQueue *vq = virtio_vector_first_queue(vdev, vector);
int index;
while (vq) {
index = virtio_get_queue_index(vq);
if (!virtio_queue_get_num(vdev, index)) {
break;
}
virtio_pci_vq_vector_mask(proxy, index, vector);
vq = virtio_vector_next_queue(vq);
}
}
| 1threat |
what is the difference b/w *array[] and array[] ? : - As we know that the value of array name is the address of the first element in the array
- and the Value of the pointer is an address .
so suppose i declare a pointer to an int
int *a= new int();
int *b= new int();
And i want it to store its address in some array but the array will not be the pointer like this
int *arr[] = {a, b};
And is it possible ??
because the array name contain the address and if we declare an array pointer then they will again contain the address same thing ,
so how can we store a pointers in regular array and not a pointer array | 0debug |
Can't seam to add items to a combobox : I have tried these sites for help:
http://www.excel-easy.com/vba/userform.html
http://sitestory.dk/excel_vba/listboxes.htm
https://www.ozgrid.com/forum/forum/help-forums/excel-general/49940-fill-combobox-with-cell-range-link-combobox-to-cell
https://stackoverflow.com/questions/17946317/how-to-add-items-to-a-combobox-in-a-form-in-excel-vba
http://www.contextures.com/Excel-VBA-ComboBox-Lists.html
https://msdn.microsoft.com/en-us/library/dd758784(v=office.12).aspx
Would appreciate the help!
| 0debug |
Fullcalendar , Make today (for current month) active : Today button disable for current month. when you go next or previous month it appear as active.(when click on the TODAY button control goes to current month).
In following code i am showing how to make today button active for current month.
function makeTodaybtnActive()
{
$('#calendar button.fc-today-button').removeAttr('disabled');
$('#calendar button.fc-today-button').removeClass('fc-state-disabled');
}
(where #calendar is fullcalendar id)
call this function when calendar load
$(window).load(function() {
makeTodaybtnActive();
});
Also in eventRender function
$('#calendar').fullCalendar({
eventRender: function(event, element) {
makeTodaybtnActive();
},
});
When calendar load (page load) that time first code work and when change the month and goes to current month (by clicking today button) then second code make Today button active.
| 0debug |
PChart linear chart image quality : <p>I am using PChart to create linear charts. Everything goes well beside the quality of the actual lines drawn.</p>
<p>Of course, antialiasing is <em>not</em> turned off, and even explicitly turned on. </p>
<p>Here is an example of the actual image, which looks quite ugly with all these steps. </p>
<p><a href="https://i.stack.imgur.com/6NRzG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6NRzG.png" alt="enter image description here"></a></p>
<p>Is there a way to make the lines drawn smoother, without stepping?</p>
<p>The code used:</p>
<pre><code>public function linearTwoAxis($data, $fileName, $startColor = 0)
{
$pData = new \pData();
$i = 0;
foreach ($data as $key => $row)
{
$serie = $this->translator->trans("pages.reportDefault.$key");
$pData->addPoints($row, $serie);
$pData->setSerieOnAxis($serie, $i);
$pData->setSerieWeight($serie, 1);
$pData->setAxisName($i, $serie);
$pData->setPalette($serie, $this->colors[$startColor++]);
$pData->setAxisDisplay($i, AXIS_FORMAT_METRIC);
$i++;
}
$monthNames = array_keys($row);
$pData->setAxisPosition(1, AXIS_POSITION_RIGHT);
$pData->addPoints($monthNames, "Labels");
$pData->setAbscissa("Labels");
$pChart = new \pImage(750, 200, $pData);
$pChart->setFontProperties(array(
"FontName" => $this->fonts_dir . "arial.ttf",
"FontSize" => 8)
);
$pChart->setGraphArea(50, 10, 700, 150);
$pChart->Antialias = TRUE;
$pChart->drawScale(["Mode" => SCALE_MODE_START0]);
$pChart->drawLineChart();
$pChart->drawLegend(325,180,array("Style"=>LEGEND_BOX,"Mode"=>LEGEND_HORIZONTAL, "BoxWidth"=>30,"Family"=>LEGEND_FAMILY_LINE,"Alpha" => 0));
$pChart->render($this->target_dir . $fileName);
return $this->target_dirname . $fileName;
}
</code></pre>
| 0debug |
How can I make a Python program do some task at some times of the day? : <p>I want to make a Python program do some task at some times of the day (for example at 12:00, 12:30,13:00, 13:30, etc.) without using sleep(), so the program can make other tasks while it waits.</p>
| 0debug |
Get Weekends between two dates if present in php : <p>Example: <code>$startdate = 01-Aug-2018</code> and <code>$enddate = 04-Aug-2018</code></p>
<p>so, it should return an array with key date and value day name</p>
<pre><code>array(
"04-Aug-2018" => "Sat"
)
</code></pre>
| 0debug |
static int cpu_gdb_read_register(CPUState *env, uint8_t *mem_buf, int n)
{
if (n < 32) {
GET_REGL(env->active_tc.gpr[n]);
}
if (env->CP0_Config1 & (1 << CP0C1_FP)) {
if (n >= 38 && n < 70) {
if (env->CP0_Status & (1 << CP0St_FR))
GET_REGL(env->active_fpu.fpr[n - 38].d);
else
GET_REGL(env->active_fpu.fpr[n - 38].w[FP_ENDIAN_IDX]);
}
switch (n) {
case 70: GET_REGL((int32_t)env->active_fpu.fcr31);
case 71: GET_REGL((int32_t)env->active_fpu.fcr0);
}
}
switch (n) {
case 32: GET_REGL((int32_t)env->CP0_Status);
case 33: GET_REGL(env->active_tc.LO[0]);
case 34: GET_REGL(env->active_tc.HI[0]);
case 35: GET_REGL(env->CP0_BadVAddr);
case 36: GET_REGL((int32_t)env->CP0_Cause);
case 37: GET_REGL(env->active_tc.PC);
case 72: GET_REGL(0);
case 89: GET_REGL((int32_t)env->CP0_PRid);
}
if (n >= 73 && n <= 88) {
GET_REGL(0);
}
return 0;
}
| 1threat |
Add 2 python dictionaries (python 3) : Trying to add 2 python dictionaries in python 3. for example:
dict1 = {'a': 10,'b':20}
dict2 = {'a': 30,'b':30}
expected result:
dict_sum = {'a': 40,'b':50}
Code:
A = Counter (dict1)
B = Counter(dict2)
dict_sum = A + B
Result:
Counter() #empty counter object
Still getting an empty counter object.
I checked on the type of keys and values in A and B, result as following.
<class 'dict_values'>
<class 'dict_keys'>
Please suggest me where am I going wrong.
| 0debug |
static int try_seek_hole(BlockDriverState *bs, off_t start, off_t *data,
off_t *hole)
{
#if defined SEEK_HOLE && defined SEEK_DATA
BDRVRawState *s = bs->opaque;
*hole = lseek(s->fd, start, SEEK_HOLE);
if (*hole == -1) {
return -errno;
}
if (*hole > start) {
*data = start;
} else {
*data = lseek(s->fd, start, SEEK_DATA);
if (*data == -1) {
*data = lseek(s->fd, 0, SEEK_END);
}
}
return 0;
#else
return -ENOTSUP;
#endif
}
| 1threat |
Postgresql: SERIAL incremented on failed constraint INSERT : <p>Having a simple table structure like this:</p>
<pre><code>CREATE TABLE test (
id INT PRIMARY KEY,
sid SERIAL
);
</code></pre>
<p>I noticed if I attempt to insert a row but it fails a constraint test (i.e. PRIMARY KEY constraint), the <code>SERIAL</code> counter will increment anyway, so the next successful insert, <code>sid</code> will be <code>sid + 2</code> instead of <code>sid + 1</code>.</p>
<p>Is this normal behavior? Any way to prevent this?</p>
| 0debug |
ios11 iphone app icon is missing on iPad : <p>I have an iPhone only app but it works in compatibility mode in the iPad too(no surprises). </p>
<p>but after I updated the app for the ios11, app icon on the iPad is missing. </p>
<p>here is what I've tried;
- launch on the iPhone simulator, icon appears
- launch on the iPad simulator, icon is missing</p>
<p>change the device options from "iphone" to "universal", run the iPad simulator, icon appears but app needs a new iPad ui.</p>
<p>change back to "iPhone" and the app icon is missing again in iPad. really confusing. </p>
<p>I tried to create a new project and make the same changes but never able to make the icon missing again. </p>
<p>I'm using cocoa pods if that makes any sense. </p>
<p>I think I'm missing a settings or something else, I'm really trying to find it, any advice would be greatly appreciated.</p>
| 0debug |
What's the time complexity (O(n), O(n^2), etc.) of the algorithm below : <p>Me and my friend were wondering what the time complexity of the below algorithm is. I think it's O(n) but he's saying it's O(n^2). I just wanted second/third/however many opinions</p>
<pre><code>def sorting(seq):
T = BinarySearchTree()
for i in seq: #The insert function is part of the BST class and thus it
T.insert(i) #follows the rules for binary tree insertion.
return inorder(T) #This will return an inorder traversal of the newly
constructed tree
</code></pre>
| 0debug |
What causes the attribute error?[ pygame ] : This code is to create a walking animation.
I dont know is it causing an attribute error.
pls help!
class player(pygame.sprite.Sprite):
def init(self):
pygame.sprite.Sprite.init(self)
self.images = []
for i in range(1, 5):
img = pygame.image.load(os.path.join('Assets','Arts','xeonsheet','xeonsheet_' + str(i) + '.png'))
self.images.append(img)
self.images = self.images[0]
self.images = self.images.get_rect
player = player()
player_list = pygame.sprite.Group()
player_list.add(player)
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/Dreamwind-Chronicles/main.py", line 121, in <module>
player = player()
File "C:/Users/User/PycharmProjects/Dreamwind-Chronicles/main.py", line 117, in init
self.images.append(img)
Attribute Error: 'builtin_function_or_method' object has no attribute 'append'`enter code here`
What is the problem with the code?
| 0debug |
moving data from Model to destination ViewController with segue : I am building a quiz app. The app uses TopicsViewController to select a topic and segue to a QuestionsViewController. The question for the topics are stored as separate swift Objects file. I would like to pick the Topic1 Question file when I press the topic1 button in TopicsViewController to segue into the QuestionsViewController. What I would like to know is how can I select the particular questions file when I select the particular topic upon segueing to the QuestionsViewController? | 0debug |
JQuery: How to select first td compared to the clicked td : ***Hello*** it will have been very easy if the selector was juste < tr> like this : $('tr')
But i target td
(for example click here or td 2 etc ...) and I want to have the content of the first td compared to the ***clicked td***
that is to say td 1 in this case.
this is my html code
<tr>
<td class="id"> td 1 </td>
<td> td 2 </td>
<td> td 3 </td>
<td> CLICK HERE </td>
</tr>
And this is my jQuery code with < tr> .. what about if a select was a < td> ?
$('tr').on('click',function()
{
var tds = $('td:first-child', this).text();
alert(tds);
});
After having documented I found this
but that did not help :(
var td1 = $(this).closest('td.id').prev('').text();
alert(td1);
Thank you in advance | 0debug |
PXA2xxState *pxa270_init(MemoryRegion *address_space,
unsigned int sdram_size, const char *revision)
{
PXA2xxState *s;
int i;
DriveInfo *dinfo;
s = (PXA2xxState *) g_malloc0(sizeof(PXA2xxState));
if (revision && strncmp(revision, "pxa27", 5)) {
fprintf(stderr, "Machine requires a PXA27x processor.\n");
exit(1);
}
if (!revision)
revision = "pxa270";
s->cpu = cpu_arm_init(revision);
if (s->cpu == NULL) {
fprintf(stderr, "Unable to find CPU definition\n");
exit(1);
}
s->reset = qemu_allocate_irq(pxa2xx_reset, s, 0);
memory_region_init_ram(&s->sdram, NULL, "pxa270.sdram", sdram_size,
&error_abort);
vmstate_register_ram_global(&s->sdram);
memory_region_add_subregion(address_space, PXA2XX_SDRAM_BASE, &s->sdram);
memory_region_init_ram(&s->internal, NULL, "pxa270.internal", 0x40000,
&error_abort);
vmstate_register_ram_global(&s->internal);
memory_region_add_subregion(address_space, PXA2XX_INTERNAL_BASE,
&s->internal);
s->pic = pxa2xx_pic_init(0x40d00000, s->cpu);
s->dma = pxa27x_dma_init(0x40000000,
qdev_get_gpio_in(s->pic, PXA2XX_PIC_DMA));
sysbus_create_varargs("pxa27x-timer", 0x40a00000,
qdev_get_gpio_in(s->pic, PXA2XX_PIC_OST_0 + 0),
qdev_get_gpio_in(s->pic, PXA2XX_PIC_OST_0 + 1),
qdev_get_gpio_in(s->pic, PXA2XX_PIC_OST_0 + 2),
qdev_get_gpio_in(s->pic, PXA2XX_PIC_OST_0 + 3),
qdev_get_gpio_in(s->pic, PXA27X_PIC_OST_4_11),
NULL);
s->gpio = pxa2xx_gpio_init(0x40e00000, s->cpu, s->pic, 121);
dinfo = drive_get(IF_SD, 0, 0);
if (!dinfo) {
fprintf(stderr, "qemu: missing SecureDigital device\n");
exit(1);
}
s->mmc = pxa2xx_mmci_init(address_space, 0x41100000,
blk_bs(blk_by_legacy_dinfo(dinfo)),
qdev_get_gpio_in(s->pic, PXA2XX_PIC_MMC),
qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_MMCI),
qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_MMCI));
for (i = 0; pxa270_serial[i].io_base; i++) {
if (serial_hds[i]) {
serial_mm_init(address_space, pxa270_serial[i].io_base, 2,
qdev_get_gpio_in(s->pic, pxa270_serial[i].irqn),
14857000 / 16, serial_hds[i],
DEVICE_NATIVE_ENDIAN);
} else {
break;
}
}
if (serial_hds[i])
s->fir = pxa2xx_fir_init(address_space, 0x40800000,
qdev_get_gpio_in(s->pic, PXA2XX_PIC_ICP),
qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_ICP),
qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_ICP),
serial_hds[i]);
s->lcd = pxa2xx_lcdc_init(address_space, 0x44000000,
qdev_get_gpio_in(s->pic, PXA2XX_PIC_LCD));
s->cm_base = 0x41300000;
s->cm_regs[CCCR >> 2] = 0x02000210;
s->clkcfg = 0x00000009;
memory_region_init_io(&s->cm_iomem, NULL, &pxa2xx_cm_ops, s, "pxa2xx-cm", 0x1000);
memory_region_add_subregion(address_space, s->cm_base, &s->cm_iomem);
vmstate_register(NULL, 0, &vmstate_pxa2xx_cm, s);
pxa2xx_setup_cp14(s);
s->mm_base = 0x48000000;
s->mm_regs[MDMRS >> 2] = 0x00020002;
s->mm_regs[MDREFR >> 2] = 0x03ca4000;
s->mm_regs[MECR >> 2] = 0x00000001;
memory_region_init_io(&s->mm_iomem, NULL, &pxa2xx_mm_ops, s, "pxa2xx-mm", 0x1000);
memory_region_add_subregion(address_space, s->mm_base, &s->mm_iomem);
vmstate_register(NULL, 0, &vmstate_pxa2xx_mm, s);
s->pm_base = 0x40f00000;
memory_region_init_io(&s->pm_iomem, NULL, &pxa2xx_pm_ops, s, "pxa2xx-pm", 0x100);
memory_region_add_subregion(address_space, s->pm_base, &s->pm_iomem);
vmstate_register(NULL, 0, &vmstate_pxa2xx_pm, s);
for (i = 0; pxa27x_ssp[i].io_base; i ++);
s->ssp = (SSIBus **)g_malloc0(sizeof(SSIBus *) * i);
for (i = 0; pxa27x_ssp[i].io_base; i ++) {
DeviceState *dev;
dev = sysbus_create_simple(TYPE_PXA2XX_SSP, pxa27x_ssp[i].io_base,
qdev_get_gpio_in(s->pic, pxa27x_ssp[i].irqn));
s->ssp[i] = (SSIBus *)qdev_get_child_bus(dev, "ssi");
}
if (usb_enabled(false)) {
sysbus_create_simple("sysbus-ohci", 0x4c000000,
qdev_get_gpio_in(s->pic, PXA2XX_PIC_USBH1));
}
s->pcmcia[0] = pxa2xx_pcmcia_init(address_space, 0x20000000);
s->pcmcia[1] = pxa2xx_pcmcia_init(address_space, 0x30000000);
sysbus_create_simple(TYPE_PXA2XX_RTC, 0x40900000,
qdev_get_gpio_in(s->pic, PXA2XX_PIC_RTCALARM));
s->i2c[0] = pxa2xx_i2c_init(0x40301600,
qdev_get_gpio_in(s->pic, PXA2XX_PIC_I2C), 0xffff);
s->i2c[1] = pxa2xx_i2c_init(0x40f00100,
qdev_get_gpio_in(s->pic, PXA2XX_PIC_PWRI2C), 0xff);
s->i2s = pxa2xx_i2s_init(address_space, 0x40400000,
qdev_get_gpio_in(s->pic, PXA2XX_PIC_I2S),
qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_I2S),
qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_I2S));
s->kp = pxa27x_keypad_init(address_space, 0x41500000,
qdev_get_gpio_in(s->pic, PXA2XX_PIC_KEYPAD));
qdev_connect_gpio_out(s->gpio, 1, s->reset);
return s;
}
| 1threat |
comparing sub-list elements in list using python : <p>i have a list a=[[1,2],[3,4],[5,6]] and i need to check if all elements in sublist are in ascending order (e.g [1,2] is less than [3,4] and [5,6], and [3,4] is less than [5,6] and so on).
i use the following function:</p>
<pre><code>def FirstRuleLink (L):
for i in range(0,len(L)):
for j in range(0,len(L[i])):
if L[i][0]<L[i+1][0] and L[i][1]<L[i+1][1]:
return True
else:
return False
</code></pre>
<p>but the python gives me error message that index is out of range. so how could i change this code to get the correct output.</p>
| 0debug |
How do I prevent downloading media on the website? : <p>I have a website where I put music, but I do not want anyone downloading it, or it gets harder and just listening online, like YouTube.</p>
| 0debug |
Jsoup response coming up as an empty page? : Im trying to connect to a website at Jsoup.connect(http://...php)
and it is returning
<html>
<head></head>
<body></body>
</html>
is it because the page is .php? and not .html
| 0debug |
Find specific word in array of strings In python : I have two lists one with Strings And other With Words To be Found lets say :
list1=['Hi I am Tayyab','I am a python programmer', 'I am new To python' ]
list2=['Tayyab','Programmer']
I want to check if list 1 contains the words present in list 2
if yes then return the complete string present in list 1.
In the Above case I want the first two items in list 1 to be returned because first two items contain the Word 'Tayyab' and 'Programmer'. | 0debug |
Best Practice in Error Handling in Vuejs With Vuex and Axios : <p>I am using Vuex + axios, I want to know the best practice in handling errors for vuex + axios. What I am doing now is that when I request using axios and it returns an error, it will be committed in mutation and update my state. What I want to do is, If there's an response error from my request it will return to my component so that I can handle the error much faster.</p>
<p>Like in angular, there's a dependency injection and the response will return to the component.</p>
| 0debug |
Android Studio 3.0 Preview - Studio does not have write access : <p>I'm using Android Studio 3.0 Canary 1. I'm trying to update it to Android Studio 3.0 Canary 2 but it shows the following error:</p>
<blockquote>
<p>Studio does not have write access to /private/var/folders/mk/h5qpw_r11_7ggh9q52n9hhlr0000gn/T/AppTranslocation/1321881E-C41D-4AF7-B207-F31894226D50/d/Android Studio 3.0 Preview.app/Contents. Please run it by a privileged user to update.</p>
</blockquote>
<p>I even tried running Android studio with sudo from the command line:</p>
<pre><code>sudo /Applications/Android\ Studio 3.0 Preview.app/Contents/MacOS/studio
</code></pre>
<p>But it didn't work. Any help will be much appreciated.</p>
| 0debug |
int event_notifier_set_handler(EventNotifier *e,
EventNotifierHandler *handler)
{
return qemu_set_fd_handler(e->fd, (IOHandler *)handler, NULL, e);
}
| 1threat |
static int nbd_handle_reply_err(QIOChannel *ioc, nbd_opt_reply *reply,
Error **errp)
{
char *msg = NULL;
int result = -1;
if (!(reply->type & (1 << 31))) {
return 1;
}
if (reply->length) {
if (reply->length > NBD_MAX_BUFFER_SIZE) {
error_setg(errp, "server error 0x%" PRIx32
" (%s) message is too long",
reply->type, nbd_rep_lookup(reply->type));
goto cleanup;
}
msg = g_malloc(reply->length + 1);
if (nbd_read(ioc, msg, reply->length, errp) < 0) {
error_prepend(errp, "failed to read option error 0x%" PRIx32
" (%s) message",
reply->type, nbd_rep_lookup(reply->type));
goto cleanup;
}
msg[reply->length] = '\0';
}
switch (reply->type) {
case NBD_REP_ERR_UNSUP:
trace_nbd_reply_err_unsup(reply->option, nbd_opt_lookup(reply->option));
result = 0;
goto cleanup;
case NBD_REP_ERR_POLICY:
error_setg(errp, "Denied by server for option %" PRIx32 " (%s)",
reply->option, nbd_opt_lookup(reply->option));
break;
case NBD_REP_ERR_INVALID:
error_setg(errp, "Invalid data length for option %" PRIx32 " (%s)",
reply->option, nbd_opt_lookup(reply->option));
break;
case NBD_REP_ERR_PLATFORM:
error_setg(errp, "Server lacks support for option %" PRIx32 " (%s)",
reply->option, nbd_opt_lookup(reply->option));
break;
case NBD_REP_ERR_TLS_REQD:
error_setg(errp, "TLS negotiation required before option %" PRIx32
" (%s)", reply->option, nbd_opt_lookup(reply->option));
break;
case NBD_REP_ERR_UNKNOWN:
error_setg(errp, "Requested export not available for option %" PRIx32
" (%s)", reply->option, nbd_opt_lookup(reply->option));
break;
case NBD_REP_ERR_SHUTDOWN:
error_setg(errp, "Server shutting down before option %" PRIx32 " (%s)",
reply->option, nbd_opt_lookup(reply->option));
break;
case NBD_REP_ERR_BLOCK_SIZE_REQD:
error_setg(errp, "Server requires INFO_BLOCK_SIZE for option %" PRIx32
" (%s)", reply->option, nbd_opt_lookup(reply->option));
break;
default:
error_setg(errp, "Unknown error code when asking for option %" PRIx32
" (%s)", reply->option, nbd_opt_lookup(reply->option));
break;
}
if (msg) {
error_append_hint(errp, "%s\n", msg);
}
cleanup:
g_free(msg);
if (result < 0) {
nbd_send_opt_abort(ioc);
}
return result;
}
| 1threat |
Specific code from SAS to R : <p>I am trying to write this (SAS) comand in R. x is a variable with this specific format: j61915035t</p>
<p>x1 = trim(upcase(substr(x,1,1)));</p>
<p>I really appreciate what you are doing in this site!</p>
| 0debug |
static inline int parse_command_line(AVFormatContext *s, const char *line,
int linelen, char *uri, int urisize,
char *method, int methodsize,
enum RTSPMethod *methodcode)
{
RTSPState *rt = s->priv_data;
const char *linept, *searchlinept;
linept = strchr(line, ' ');
if (linept - line > methodsize - 1) {
av_log(s, AV_LOG_ERROR, "Method string too long\n");
return AVERROR(EIO);
}
memcpy(method, line, linept - line);
method[linept - line] = '\0';
linept++;
if (!strcmp(method, "ANNOUNCE"))
*methodcode = ANNOUNCE;
else if (!strcmp(method, "OPTIONS"))
*methodcode = OPTIONS;
else if (!strcmp(method, "RECORD"))
*methodcode = RECORD;
else if (!strcmp(method, "SETUP"))
*methodcode = SETUP;
else if (!strcmp(method, "PAUSE"))
*methodcode = PAUSE;
else if (!strcmp(method, "TEARDOWN"))
*methodcode = TEARDOWN;
else
*methodcode = UNKNOWN;
if (rt->state == RTSP_STATE_IDLE) {
if ((*methodcode != ANNOUNCE) && (*methodcode != OPTIONS)) {
av_log(s, AV_LOG_ERROR, "Unexpected command in Idle State %s\n",
line);
return AVERROR_PROTOCOL_NOT_FOUND;
}
} else if (rt->state == RTSP_STATE_PAUSED) {
if ((*methodcode != OPTIONS) && (*methodcode != RECORD)
&& (*methodcode != SETUP)) {
av_log(s, AV_LOG_ERROR, "Unexpected command in Paused State %s\n",
line);
return AVERROR_PROTOCOL_NOT_FOUND;
}
} else if (rt->state == RTSP_STATE_STREAMING) {
if ((*methodcode != PAUSE) && (*methodcode != OPTIONS)
&& (*methodcode != TEARDOWN)) {
av_log(s, AV_LOG_ERROR, "Unexpected command in Streaming State"
" %s\n", line);
return AVERROR_PROTOCOL_NOT_FOUND;
}
} else {
av_log(s, AV_LOG_ERROR, "Unexpected State [%d]\n", rt->state);
return AVERROR_BUG;
}
searchlinept = strchr(linept, ' ');
if (!searchlinept) {
av_log(s, AV_LOG_ERROR, "Error parsing message URI\n");
}
if (searchlinept - linept > urisize - 1) {
av_log(s, AV_LOG_ERROR, "uri string length exceeded buffer size\n");
return AVERROR(EIO);
}
memcpy(uri, linept, searchlinept - linept);
uri[searchlinept - linept] = '\0';
if (strcmp(rt->control_uri, uri)) {
char host[128], path[512], auth[128];
int port;
char ctl_host[128], ctl_path[512], ctl_auth[128];
int ctl_port;
av_url_split(NULL, 0, auth, sizeof(auth), host, sizeof(host), &port,
path, sizeof(path), uri);
av_url_split(NULL, 0, ctl_auth, sizeof(ctl_auth), ctl_host,
sizeof(ctl_host), &ctl_port, ctl_path, sizeof(ctl_path),
rt->control_uri);
if (strcmp(host, ctl_host))
av_log(s, AV_LOG_INFO, "Host %s differs from expected %s\n",
host, ctl_host);
if (strcmp(path, ctl_path) && *methodcode != SETUP)
av_log(s, AV_LOG_WARNING, "WARNING: Path %s differs from expected"
" %s\n", path, ctl_path);
if (*methodcode == ANNOUNCE) {
av_log(s, AV_LOG_INFO,
"Updating control URI to %s\n", uri);
av_strlcpy(rt->control_uri, uri, sizeof(rt->control_uri));
}
}
linept = searchlinept + 1;
if (!av_strstart(linept, "RTSP/1.0", NULL)) {
av_log(s, AV_LOG_ERROR, "Error parsing protocol or version\n");
return AVERROR_PROTOCOL_NOT_FOUND;
}
return 0;
} | 1threat |
static int film_read_packet(AVFormatContext *s,
AVPacket *pkt)
{
FilmDemuxContext *film = s->priv_data;
AVIOContext *pb = s->pb;
film_sample *sample;
int ret = 0;
int i;
int left, right;
if (film->current_sample >= film->sample_count)
sample = &film->sample_table[film->current_sample];
avio_seek(pb, sample->sample_offset, SEEK_SET);
if ((sample->stream == film->video_stream_index) &&
(film->video_type == CODEC_ID_CINEPAK)) {
pkt->pos= avio_tell(pb);
if (av_new_packet(pkt, sample->sample_size))
return AVERROR(ENOMEM);
avio_read(pb, pkt->data, sample->sample_size);
} else if ((sample->stream == film->audio_stream_index) &&
(film->audio_channels == 2) &&
(film->audio_type != CODEC_ID_ADPCM_ADX)) {
if (av_new_packet(pkt, sample->sample_size))
return AVERROR(ENOMEM);
if (sample->sample_size > film->stereo_buffer_size) {
av_free(film->stereo_buffer);
film->stereo_buffer_size = sample->sample_size;
film->stereo_buffer = av_malloc(film->stereo_buffer_size);
if (!film->stereo_buffer) {
film->stereo_buffer_size = 0;
return AVERROR(ENOMEM);
}
}
pkt->pos= avio_tell(pb);
ret = avio_read(pb, film->stereo_buffer, sample->sample_size);
if (ret != sample->sample_size)
ret = AVERROR(EIO);
left = 0;
right = sample->sample_size / 2;
for (i = 0; i < sample->sample_size; ) {
if (film->audio_bits == 8) {
pkt->data[i++] = film->stereo_buffer[left++];
pkt->data[i++] = film->stereo_buffer[right++];
} else {
pkt->data[i++] = film->stereo_buffer[left++];
pkt->data[i++] = film->stereo_buffer[left++];
pkt->data[i++] = film->stereo_buffer[right++];
pkt->data[i++] = film->stereo_buffer[right++];
}
}
} else {
ret= av_get_packet(pb, pkt, sample->sample_size);
if (ret != sample->sample_size)
ret = AVERROR(EIO);
}
pkt->stream_index = sample->stream;
pkt->pts = sample->pts;
film->current_sample++;
return ret;
} | 1threat |
how do i backup a database in docker : <p>i'm running my app using docker-compose with the below yml file</p>
<pre><code> postgres:
container_name: postgres
image: postgres:${POSTGRES_VERSION}
volumes:
- postgresdata:/var/lib/postgresql/data
expose:
- "5432"
environment:
- POSTGRES_DB=42EXP
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
node:
container_name: node
links:
- postgres:postgres
depends_on:
- postgres
volumes:
postgresdata:
</code></pre>
<p>As you can see here ,i'm using a <code>named volume</code> to manage postgres state.</p>
<p>According to the official docs, i can backup a volume like the below</p>
<pre><code>docker run --rm --volumes postgresdata:/var/lib/postgresql/data -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /dbdata
</code></pre>
<p>Some other tutorials suggested i use the <code>pg-dump</code> function provided by postgres for backups.</p>
<pre><code>pg_dump -Fc database_name_here > database.bak
</code></pre>
<p>I guess i would have to go inside the postgres container to perform this function and mount the backup directory to the host.</p>
<p>Is one approach better/preferable than the other?</p>
| 0debug |
Visual Studio, Python not auto-indenting : <p>This is probably a simple issue but something is wrong with my Python tools for visual studio. When I first started using VS2015 for Python it would auto-indent whenever I used a colon. Now VS2015 is just acting like a text editor with syntax highlighting. I tried uninstalling and reinstalling the Python tools but that did not work. How do I fix Visual Studio to auto-style as I write Python again?</p>
| 0debug |
static void ra144_encode_subblock(RA144Context *ractx,
const int16_t *sblock_data,
const int16_t *lpc_coefs, unsigned int rms,
PutBitContext *pb)
{
float data[BLOCKSIZE] = { 0 }, work[LPC_ORDER + BLOCKSIZE];
float coefs[LPC_ORDER];
float zero[BLOCKSIZE], cba[BLOCKSIZE], cb1[BLOCKSIZE], cb2[BLOCKSIZE];
int16_t cba_vect[BLOCKSIZE];
int cba_idx, cb1_idx, cb2_idx, gain;
int i, n;
unsigned m[3];
float g[3];
float error, best_error;
for (i = 0; i < LPC_ORDER; i++) {
work[i] = ractx->curr_sblock[BLOCKSIZE + i];
coefs[i] = lpc_coefs[i] * (1/4096.0);
}
ff_celp_lp_synthesis_filterf(work + LPC_ORDER, coefs, data, BLOCKSIZE,
LPC_ORDER);
for (i = 0; i < BLOCKSIZE; i++) {
zero[i] = work[LPC_ORDER + i];
data[i] = sblock_data[i] - zero[i];
}
memset(work, 0, LPC_ORDER * sizeof(*work));
cba_idx = adaptive_cb_search(ractx->adapt_cb, work + LPC_ORDER, coefs,
data);
if (cba_idx) {
memcpy(cba, work + LPC_ORDER, sizeof(cba));
ff_copy_and_dup(cba_vect, ractx->adapt_cb, cba_idx + BLOCKSIZE / 2 - 1);
m[0] = (ff_irms(cba_vect) * rms) >> 12;
}
fixed_cb_search(work + LPC_ORDER, coefs, data, cba_idx, &cb1_idx, &cb2_idx);
for (i = 0; i < BLOCKSIZE; i++) {
cb1[i] = ff_cb1_vects[cb1_idx][i];
cb2[i] = ff_cb2_vects[cb2_idx][i];
}
ff_celp_lp_synthesis_filterf(work + LPC_ORDER, coefs, cb1, BLOCKSIZE,
LPC_ORDER);
memcpy(cb1, work + LPC_ORDER, sizeof(cb1));
m[1] = (ff_cb1_base[cb1_idx] * rms) >> 8;
ff_celp_lp_synthesis_filterf(work + LPC_ORDER, coefs, cb2, BLOCKSIZE,
LPC_ORDER);
memcpy(cb2, work + LPC_ORDER, sizeof(cb2));
m[2] = (ff_cb2_base[cb2_idx] * rms) >> 8;
best_error = FLT_MAX;
gain = 0;
for (n = 0; n < 256; n++) {
g[1] = ((ff_gain_val_tab[n][1] * m[1]) >> ff_gain_exp_tab[n]) *
(1/4096.0);
g[2] = ((ff_gain_val_tab[n][2] * m[2]) >> ff_gain_exp_tab[n]) *
(1/4096.0);
error = 0;
if (cba_idx) {
g[0] = ((ff_gain_val_tab[n][0] * m[0]) >> ff_gain_exp_tab[n]) *
(1/4096.0);
for (i = 0; i < BLOCKSIZE; i++) {
data[i] = zero[i] + g[0] * cba[i] + g[1] * cb1[i] +
g[2] * cb2[i];
error += (data[i] - sblock_data[i]) *
(data[i] - sblock_data[i]);
}
} else {
for (i = 0; i < BLOCKSIZE; i++) {
data[i] = zero[i] + g[1] * cb1[i] + g[2] * cb2[i];
error += (data[i] - sblock_data[i]) *
(data[i] - sblock_data[i]);
}
}
if (error < best_error) {
best_error = error;
gain = n;
}
}
put_bits(pb, 7, cba_idx);
put_bits(pb, 8, gain);
put_bits(pb, 7, cb1_idx);
put_bits(pb, 7, cb2_idx);
ff_subblock_synthesis(ractx, lpc_coefs, cba_idx, cb1_idx, cb2_idx, rms,
gain);
}
| 1threat |
How does Math.tan(x) actually work? (Javascript) : <p>I'm trying to understand the math behind the Math.tan method but it doesn't make any sense. Can someone please explain to me how it works?</p>
<p>Firstly the mathematical formula to solve for a tangent angle is Tangent = Opposite/Adjacent. Which means I need to know two sides of the triangle to figure out the tangent angle. However the Math.tan method only accept a single argument in radians, not the length of two sides, so I don't understand how it's figuring out the angle of the tangent. </p>
<p>Next in examples they show passing impossibly huge radian values into the method and getting back a value. For example, W3 schools shows the example of <code>Math.tan(90)</code> but 90 radians equals 5,156.6 degrees which is an impossible angle for a corner of a right triangle.</p>
<p>How does this method work, what's happening behind the scenes that turns 90 radians into a tangent angle of -1.995200412208242 </p>
| 0debug |
static int execute_decode_slices(H264Context *h, int context_count)
{
MpegEncContext *const s = &h->s;
AVCodecContext *const avctx = s->avctx;
H264Context *hx;
int i;
if (s->avctx->hwaccel ||
s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
return 0;
if (context_count == 1) {
return decode_slice(avctx, &h);
} else {
for (i = 1; i < context_count; i++) {
hx = h->thread_context[i];
hx->s.err_recognition = avctx->err_recognition;
hx->s.error_count = 0;
hx->x264_build = h->x264_build;
}
avctx->execute(avctx, decode_slice, h->thread_context,
NULL, context_count, sizeof(void *));
hx = h->thread_context[context_count - 1];
s->mb_x = hx->s.mb_x;
s->mb_y = hx->s.mb_y;
s->droppable = hx->s.droppable;
s->picture_structure = hx->s.picture_structure;
for (i = 1; i < context_count; i++)
h->s.error_count += h->thread_context[i]->s.error_count;
}
return 0;
} | 1threat |
int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
AVFrame *frame,
int *got_frame_ptr,
const AVPacket *avpkt)
{
AVCodecInternal *avci = avctx->internal;
int planar, channels;
int ret = 0;
*got_frame_ptr = 0;
if (!avpkt->data && avpkt->size) {
av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
}
if (avctx->codec->type != AVMEDIA_TYPE_AUDIO) {
av_log(avctx, AV_LOG_ERROR, "Invalid media type for audio\n");
}
avcodec_get_frame_defaults(frame);
if (!avctx->refcounted_frames)
av_frame_unref(&avci->to_free);
if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
uint8_t *side;
int side_size;
AVPacket tmp = *avpkt;
int did_split = av_packet_split_side_data(&tmp);
apply_param_change(avctx, &tmp);
avctx->pkt = &tmp;
if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
ret = ff_thread_decode_frame(avctx, frame, got_frame_ptr, &tmp);
else {
ret = avctx->codec->decode(avctx, frame, got_frame_ptr, &tmp);
frame->pkt_dts = avpkt->dts;
}
if (ret >= 0 && *got_frame_ptr) {
add_metadata_from_side_data(avctx, frame);
avctx->frame_number++;
av_frame_set_best_effort_timestamp(frame,
guess_correct_pts(avctx,
frame->pkt_pts,
frame->pkt_dts));
if (frame->format == AV_SAMPLE_FMT_NONE)
frame->format = avctx->sample_fmt;
if (!frame->channel_layout)
frame->channel_layout = avctx->channel_layout;
if (!av_frame_get_channels(frame))
av_frame_set_channels(frame, avctx->channels);
if (!frame->sample_rate)
frame->sample_rate = avctx->sample_rate;
}
side= av_packet_get_side_data(avctx->pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
if(side && side_size>=10) {
avctx->internal->skip_samples = AV_RL32(side);
av_log(avctx, AV_LOG_DEBUG, "skip %d samples due to side data\n",
avctx->internal->skip_samples);
}
if (avctx->internal->skip_samples && *got_frame_ptr) {
if(frame->nb_samples <= avctx->internal->skip_samples){
*got_frame_ptr = 0;
avctx->internal->skip_samples -= frame->nb_samples;
av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
avctx->internal->skip_samples);
} else {
av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
if(avctx->pkt_timebase.num && avctx->sample_rate) {
int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
(AVRational){1, avctx->sample_rate},
avctx->pkt_timebase);
if(frame->pkt_pts!=AV_NOPTS_VALUE)
frame->pkt_pts += diff_ts;
if(frame->pkt_dts!=AV_NOPTS_VALUE)
frame->pkt_dts += diff_ts;
if (av_frame_get_pkt_duration(frame) >= diff_ts)
av_frame_set_pkt_duration(frame, av_frame_get_pkt_duration(frame) - diff_ts);
} else {
av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
}
av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
avctx->internal->skip_samples, frame->nb_samples);
frame->nb_samples -= avctx->internal->skip_samples;
avctx->internal->skip_samples = 0;
}
}
avctx->pkt = NULL;
if (did_split) {
ff_packet_free_side_data(&tmp);
if(ret == tmp.size)
ret = avpkt->size;
}
if (ret >= 0 && *got_frame_ptr) {
if (!avctx->refcounted_frames) {
avci->to_free = *frame;
avci->to_free.extended_data = avci->to_free.data;
memset(frame->buf, 0, sizeof(frame->buf));
frame->extended_buf = NULL;
frame->nb_extended_buf = 0;
}
} else if (frame->data[0])
av_frame_unref(frame);
}
if (*got_frame_ptr) {
planar = av_sample_fmt_is_planar(frame->format);
channels = av_frame_get_channels(frame);
if (!(planar && channels > AV_NUM_DATA_POINTERS))
frame->extended_data = frame->data;
} else {
frame->extended_data = NULL;
}
return ret;
} | 1threat |
static void hb_regs_write(void *opaque, hwaddr offset,
uint64_t value, unsigned size)
{
uint32_t *regs = opaque;
if (offset == 0xf00) {
if (value == 1 || value == 2) {
qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
} else if (value == 3) {
qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
}
}
regs[offset/4] = value;
}
| 1threat |
pvscsi_on_cmd_setup_rings(PVSCSIState *s)
{
PVSCSICmdDescSetupRings *rc =
(PVSCSICmdDescSetupRings *) s->curr_cmd_data;
trace_pvscsi_on_cmd_arrived("PVSCSI_CMD_SETUP_RINGS");
pvscsi_dbg_dump_tx_rings_config(rc);
pvscsi_ring_init_data(&s->rings, rc);
s->rings_info_valid = TRUE;
return PVSCSI_COMMAND_PROCESSING_SUCCEEDED;
}
| 1threat |
Laravel 5.4 LengthAwarePaginator : <p>My brain suddenly crashed on this one. Anyone care to help me is highly appreciated.</p>
<p>This is LengthAwarepaginator in laravel 5.4</p>
<p>Here is the code.</p>
<pre><code>$collection = [];
foreach ($maincategories->merchantCategory as $merchantCat) {
foreach ($merchantCat->merchantSubcategory as $merchantSub) {
foreach($merchantSub->products as $products){
$collection[] = $products;
}
}
}
$paginate = new LengthAwarePaginator($collection, count($collection), 10, 1, ['path'=>url('api/products')]);
dd($paginate);
</code></pre>
<p>It displays perfectly but the problem is the items is 100. That's all my items and I specify it correctly. I need to display only 10.</p>
<p>Base on LengthAwarePaginator constructor. Here is the reference.</p>
<pre><code>public function __construct($items, $total, $perPage, $currentPage = null, array $options = [])
</code></pre>
<p>Here is the screen shot.</p>
<p><a href="https://i.stack.imgur.com/nUNHk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nUNHk.png" alt="enter image description here"></a></p>
<p>Where did I go wrong? TY</p>
| 0debug |
static int mxf_read_generic_descriptor(MXFDescriptor *descriptor, ByteIOContext *pb, int tag, int size, UID uid)
{
switch(tag) {
case 0x3F01:
descriptor->sub_descriptors_count = get_be32(pb);
if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
return -1;
descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
if (!descriptor->sub_descriptors_refs)
return -1;
url_fskip(pb, 4);
get_buffer(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
break;
case 0x3004:
get_buffer(pb, descriptor->essence_container_ul, 16);
break;
case 0x3006:
descriptor->linked_track_id = get_be32(pb);
break;
case 0x3201:
get_buffer(pb, descriptor->essence_codec_ul, 16);
break;
case 0x3203:
descriptor->width = get_be32(pb);
break;
case 0x3202:
descriptor->height = get_be32(pb);
break;
case 0x320E:
descriptor->aspect_ratio.num = get_be32(pb);
descriptor->aspect_ratio.den = get_be32(pb);
break;
case 0x3D03:
descriptor->sample_rate.num = get_be32(pb);
descriptor->sample_rate.den = get_be32(pb);
break;
case 0x3D06:
get_buffer(pb, descriptor->essence_codec_ul, 16);
break;
case 0x3D07:
descriptor->channels = get_be32(pb);
break;
case 0x3D01:
descriptor->bits_per_sample = get_be32(pb);
break;
case 0x3401:
mxf_read_pixel_layout(pb, descriptor);
break;
default:
if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
descriptor->extradata = av_malloc(size);
if (!descriptor->extradata)
return -1;
descriptor->extradata_size = size;
get_buffer(pb, descriptor->extradata, size);
}
break;
}
return 0;
}
| 1threat |
Can not parse json file in go : <p>I'm trying to parse a json file using GoLang but it seems like not work. Am I doing right?</p>
<p>this is my Go Code:</p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"encoding/json"
"fmt"
"io/ioutil"
)
type info struct {
username string `json:"username"`
password string `json:"password"`
timedelay int `json:"timedelay"`
courselist []string `json:"courselist"`
}
func main() {
var jsonParse info
file, err := ioutil.ReadFile("info.json")
if err != nil {
fmt.Println(err)
}
fmt.Println("My file content is:\n", string(file))
fmt.Println("---------------Parsing Json File----------------")
json.Unmarshal(file, &jsonParse)
fmt.Println("My Json Parse is:\n", jsonParse)
}
</code></pre>
<p>and this is my json file</p>
<pre><code>{
"username" : "17020726",
"password": "Blueflower",
"timedelay": 200,
"courselist": ["54"]
}
</code></pre>
<p>this is result of my code</p>
<pre><code>My file content is:
{
"username" : "17020726",
"password": "Blueflower",
"timedelay": 200,
"courselist": ["54"]
}
---------------Parsing Json File----------------
My Json Parse is:
{ 0 []}
</code></pre>
| 0debug |
static void quantize_and_encode_band_mips(struct AACEncContext *s, PutBitContext *pb,
const float *in, float *out, int size, int scale_idx,
int cb, const float lambda, int rtz)
{
quantize_and_encode_band_cost(s, pb, in, out, NULL, size, scale_idx, cb, lambda,
INFINITY, NULL, (rtz) ? ROUND_TO_ZERO : ROUND_STANDARD);
}
| 1threat |
int cpu_get_dump_info(ArchDumpInfo *info,
const GuestPhysBlockList *guest_phys_blocks)
{
bool lma = false;
GuestPhysBlock *block;
#ifdef TARGET_X86_64
X86CPU *first_x86_cpu = X86_CPU(first_cpu);
lma = !!(first_x86_cpu->env.hflags & HF_LMA_MASK);
#endif
if (lma) {
info->d_machine = EM_X86_64;
} else {
info->d_machine = EM_386;
}
info->d_endian = ELFDATA2LSB;
if (lma) {
info->d_class = ELFCLASS64;
} else {
info->d_class = ELFCLASS32;
QTAILQ_FOREACH(block, &guest_phys_blocks->head, next) {
if (block->target_end > UINT_MAX) {
info->d_class = ELFCLASS64;
break;
}
}
}
return 0;
}
| 1threat |
Add comma in number after every thousand on event of "Enter" in a text box using Angular JS : <p>This is a question from Angular JS.
I need to add "comma" after every thousand on event of enter in a text box.
Like, if enter a number 1000000 in a text box and hit"Enter" button, text box should now show the value 1,000,000</p>
<p>I am trying to do it using a directive.Please tell me how can I do it. </p>
| 0debug |
How to efficiently retrieve the indices of maximum values in a Torch tensor? : <p>Assume to have a torch tensor, for example of the following shape:</p>
<pre><code>x = torch.rand(20, 1, 120, 120)
</code></pre>
<p>What I would like now, is to get the indices of the maximum values of each 120x120 matrix. To simplify the problem I would first <code>x.squeeze()</code> to work with shape <code>[20, 120, 120]</code>. I would then like to get torch tensor which is a list of indices with shape <code>[20, 2]</code>.</p>
<p>How can I do this fast?</p>
| 0debug |
snippet for creating object from destructured array : <p>For example, I had an array with 3 numbers:</p>
<pre><code>var arr = [124, -50, 24];
</code></pre>
<p>and I need to convert this array to the object:</p>
<pre><code>{
x: 124,
y: -50,
z: 24
}
</code></pre>
<p>I don`t want to use "old-style" syntax for this, for example:</p>
<pre><code>{
x: arr[0],
y: arr[1],
z: arr[2]
}
</code></pre>
<p>so for now, I`m using that syntax:</p>
<pre><code>const [x, y, z] = [...arr];
const obj = {x, y, z};
</code></pre>
<p>But, is there is any way to do this with a straight dectructuring array to object without need of temporary variables?</p>
| 0debug |
Am I allowed to make circular references with constants structs? : <p>Am I allowed to do this in C99? </p>
<pre><code>typedef struct dlNode {
dlNode* next,prev;
void* datum;
} dlNode;
const static dlNode head={
.next=&tail,
.prev=NULL,
.datum=NULL
};
const static dlNode tail={
.next=NULL,
.prev=&head,
.datum=NULL
};
</code></pre>
<p>I can make my program work without this, it'd just be convenient. </p>
| 0debug |
iOS how to take the webview to first page : I have a webview which load a page when the user navigates he can go to 7 levels I mean he can go to 7 different pages with different URL.
Now I want to go back to the first page directly instead of going back one by one.
I couldn't find any API in webview to do this so I thought to loading the first page url again but webview's cangoback will return true.
So I thought I will reinitialise the webview and load the URL
self.webview=[self.webview init];
as expect it loads the new url and webview's cangoback returns false which is good.
but the problem is when I try to scroll the page down I can see the previous page behind it as background of scrollview.
Any ideas on how to fix the issue
| 0debug |
static void decode_opc(DisasContext * ctx)
{
uint32_t old_flags = ctx->envflags;
_decode_opc(ctx);
if (old_flags & DELAY_SLOT_MASK) {
ctx->envflags &= ~DELAY_SLOT_MASK;
tcg_gen_movi_i32(cpu_flags, ctx->envflags);
ctx->bstate = BS_BRANCH;
if (old_flags & DELAY_SLOT_CONDITIONAL) {
gen_delayed_conditional_jump(ctx);
} else if (old_flags & DELAY_SLOT) {
gen_jump(ctx);
}
}
}
| 1threat |
Chrome not Firefox are not dumping to SSLKEYLOGFILE variable : <p>I'm trying to decrypt SSL packages with Wireshark as described <a href="https://jimshaver.net/2015/02/11/decrypting-tls-browser-traffic-with-wireshark-the-easy-way/" rel="noreferrer">here</a>. I have already created a SSLKEYLOGFILE System and User variable and the log file. I have restarted my computer (running Windows 10), and opened https urls with Chrome and Firefox, but none write to the ssl log file. My Chrome version is 56.0.2924.87 (64-bit) and my Firefox version is 51.0.1 (32-bit). Any idea how can I make any of the two browsers write to that file? Or is there any way to get the SSL key to be able to decrypt SSL packages in Wireshark? </p>
| 0debug |
Assigning a static_cast<int>(-15) to a static const char type variable : <p>Hello it may be some silly question, but this is bugging me since few days. </p>
<p>I have bellow line of code:</p>
<pre><code>static const char x1 = static_cast<int>(-15);
cout<<x1;
static const char x2= 16;
cout<< "hello "<< x2<<'\n';
</code></pre>
<p>The output is None I mean nothing is getting printed in console. But when I did the comparison like <code>if(kill == -15)</code> its evaluated as True. So may I know why I can not see any output in console when I am printing.</p>
| 0debug |
int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
uint8_t *buf, int buf_size,
const short *samples)
{
AVPacket pkt;
AVFrame frame0 = { 0 };
AVFrame *frame;
int ret, samples_size, got_packet;
av_init_packet(&pkt);
pkt.data = buf;
pkt.size = buf_size;
if (samples) {
frame = &frame0;
avcodec_get_frame_defaults(frame);
if (avctx->frame_size) {
frame->nb_samples = avctx->frame_size;
} else {
int64_t nb_samples;
if (!av_get_bits_per_sample(avctx->codec_id)) {
av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
"support this codec\n");
return AVERROR(EINVAL);
}
nb_samples = (int64_t)buf_size * 8 /
(av_get_bits_per_sample(avctx->codec_id) *
avctx->channels);
if (nb_samples >= INT_MAX)
return AVERROR(EINVAL);
frame->nb_samples = nb_samples;
}
samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
frame->nb_samples,
avctx->sample_fmt, 1);
if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
avctx->sample_fmt,
(const uint8_t *)samples,
samples_size, 1)))
return ret;
if (avctx->sample_rate && avctx->time_base.num)
frame->pts = ff_samples_to_time_base(avctx,
avctx->internal->sample_count);
else
frame->pts = AV_NOPTS_VALUE;
avctx->internal->sample_count += frame->nb_samples;
} else {
frame = NULL;
}
got_packet = 0;
ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
if (!ret && got_packet && avctx->coded_frame) {
avctx->coded_frame->pts = pkt.pts;
avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
}
ff_packet_free_side_data(&pkt);
if (frame && frame->extended_data != frame->data)
av_freep(&frame->extended_data);
return ret ? ret : pkt.size;
}
| 1threat |
Beanstalk: Node.js deployment - node-gyp fails due to permission denied : <p>Deployment of a Node.js application (Node 6, npm 5) to Beanstalk fails with:</p>
<blockquote>
<p>gyp ERR! stack Error: EACCES: permission denied, mkdir
'/tmp/deployment/application/node_modules/heapdump/build'</p>
</blockquote>
<p>though the error is not package-specific, any node-gyp call fails.</p>
<p>The ERROR event in the AWS Console reads:</p>
<blockquote>
<p>[Instance: i-12345] Command failed on instance. Return
code: 1 Output:
(TRUNCATED).../opt/elasticbeanstalk/containerfiles/ebnode.py", line
180, in npm_install raise e subprocess.CalledProcessError: Command
'['/opt/elasticbeanstalk/node-install/node-v6.10.0-linux-x64/bin/npm',
'--production', 'install']' returned non-zero exit status 1. Hook
/opt/elasticbeanstalk/hooks/appdeploy/pre/50npm.sh failed. For more
detail, check /var/log/eb-activity.log using console or EB CLI.</p>
</blockquote>
<p>and <code>eb-activity.log</code> contained the aforementioned npm error.</p>
<p>The application was deployed manually by uploading a .zip file that did not include <code>node_modules</code>. I.e. it was not deployed via the <code>eb</code> command-line tool.</p>
| 0debug |
static int ff_interleave_new_audio_packet(AVFormatContext *s, AVPacket *pkt,
int stream_index, int flush)
{
AVStream *st = s->streams[stream_index];
AudioInterleaveContext *aic = st->priv_data;
int size = FFMIN(av_fifo_size(aic->fifo), *aic->samples * aic->sample_size);
if (!size || (!flush && size == av_fifo_size(aic->fifo)))
return 0;
av_new_packet(pkt, size);
av_fifo_generic_read(aic->fifo, pkt->data, size, NULL);
pkt->dts = pkt->pts = aic->dts;
pkt->duration = av_rescale_q(*aic->samples, st->time_base, aic->time_base);
pkt->stream_index = stream_index;
aic->dts += pkt->duration;
aic->samples++;
if (!*aic->samples)
aic->samples = aic->samples_per_frame;
return size;
}
| 1threat |
static void get_downmix_coeffs(AC3DecodeContext *ctx)
{
int from = ctx->bsi.acmod;
int to = ctx->output;
float clev = clevs[ctx->bsi.cmixlev];
float slev = slevs[ctx->bsi.surmixlev];
ac3_audio_block *ab = &ctx->audio_block;
if (to == AC3_OUTPUT_UNMODIFIED)
return 0;
switch (from) {
case AC3_INPUT_DUALMONO:
switch (to) {
case AC3_OUTPUT_MONO:
case AC3_OUTPUT_STEREO:
ab->chcoeffs[0] *= LEVEL_MINUS_6DB;
ab->chcoeffs[1] *= LEVEL_MINUS_6DB;
break;
}
break;
case AC3_INPUT_MONO:
switch (to) {
case AC3_OUTPUT_STEREO:
ab->chcoeffs[0] *= LEVEL_MINUS_3DB;
break;
}
break;
case AC3_INPUT_STEREO:
switch (to) {
case AC3_OUTPUT_MONO:
ab->chcoeffs[0] *= LEVEL_MINUS_3DB;
ab->chcoeffs[1] *= LEVEL_MINUS_3DB;
break;
}
break;
case AC3_INPUT_3F:
switch (to) {
case AC3_OUTPUT_MONO:
ab->chcoeffs[0] *= LEVEL_MINUS_3DB;
ab->chcoeffs[2] *= LEVEL_MINUS_3DB;
ab->chcoeffs[1] *= clev * LEVEL_PLUS_3DB;
break;
case AC3_OUTPUT_STEREO:
ab->chcoeffs[1] *= clev;
break;
}
break;
case AC3_INPUT_2F_1R:
switch (to) {
case AC3_OUTPUT_MONO:
ab->chcoeffs[0] *= LEVEL_MINUS_3DB;
ab->chcoeffs[1] *= LEVEL_MINUS_3DB;
ab->chcoeffs[2] *= slev * LEVEL_MINUS_3DB;
break;
case AC3_OUTPUT_STEREO:
ab->chcoeffs[2] *= slev * LEVEL_MINUS_3DB;
break;
case AC3_OUTPUT_DOLBY:
ab->chcoeffs[2] *= LEVEL_MINUS_3DB;
break;
}
break;
case AC3_INPUT_3F_1R:
switch (to) {
case AC3_OUTPUT_MONO:
ab->chcoeffs[0] *= LEVEL_MINUS_3DB;
ab->chcoeffs[2] *= LEVEL_MINUS_3DB;
ab->chcoeffs[1] *= clev * LEVEL_PLUS_3DB;
ab->chcoeffs[3] *= slev * LEVEL_MINUS_3DB;
break;
case AC3_OUTPUT_STEREO:
ab->chcoeffs[1] *= clev;
ab->chcoeffs[3] *= slev * LEVEL_MINUS_3DB;
break;
case AC3_OUTPUT_DOLBY:
ab->chcoeffs[1] *= LEVEL_MINUS_3DB;
ab->chcoeffs[3] *= LEVEL_MINUS_3DB;
break;
}
break;
case AC3_INPUT_2F_2R:
switch (to) {
case AC3_OUTPUT_MONO:
ab->chcoeffs[0] *= LEVEL_MINUS_3DB;
ab->chcoeffs[1] *= LEVEL_MINUS_3DB;
ab->chcoeffs[2] *= slev * LEVEL_MINUS_3DB;
ab->chcoeffs[3] *= slev * LEVEL_MINUS_3DB;
break;
case AC3_OUTPUT_STEREO:
ab->chcoeffs[2] *= slev;
ab->chcoeffs[3] *= slev;
break;
case AC3_OUTPUT_DOLBY:
ab->chcoeffs[2] *= LEVEL_MINUS_3DB;
ab->chcoeffs[3] *= LEVEL_MINUS_3DB;
break;
}
break;
case AC3_INPUT_3F_2R:
switch (to) {
case AC3_OUTPUT_MONO:
ab->chcoeffs[0] *= LEVEL_MINUS_3DB;
ab->chcoeffs[2] *= LEVEL_MINUS_3DB;
ab->chcoeffs[1] *= clev * LEVEL_PLUS_3DB;
ab->chcoeffs[3] *= slev * LEVEL_MINUS_3DB;
ab->chcoeffs[4] *= slev * LEVEL_MINUS_3DB;
break;
case AC3_OUTPUT_STEREO:
ab->chcoeffs[1] *= clev;
ab->chcoeffs[3] *= slev;
ab->chcoeffs[4] *= slev;
break;
case AC3_OUTPUT_DOLBY:
ab->chcoeffs[1] *= LEVEL_MINUS_3DB;
ab->chcoeffs[3] *= LEVEL_MINUS_3DB;
ab->chcoeffs[4] *= LEVEL_MINUS_3DB;
break;
}
break;
}
}
| 1threat |
static MaltaFPGAState *malta_fpga_init(MemoryRegion *address_space,
target_phys_addr_t base, qemu_irq uart_irq, CharDriverState *uart_chr)
{
MaltaFPGAState *s;
s = (MaltaFPGAState *)g_malloc0(sizeof(MaltaFPGAState));
memory_region_init_io(&s->iomem, &malta_fpga_ops, s,
"malta-fpga", 0x100000);
memory_region_init_alias(&s->iomem_lo, "malta-fpga",
&s->iomem, 0, 0x900);
memory_region_init_alias(&s->iomem_hi, "malta-fpga",
&s->iomem, 0xa00, 0x10000-0xa00);
memory_region_add_subregion(address_space, base, &s->iomem_lo);
memory_region_add_subregion(address_space, base + 0xa00, &s->iomem_hi);
s->display = qemu_chr_new("fpga", "vc:320x200", malta_fpga_led_init);
s->uart = serial_mm_init(address_space, base + 0x900, 3, uart_irq,
230400, uart_chr, DEVICE_NATIVE_ENDIAN);
malta_fpga_reset(s);
qemu_register_reset(malta_fpga_reset, s);
return s;
}
| 1threat |
Comes up with an syntax error on the space : <p>I don't really know why this is happening, can someone help explaining why the syntax error happens </p>
<pre><code>Menu_select = input("""
[------------------]
[ Menu.model ]
[ 1) Start: ]
[ 2) Options: ]
[ 3) Placeholder1: ]
[ 4) Placeholder2: ]
[ 5) Exit: ]
[------------------]
"""))
if Menu_select == '1':
startyn = input('Do you want to start? ')
while startyn != 'Yes' or startyn != 'yes' or startyn != 'y' or startyn != 'Y':
if startyn == 'Yes' or startyn == 'yes' or startyn == 'y' or startyn == 'Y':
print('Okay lets start!')
elif startyn == 'No' or startyn == 'no' or startyn == 'N' or startyn == 'n':
print('Okay back to the menu!')
elif Menu_select == '2':
optionsyn = input('Do you want to go into the options? ')
</code></pre>
| 0debug |
React Intl FormattedNumber with the currency symbol before, not after : <p>I am using FormattedNumber from React Intl in a big React project that has the capability for many different languages.</p>
<p>Here is a Currency component I made so that I can easily insert a formatted currency into my views:</p>
<pre><code>import {FormattedNumber} from 'react-intl';
const Currency = (props) => {
const currency = props.currency;
const minimum = props.minimumFractionDigits || 2;
const maximum = props.maximumFractionDigits || 2;
return <FormattedNumber
value={props.amount}
style="currency"
currency={currency}
minimumFractionDigits={minimum}
maximumFractionDigits={maximum}
/>;
};
export default Currency;
</code></pre>
<p>The component works great. And, it works as expected. In English - when <code>currency</code> is <code>GBP</code> - an amount is formatted as such:</p>
<pre><code>£4.00
</code></pre>
<p>In German - when <code>currency</code> is <code>EUR</code> - it's formatted as such:</p>
<pre><code>4,00€
</code></pre>
<p>However, I need to format the amount differently in a particular case. So, what I'm looking for is the Euro coming before the amount, like so:</p>
<pre><code>€4,00
</code></pre>
<p>Is this possible with FormattedNumber? I don't want to have to manually reformat the formatted number if I can avoid it.</p>
| 0debug |
Word length finding : <p>I'm trying to find out the length of a words in a list in python. Somehow I'm displaying the wrong numbers. I know I need to change line 3 but dunno what to.</p>
<pre><code>>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print i, a[i]
</code></pre>
<p>Sorry if this question isn't properly formatted.</p>
| 0debug |
I want to match whole word django : Here is my code that i want to search the input that user fill in the web, I called input as aranan, but it dose not work proper. I search 'urla' but it return me 'memurlarin' . the urla is inside the word memurlarin. but I want to get me back just sentences thet urla is on it.I
please help me. thenk you
if form.is_valid():
cd = form.cleaned_data
aranan = cd['aranan']
sen1 = pd.read_csv('.../Corpus.csv',encoding="utf-8")
sen1 = sen1.sentence1_stop
sen2 = pd.read_csv(.../Corpus.csv',encoding="utf-8")
sen2 = sen2.sentence2_stop
for i in range(len(sen1)):
if (aranan in sen1[i] and aranan in sen2[i]):
... | 0debug |
Mac OSX python ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) : <p>Many operations in python require accessing things via https. This includes pip install, or just using http.client.HTTPSConnection, or any modules or applications that use these things internally.</p>
<p>If python was installed from the official python pkg installer, downloaded from <a href="https://python.org" rel="noreferrer">https://python.org</a>, then it uses an internal version of openssl, and contains no root certificates. Anything that uses an SSL connection results in this error:</p>
<pre><code>ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)
</code></pre>
<p>How can I install root certs to make the above error go away?</p>
| 0debug |
static void pci_basic(gconstpointer data)
{
QVirtioPCIDevice *dev;
QPCIBus *bus;
QVirtQueuePCI *tx, *rx;
QGuestAllocator *alloc;
void (*func) (QVirtioDevice *dev,
QGuestAllocator *alloc,
QVirtQueue *rvq,
QVirtQueue *tvq,
int socket) = data;
int sv[2], ret;
ret = socketpair(PF_UNIX, SOCK_STREAM, 0, sv);
g_assert_cmpint(ret, !=, -1);
bus = pci_test_start(sv[1]);
dev = virtio_net_pci_init(bus, PCI_SLOT);
alloc = pc_alloc_init();
rx = (QVirtQueuePCI *)qvirtqueue_setup(&dev->vdev, alloc, 0);
tx = (QVirtQueuePCI *)qvirtqueue_setup(&dev->vdev, alloc, 1);
driver_init(&dev->vdev);
func(&dev->vdev, alloc, &rx->vq, &tx->vq, sv[0]);
close(sv[0]);
qvirtqueue_cleanup(dev->vdev.bus, &tx->vq, alloc);
qvirtqueue_cleanup(dev->vdev.bus, &rx->vq, alloc);
pc_alloc_uninit(alloc);
qvirtio_pci_device_disable(dev);
g_free(dev->pdev);
g_free(dev);
qpci_free_pc(bus);
test_end();
}
| 1threat |
django can't find new sqlite version? (SQLite 3.8.3 or later is required (found 3.7.17)) : <p>I've cloned a django project to a Centos 7 vps and I'm trying to run it now, but I get this error when trying to <code>migrate</code>:</p>
<pre><code>$ python manage.py migrate
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17).
</code></pre>
<p>When I checked the version for sqlite, it was 3.7.17, so I downloaded the newest version from sqlite website and replaced it with the old one, and now when I version it, it gives:</p>
<pre><code>$ sqlite3 --version
3.27.2 2019-02-25 16:06:06 bd49a8271d650fa89e446b42e513b595a717b9212c91dd384aab871fc1d0f6d7
</code></pre>
<p>Still when I try to migrate the project, I get the exact same message as before which means the newer version is not found. I'm new to linux and would appreciate any help.</p>
| 0debug |
Why P-521 public key X,Y some time is 65 bytes some time is 66 bytes : <p>I use golang generate the P-521 public key.
source code look like that:</p>
<pre><code>curve:=elliptic.P521()
priv, x, y, err := elliptic.GenerateKey(curve, rand.Reader)
xBytes:=x.Bytes()
yBytes:=y.bytes()
//len(xBytes) some time is 65 bytes ,some time is 66 bytes
</code></pre>
<p>Why P-521 public key X,Y not like P-256 or P-384 that have a fixed public key length?</p>
| 0debug |
c++ Realloc() doest not working : i have this code
Perro **obj = NULL;
obj = (Perro**)malloc(10*sizeof(Perro*));
for (int i = 0; i < 10; i++)
{
obj[i] = new Perrito((char*)"d",i);
}
realloc(obj,12*sizeof(Perro*));
for (int i = 9; i < 12; i++)
{
obj[i] = new Perrito((char*)"d",i);
}
for (int i = 0; i < 12; i++)
{
Perrito *p;
p = (Perrito*)obj[i];
cout << p->getEdad() << endl;
}
why when i'm reading my object a see a memori dumpd ( segmentation fault )
when i comend the line of realloc and reduce the last for length item it works normaly but a need to ude realloc for increase my polifirmist object length please help mee thanks! | 0debug |
static int wm8750_event(I2CSlave *i2c, enum i2c_event event)
{
WM8750State *s = WM8750(i2c);
switch (event) {
case I2C_START_SEND:
s->i2c_len = 0;
break;
case I2C_FINISH:
#ifdef VERBOSE
if (s->i2c_len < 2)
printf("%s: message too short (%i bytes)\n",
__FUNCTION__, s->i2c_len);
#endif
break;
default:
break;
}
return 0;
}
| 1threat |
Sending a positive octet of zero bits over a socket : I am currently attempting to communicate with an external application over TCP/IP based socket. I have successfully established a connection with the client and received some data. This manual [here][1] states that
> After this command is received, the client must read an acknowledgement
> octet from the daemon. A positive acknowledgement is an octet of zero bits. A negative acknowledgement is an octet of any other pattern.
I would like to send a positive acknowledgment and I am sending it this way
void WriteData(std::string content)
{
send(newsockfd,content.c_str(),content.length(),0);
}
WriteData("00000000");
My question is if I am sending this data corectly ?
[1]: https://www.ietf.org/rfc/rfc1179.txt | 0debug |
java.lang.NullPointerException (no error message) APK building : <pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
jcenter()
}
dependencies {
classpath "gradle.plugin.me.tatarka:gradle-retrolambda:3.3.0"
classpath 'com.android.tools.build:gradle:2.2.1'
}
}
allprojects {
repositories {
jcenter()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p>The :app file</p>
<pre><code>apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "24.0.3"
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "it.univpm.gruppoids.iotforemergencyandnavigation"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
jackOptions {
enabled true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:support-v4:23.4.0'
compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
compile 'com.google.zxing:core:3.2.1'
compile 'org.jgrapht:jgrapht-core:1.0.0'
}
</code></pre>
<p>When i try to build APK it shows me: Error:A problem occurred configuring project ':app'.</p>
<blockquote>
<p>java.lang.NullPointerException (no error message)</p>
</blockquote>
<p>Is it a problem with versions? or with lamdas?? someone can help me?</p>
| 0debug |
Can someone explain me what is flex property? : <p>Hello currently I'm learning flexbox, and I've watched a lot tutorials but I couldn't figure out what does flex property do? Some explanation and links that explain what it does would be really helpful. Thanks.</p>
| 0debug |
php artisan migrate : erorr : <code>$ php artisan migrate
Migration table created successfully.
In Connection.php line 647:
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table `users`
add unique `users_email_unique`(`email`))
In Connection.php line 449:
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes</code>
what's the problem?:| | 0debug |
Flutter Text Field: How to add Icon inside the border : <p><a href="https://i.stack.imgur.com/TfQ2u.jpg" rel="noreferrer">The Search Bar to Replicate</a></p>
<p>I would like to add the icon in the search bar. Here is my code so far:</p>
<pre><code>new TextField(
decoration: new InputDecoration(
icon: new Icon(Icons.search)
labelText: "Describe Your Issue...",
enabledBorder: const OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
borderSide: const BorderSide(
color: Colors.grey,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
borderSide: BorderSide(color: Colors.blue),
),
),
),
</code></pre>
<p>This is the result of the code above (this is not what i want):</p>
<p><a href="https://i.stack.imgur.com/sgY8b.jpg" rel="noreferrer">Output of my code (this is not what i want)</a></p>
| 0debug |
Configure docker-compose override to ignore / hide some containers : <p>If I have (simplified), the following <em>docker-compose.yml</em>:</p>
<pre><code>parent:
image: parent
links:
- child
child:
image: child
</code></pre>
<p>Can I construct a <em>docker-compose.override.yml</em> file that will <strong>not</strong> create or start the <code>child</code> image?</p>
<hr>
<p>An undesirable (for me) solution, would be to reverse the files, such that the default yml file would create only the <code>parent</code>, and the override would create both.</p>
<p>However, I would like the <em>master</em> configuration file to contain the most common usage scenario.</p>
| 0debug |
static void *spapr_create_fdt_skel(hwaddr initrd_base,
hwaddr initrd_size,
hwaddr kernel_size,
bool little_endian,
const char *kernel_cmdline,
uint32_t epow_irq)
{
void *fdt;
uint32_t start_prop = cpu_to_be32(initrd_base);
uint32_t end_prop = cpu_to_be32(initrd_base + initrd_size);
GString *hypertas = g_string_sized_new(256);
GString *qemu_hypertas = g_string_sized_new(256);
uint32_t refpoints[] = {cpu_to_be32(0x4), cpu_to_be32(0x4)};
uint32_t interrupt_server_ranges_prop[] = {0, cpu_to_be32(max_cpus)};
unsigned char vec5[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x80};
char *buf;
add_str(hypertas, "hcall-pft");
add_str(hypertas, "hcall-term");
add_str(hypertas, "hcall-dabr");
add_str(hypertas, "hcall-interrupt");
add_str(hypertas, "hcall-tce");
add_str(hypertas, "hcall-vio");
add_str(hypertas, "hcall-splpar");
add_str(hypertas, "hcall-bulk");
add_str(hypertas, "hcall-set-mode");
add_str(hypertas, "hcall-sprg0");
add_str(hypertas, "hcall-copy");
add_str(hypertas, "hcall-debug");
add_str(qemu_hypertas, "hcall-memop1");
fdt = g_malloc0(FDT_MAX_SIZE);
_FDT((fdt_create(fdt, FDT_MAX_SIZE)));
if (kernel_size) {
_FDT((fdt_add_reservemap_entry(fdt, KERNEL_LOAD_ADDR, kernel_size)));
}
if (initrd_size) {
_FDT((fdt_add_reservemap_entry(fdt, initrd_base, initrd_size)));
}
_FDT((fdt_finish_reservemap(fdt)));
_FDT((fdt_begin_node(fdt, "")));
_FDT((fdt_property_string(fdt, "device_type", "chrp")));
_FDT((fdt_property_string(fdt, "model", "IBM pSeries (emulated by qemu)")));
_FDT((fdt_property_string(fdt, "compatible", "qemu,pseries")));
if (kvmppc_get_host_model(&buf)) {
_FDT((fdt_property_string(fdt, "host-model", buf)));
g_free(buf);
}
if (kvmppc_get_host_serial(&buf)) {
_FDT((fdt_property_string(fdt, "host-serial", buf)));
g_free(buf);
}
buf = g_strdup_printf(UUID_FMT, qemu_uuid[0], qemu_uuid[1],
qemu_uuid[2], qemu_uuid[3], qemu_uuid[4],
qemu_uuid[5], qemu_uuid[6], qemu_uuid[7],
qemu_uuid[8], qemu_uuid[9], qemu_uuid[10],
qemu_uuid[11], qemu_uuid[12], qemu_uuid[13],
qemu_uuid[14], qemu_uuid[15]);
_FDT((fdt_property_string(fdt, "vm,uuid", buf)));
if (qemu_uuid_set) {
_FDT((fdt_property_string(fdt, "system-id", buf)));
}
g_free(buf);
if (qemu_get_vm_name()) {
_FDT((fdt_property_string(fdt, "ibm,partition-name",
qemu_get_vm_name())));
}
_FDT((fdt_property_cell(fdt, "#address-cells", 0x2)));
_FDT((fdt_property_cell(fdt, "#size-cells", 0x2)));
_FDT((fdt_begin_node(fdt, "chosen")));
_FDT((fdt_property(fdt, "ibm,architecture-vec-5", vec5, sizeof(vec5))));
_FDT((fdt_property_string(fdt, "bootargs", kernel_cmdline)));
_FDT((fdt_property(fdt, "linux,initrd-start",
&start_prop, sizeof(start_prop))));
_FDT((fdt_property(fdt, "linux,initrd-end",
&end_prop, sizeof(end_prop))));
if (kernel_size) {
uint64_t kprop[2] = { cpu_to_be64(KERNEL_LOAD_ADDR),
cpu_to_be64(kernel_size) };
_FDT((fdt_property(fdt, "qemu,boot-kernel", &kprop, sizeof(kprop))));
if (little_endian) {
_FDT((fdt_property(fdt, "qemu,boot-kernel-le", NULL, 0)));
}
}
if (boot_menu) {
_FDT((fdt_property_cell(fdt, "qemu,boot-menu", boot_menu)));
}
_FDT((fdt_property_cell(fdt, "qemu,graphic-width", graphic_width)));
_FDT((fdt_property_cell(fdt, "qemu,graphic-height", graphic_height)));
_FDT((fdt_property_cell(fdt, "qemu,graphic-depth", graphic_depth)));
_FDT((fdt_end_node(fdt)));
_FDT((fdt_begin_node(fdt, "rtas")));
if (!kvm_enabled() || kvmppc_spapr_use_multitce()) {
add_str(hypertas, "hcall-multi-tce");
}
_FDT((fdt_property(fdt, "ibm,hypertas-functions", hypertas->str,
hypertas->len)));
g_string_free(hypertas, TRUE);
_FDT((fdt_property(fdt, "qemu,hypertas-functions", qemu_hypertas->str,
qemu_hypertas->len)));
g_string_free(qemu_hypertas, TRUE);
_FDT((fdt_property(fdt, "ibm,associativity-reference-points",
refpoints, sizeof(refpoints))));
_FDT((fdt_property_cell(fdt, "rtas-error-log-max", RTAS_ERROR_LOG_MAX)));
_FDT((fdt_property_cell(fdt, "rtas-event-scan-rate",
RTAS_EVENT_SCAN_RATE)));
if (msi_nonbroken) {
_FDT((fdt_property(fdt, "ibm,change-msix-capable", NULL, 0)));
}
_FDT((fdt_property(fdt, "ibm,extended-os-term", NULL, 0)));
_FDT((fdt_end_node(fdt)));
_FDT((fdt_begin_node(fdt, "interrupt-controller")));
_FDT((fdt_property_string(fdt, "device_type",
"PowerPC-External-Interrupt-Presentation")));
_FDT((fdt_property_string(fdt, "compatible", "IBM,ppc-xicp")));
_FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));
_FDT((fdt_property(fdt, "ibm,interrupt-server-ranges",
interrupt_server_ranges_prop,
sizeof(interrupt_server_ranges_prop))));
_FDT((fdt_property_cell(fdt, "#interrupt-cells", 2)));
_FDT((fdt_property_cell(fdt, "linux,phandle", PHANDLE_XICP)));
_FDT((fdt_property_cell(fdt, "phandle", PHANDLE_XICP)));
_FDT((fdt_end_node(fdt)));
_FDT((fdt_begin_node(fdt, "vdevice")));
_FDT((fdt_property_string(fdt, "device_type", "vdevice")));
_FDT((fdt_property_string(fdt, "compatible", "IBM,vdevice")));
_FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));
_FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));
_FDT((fdt_property_cell(fdt, "#interrupt-cells", 0x2)));
_FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));
_FDT((fdt_end_node(fdt)));
spapr_events_fdt_skel(fdt, epow_irq);
if (kvm_enabled()) {
uint8_t hypercall[16];
_FDT((fdt_begin_node(fdt, "hypervisor")));
_FDT((fdt_property_string(fdt, "compatible", "linux,kvm")));
if (kvmppc_has_cap_fixup_hcalls()) {
if (!kvmppc_get_hypercall(first_cpu->env_ptr, hypercall,
sizeof(hypercall))) {
_FDT((fdt_property(fdt, "hcall-instructions", hypercall,
sizeof(hypercall))));
}
}
_FDT((fdt_end_node(fdt)));
}
_FDT((fdt_end_node(fdt)));
_FDT((fdt_finish(fdt)));
return fdt;
}
| 1threat |
static int put_image(struct vf_instance *vf, mp_image_t *mpi, double pts)
{
mp_image_t *dmpi;
dmpi=ff_vf_get_image(vf->next, IMGFMT_YV12,
MP_IMGTYPE_TEMP, MP_IMGFLAG_ACCEPT_STRIDE |
((vf->priv->scaleh == 1) ? MP_IMGFLAG_READABLE : 0),
mpi->w * vf->priv->scalew,
mpi->h / vf->priv->scaleh - vf->priv->skipline);
toright(dmpi->planes, mpi->planes, dmpi->stride,
mpi->stride, mpi->w, mpi->h, vf->priv);
return ff_vf_next_put_image(vf,dmpi, pts);
}
| 1threat |
float32 HELPER(ucf64_df2si)(float64 x, CPUUniCore32State *env)
{
return ucf64_itos(float64_to_int32(x, &env->ucf64.fp_status));
}
| 1threat |
When I put a div around an image, why is there spacing at the bottom? : <p>Take for example this fiddle: <a href="https://jsfiddle.net/ou33muc2/" rel="nofollow noreferrer">https://jsfiddle.net/ou33muc2/</a></p>
<pre><code><div class = "overallDiv">
<div id="example"><img src = "http://writingexercises.co.uk/images2/randomimage/slimy.jpg" style="width:100vw; opacity: 0.5;"/></div></div>
</code></pre>
<p>I fail to understand why there is no gap between the div surrounding the image and the image on the top, left and right, but there is a gap on the bottom as shown by the red border.</p>
<p>Moreover, how can I remove this, so that the div fits snugly around the whole image?</p>
<p>Edit: I know it might seem a bit pointless having a div around a div around an image, but this is a scaled down problem where the question still applies, so please ignore the practicalities of it.</p>
| 0debug |
Vue JS: Difference of data() { return {} } vs data:() => ({ }) : <p>I'm curious both of this data function, is there any difference between this two.</p>
<p>I usually saw is</p>
<pre><code>data () {
return {
obj
}
}
</code></pre>
<p>And ES6 "fat arrow" which I typically used</p>
<pre><code>data:()=>({
obj
})
</code></pre>
| 0debug |
static uint32_t nvram_readb (void *opaque, target_phys_addr_t addr)
{
M48t59State *NVRAM = opaque;
uint32_t retval;
retval = m48t59_read(NVRAM, addr);
return retval;
}
| 1threat |
uint64_t HELPER(abs_i64)(int64_t val)
{
HELPER_LOG("%s: val 0x%" PRIx64 "\n", __func__, val);
if (val < 0) {
return -val;
} else {
return val;
}
}
| 1threat |
Vue component props without value : <p>I want to set an attribute on my component without any value. For example:</p>
<pre><code><my-button primary>Save</my-button>
</code></pre>
<p>I'm declaring <code>primary</code> in <code>props</code> of my component:</p>
<pre><code>Vue.component("my-button", {
props: ["primary"],
template: "<button v-bind:class='{primary: primary}'><slot></slot></button>"
})
</code></pre>
<p>Unfortunately, it doesn't work. The <code>primary</code> property is <code>undefined</code> and the class is not applied.</p>
<p>JSFiddle: <a href="https://jsfiddle.net/LukaszWiktor/g3jkscna/" rel="noreferrer">https://jsfiddle.net/LukaszWiktor/g3jkscna/</a></p>
| 0debug |
Conda: Creating a virtual environment : <p>I'm trying to create a virtual environment. I've followed steps from both <a href="https://conda.io/docs/user-guide/tasks/manage-environments.html#" rel="noreferrer" title="Conda">Conda</a> and <a href="https://medium.com/@tk2bit/how-to-set-up-and-maintain-conda-virtual-environment-for-your-python-projects-643c8f0c81a1" rel="noreferrer" title="Medium">Medium</a>.</p>
<p>Everything works fine until I need to source the new environment.</p>
<pre><code>conda info -e
# conda environments:
#
base * /Users/fwrenn/anaconda3
test_env /Users/fwrenn/anaconda3/envs/test_env
source ~/anaconda3/bin/activate test_env
_CONDA_ROOT=/Users/fwrenn/anaconda3: Command not found.
Badly placed ()'s.
</code></pre>
<p>I can't figure out the problem. Searching on here has solutions that say adding lines to your bash_profile, but I don't work in bash, only csh. It LOOKS like it's unable to build the directory path in <code>activate</code>.</p>
<p>My particulars:</p>
<pre><code>OSX
python --version
Python 3.6.3 :: Anaconda custom (64-bit)
conda --version
conda 4.4.7
</code></pre>
| 0debug |
Ajax request in es6 vanilla javascript : <p>I am able to make an ajax request using jquery and es5 but I want to transition me code so that its vanilla and uses es6. How would this request change. (Note: I am querying Wikipedia's api).</p>
<pre><code> var link = "https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids="+ page +"&format=json&callback=?";
$.ajax({
type: "GET",
url: link,
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success:function(re){
},
error:function(u){
console.log("u")
alert("sorry, there are no results for your search")
}
</code></pre>
| 0debug |
Printing the minimum value out of a list (PYTHON) : <p>new to python just trying to figure out how to print the minimum of this generated list, but its giving me the error</p>
<pre><code>TypeError: 'int' object is not iterable
</code></pre>
<p>and this is my code,</p>
<pre><code>number = []
for number in range(1,21)
print min(number)
</code></pre>
<p>I have tried several things including </p>
<pre><code>print(min(int(number)))
</code></pre>
<p>Which seems like since its giving me an int problem would solve it, no?</p>
| 0debug |
static int au_read_packet(AVFormatContext *s,
AVPacket *pkt)
{
int ret;
ret= av_get_packet(s->pb, pkt, BLOCK_SIZE *
s->streams[0]->codec->channels *
av_get_bits_per_sample(s->streams[0]->codec->codec_id) >> 3);
if (ret < 0)
return ret;
pkt->flags &= ~AV_PKT_FLAG_CORRUPT;
pkt->stream_index = 0;
return 0;
}
| 1threat |
static void merge_context_after_encode(MpegEncContext *dst, MpegEncContext *src){
int i;
MERGE(dct_count[0]);
MERGE(dct_count[1]);
MERGE(mv_bits);
MERGE(i_tex_bits);
MERGE(p_tex_bits);
MERGE(i_count);
MERGE(f_count);
MERGE(b_count);
MERGE(skip_count);
MERGE(misc_bits);
MERGE(er.error_count);
MERGE(padding_bug_score);
MERGE(current_picture.f->error[0]);
MERGE(current_picture.f->error[1]);
MERGE(current_picture.f->error[2]);
if(dst->avctx->noise_reduction){
for(i=0; i<64; i++){
MERGE(dct_error_sum[0][i]);
MERGE(dct_error_sum[1][i]);
}
}
assert(put_bits_count(&src->pb) % 8 ==0);
assert(put_bits_count(&dst->pb) % 8 ==0);
avpriv_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));
flush_put_bits(&dst->pb);
}
| 1threat |
The object qualifer that are not compatible with the member functions : <p>I am trying to change a subclass values Capacity, RentRate and RentMin using operation overloading. I'm newish to c++, come from java.
I want to create the objects</p>
<pre><code>VanIn Van7("Large", 200, 2.0);
ManVanIn ManVan8("Abc", 99999, "Medium", 100, 1.0);
ManVan8 = Van7;
</code></pre>
<p>Making ManVan8 values change from "Medium, 100, 1.0" to "Large, 200, 2.0" but I keep getting a object qualifer error at the operations overload method</p>
<pre><code> using namespace std;
class AbstractVan {
private:
int RentMin;
string Drivername;
long DLno;
string Capacity;
float RentRate;
public:
AbstractVan(string Drivername, long DLno, string Capacity, int RentMin, float RentRate) : Capacity(Capacity), RentMin(RentMin), RentRate(RentRate), DLno(DLno), Drivername(Drivername) {}
void setCapacity(string cap) { Capacity = cap; }
void setRentRate(float rate) {RentRate = rate;}
void setRentMin(int min) {RentMin = min;}
string getCapacity() { return Capacity; }
float getRentRate() { return RentRate; }
int getRentMin() { return RentMin; }
virtual void print() = 0;
};
</code></pre>
<p>Derived class from AbstractVan</p>
<pre><code> class VanIn : public AbstractVan {
public:
VanIn(string Capacity, int RentMin, float RentRate) : AbstractVan(Capacity, RentMin, RentRate) {}
AbstractVan(string Drivername, long DLno, string Capacity, int RentMin, float RentRate) : Capacity(Capacity), RentMin(RentMin), RentRate(RentRate), DLno(DLno), Drivername(Drivername) {}
</code></pre>
<p>Derived class from VanIn</p>
<pre><code> class ManVanIn : public VanIn {
private:
string Drivername;
int DLno;
public:
ManVanIn(string Drivername, long DLno, string Capacity, int RentMin, float RentRate) : VanIn(Drivername, DLno, Capacity, RentMin, RentRate){}
void print() { cout << "Drivername " << this->Drivername << " Registration " << this->DLno << " - " << getCapacity() << endl; }
~ManVanIn() {cout << "Destroy ManVanIn" << endl;}
void operator = (const VanIn &D) {
setCapacity(D.getCapacity());
setRentRate(D.getRentRate());
setRentMin(D.getRentMin());
}
};
</code></pre>
<p>Entry</p>
<pre><code>int main()
{
VanIn Van7("Large", 200, 2.0);
ManVanIn ManVan8("Abc", 99999, "Medium", 100,1.0);
ManVan8 = Van7;
ManVan8.print();
system("pause");
return 0;
};
</code></pre>
| 0debug |
Organizing AWS IAM permissions: limit of 10 policies? : <p>I'm trying to polish the organization of my IAM roles in Amazon and their access to permissions.</p>
<p>I have groups, with policies attached, which map to groups within my company. I have reached the 10-policy limit on some groups.</p>
<p>So, users have a 10-policy limit, and a 10-group limit. If I want to keep things tidy, I can't start creating groups just for the sake of bundling unrelated policies together to try and keep everything under the limit of 10.</p>
<p>How is one supposed to organize permissions?</p>
| 0debug |
How to change application name in NativeScript : <p>I'm working with <strong>NativeScript</strong> from <strong>Telerik</strong> and I made an app with a debug name ("notiApp") but now I can't change the app's name in launcher and action bar.</p>
<p>I already tried configuring my <code>AndroidManifest.xml</code> in <code>/app/App_Resources/Android/</code> modifying the <code>android:label</code> attribute of my <code><application></code> tag.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest>
<application
android:label="DESIRED NAME">
</application>
</manifest>
</code></pre>
<p>Also, I tried changing my project's root directory name for the new app desired name.</p>
<p>There's anything else I can do or any additional information I could provide?</p>
<p>Thanks in advance guys!</p>
| 0debug |
Why its happening? : So, i'm tryin' to create a full width navbar using bootstrap, but theres a kind of limit in my nav [LIKE THIS][1]
This is my html:
<div class="row">
<div class="col-md-12 text-center">
<nav class="navbar navbar-default">
<div class="container-fluid">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Features</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</div>
</nav>
</div>
</div>
This is my css:
@import url(https://fonts.googleapis.com/css?family=Raleway:400,700,300,100);
body {
font-family: "Raleway", Sans-Serif;
font-weight: 400;
}
p {
text-align: justify;
font-size: 16px;
}
.navbar {
font-weight: 700;
letter-spacing: 2px;
text-transform: uppercase;
}
.navbar-default .navbar-nav .active a,
.navbar-default .navbar-nav .active a:focus,
.navbar-default .navbar-nav .active a:hover,
.navbar-default .navbar-nav li a:hover{
color:#e1b315;
}
.navbar .navbar-nav {
display: inline-block;
float: none;
}
.navbar-default .navbar-nav li {
margin: 0 15px;
}
I'm not certainly about why that happens =/
What i'm really tryin' to do is something [LIKE THIS][2]
[1]: http://i.stack.imgur.com/PJn5N.png
[2]: http://i.stack.imgur.com/kZgRo.png | 0debug |
Merge JSON array into Object : If I have an Object like.
myObj = {
"name":"John",
"age":30
}
and an array like this.
myObjArr = [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
How can I merge my array into the object so the output is like
myObj = {
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}
Sorry if this is a redundant question, but for some reason I just get lost with arrays. I have tried push which did not work and cannot find any good example on how to do this. | 0debug |
how to make textbox to remembers the previous input in excel vba? : >How to make the textbox to remember the previous input in excel vba? Please give me a simple code too. | 0debug |
(React native) How to use SafeAreaView for Android notch devices? : <p>I'm actually developing an app with react native and i'm testing with my one plus 6 and it has a notch. The SafeAreaView is a solution for the iPhone X but for Android, it seems there is no solution.</p>
<p>Did someone heard about anything to solve this kinf of issue ?</p>
| 0debug |
quiz in python reading a text file :
I am trying to ask the user to pick a quiz, read the relevant questions from a txt file, ask for user answers, validate and check they are correct then add up to scores. I am completely self taught so have picked this code up from various sites but as I have adapted it it no longer works - what have I done wrong? I know its probably something really obvious so please be gentle with me!
enter code hereimport time
def welcome():
print ("Welcome to Mrs Askew's GCSE ICT Quiz")
print()
def get_name():
firstname = input("What is your first name?:")
secondname = input("What is your second name?:")
print ("Good luck", firstname,", lets begin")
return firstname
return secondname
def displaymenu():
print("-------------------------------------------------------")
print("Menu")
print()
print("1. Input and Output Devices")
print("2. Collaborative working")
print("3. quiz3")
print("4. quiz4")
print("5. view scores")
print("6. Exit")
print()
print("-------------------------------------------------------")
def getchoice():
while True:
print("enter number 1 to 6")
quizchoice = input()
print("You have chosen number "+quizchoice)
print()
if quizchoice >='1' and quizchoice <='6':
print("that is a valid entry")
break
else:
print("invalid entry")
return quizchoice
def main():
welcome()
get_name()
while True:
displaymenu()
quizchoice = getchoice()
print ("please chooses from the options above: ")
if quizchoice == ("1"):
the_file = open("questions.txt", "r")
startquiz()
elif quizchoice == ("2"):
collaborativeworking()
startquiz()
else:
break
def collborativeworking():
the_file = open("Collaborative working.txt", "r")
return the_file
def next_line(the_file):
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct=correct[0]
explanation = next_line(the_file)
time.sleep(2)
return category, question, answers, correct, explanation
def startquiz():
title = next_line(the_file)
score = 0
category, question, answers, correct, explanation = next_block(the_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer and validate
while True:
answer =(input("What's your answer?: "))
if answer >= '1' and answer <='4':
break
else:
print ("the number needs to be between 1 and 4, try again ")
# check answer
answer=str(answer)
if answer == correct:
print("\nRight!", end=" ")
return score
main() | 0debug |
static int tiff_decode_tag(TiffContext *s, const uint8_t *start, const uint8_t *buf, const uint8_t *end_buf)
{
int tag, type, count, off, value = 0;
int i, j;
uint32_t *pal;
const uint8_t *rp, *gp, *bp;
tag = tget_short(&buf, s->le);
type = tget_short(&buf, s->le);
count = tget_long(&buf, s->le);
off = tget_long(&buf, s->le);
if(count == 1){
switch(type){
case TIFF_BYTE:
case TIFF_SHORT:
buf -= 4;
value = tget(&buf, type, s->le);
buf = NULL;
break;
case TIFF_LONG:
value = off;
buf = NULL;
break;
case TIFF_STRING:
if(count <= 4){
buf -= 4;
break;
}
default:
value = -1;
buf = start + off;
}
}else if(type_sizes[type] * count <= 4){
buf -= 4;
}else{
buf = start + off;
}
if(buf && (buf < start || buf > end_buf)){
av_log(s->avctx, AV_LOG_ERROR, "Tag referencing position outside the image\n");
return -1;
}
switch(tag){
case TIFF_WIDTH:
s->width = value;
break;
case TIFF_HEIGHT:
s->height = value;
break;
case TIFF_BPP:
if(count == 1) s->bpp = value;
else{
switch(type){
case TIFF_BYTE:
s->bpp = (off & 0xFF) + ((off >> 8) & 0xFF) + ((off >> 16) & 0xFF) + ((off >> 24) & 0xFF);
break;
case TIFF_SHORT:
case TIFF_LONG:
s->bpp = 0;
for(i = 0; i < count; i++) s->bpp += tget(&buf, type, s->le);
break;
default:
s->bpp = -1;
}
}
switch(s->bpp){
case 1:
s->avctx->pix_fmt = PIX_FMT_MONOBLACK;
break;
case 8:
s->avctx->pix_fmt = PIX_FMT_PAL8;
break;
case 24:
s->avctx->pix_fmt = PIX_FMT_RGB24;
break;
case 16:
if(count == 1){
s->avctx->pix_fmt = PIX_FMT_GRAY16BE;
}else{
av_log(s->avctx, AV_LOG_ERROR, "This format is not supported (bpp=%i)\n", s->bpp);
return -1;
}
break;
case 32:
if(count == 4){
s->avctx->pix_fmt = PIX_FMT_RGBA;
}else{
av_log(s->avctx, AV_LOG_ERROR, "This format is not supported (bpp=%d, %d components)\n", s->bpp, count);
return -1;
}
break;
default:
av_log(s->avctx, AV_LOG_ERROR, "This format is not supported (bpp=%d, %d components)\n", s->bpp, count);
return -1;
}
if(s->width != s->avctx->width || s->height != s->avctx->height){
if(avcodec_check_dimensions(s->avctx, s->width, s->height))
return -1;
avcodec_set_dimensions(s->avctx, s->width, s->height);
}
if(s->picture.data[0])
s->avctx->release_buffer(s->avctx, &s->picture);
if(s->avctx->get_buffer(s->avctx, &s->picture) < 0){
av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
return -1;
}
if(s->bpp == 8){
pal = (uint32_t *) s->picture.data[1];
for(i = 0; i < 256; i++)
pal[i] = i * 0x010101;
}
break;
case TIFF_COMPR:
s->compr = value;
s->predictor = 0;
switch(s->compr){
case TIFF_RAW:
case TIFF_PACKBITS:
case TIFF_LZW:
case TIFF_CCITT_RLE:
break;
case TIFF_G3:
case TIFF_G4:
s->fax_opts = 0;
break;
case TIFF_DEFLATE:
case TIFF_ADOBE_DEFLATE:
#if CONFIG_ZLIB
break;
#else
av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
return -1;
#endif
case TIFF_JPEG:
case TIFF_NEWJPEG:
av_log(s->avctx, AV_LOG_ERROR, "JPEG compression is not supported\n");
return -1;
default:
av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n", s->compr);
return -1;
}
break;
case TIFF_ROWSPERSTRIP:
if(type == TIFF_LONG && value == -1)
value = s->avctx->height;
if(value < 1){
av_log(s->avctx, AV_LOG_ERROR, "Incorrect value of rows per strip\n");
return -1;
}
s->rps = value;
break;
case TIFF_STRIP_OFFS:
if(count == 1){
s->stripdata = NULL;
s->stripoff = value;
}else
s->stripdata = start + off;
s->strips = count;
if(s->strips == 1) s->rps = s->height;
s->sot = type;
if(s->stripdata > end_buf){
av_log(s->avctx, AV_LOG_ERROR, "Tag referencing position outside the image\n");
return -1;
}
break;
case TIFF_STRIP_SIZE:
if(count == 1){
s->stripsizes = NULL;
s->stripsize = value;
s->strips = 1;
}else{
s->stripsizes = start + off;
}
s->strips = count;
s->sstype = type;
if(s->stripsizes > end_buf){
av_log(s->avctx, AV_LOG_ERROR, "Tag referencing position outside the image\n");
return -1;
}
break;
case TIFF_PREDICTOR:
s->predictor = value;
break;
case TIFF_INVERT:
switch(value){
case 0:
s->invert = 1;
break;
case 1:
s->invert = 0;
break;
case 2:
case 3:
break;
default:
av_log(s->avctx, AV_LOG_ERROR, "Color mode %d is not supported\n", value);
return -1;
}
break;
case TIFF_PAL:
if(s->avctx->pix_fmt != PIX_FMT_PAL8){
av_log(s->avctx, AV_LOG_ERROR, "Palette met but this is not palettized format\n");
return -1;
}
pal = (uint32_t *) s->picture.data[1];
off = type_sizes[type];
rp = buf;
gp = buf + count / 3 * off;
bp = buf + count / 3 * off * 2;
off = (type_sizes[type] - 1) << 3;
for(i = 0; i < count / 3; i++){
j = (tget(&rp, type, s->le) >> off) << 16;
j |= (tget(&gp, type, s->le) >> off) << 8;
j |= tget(&bp, type, s->le) >> off;
pal[i] = j;
}
break;
case TIFF_PLANAR:
if(value == 2){
av_log(s->avctx, AV_LOG_ERROR, "Planar format is not supported\n");
return -1;
}
break;
case TIFF_T4OPTIONS:
case TIFF_T6OPTIONS:
s->fax_opts = value;
break;
}
return 0;
}
| 1threat |
static void rbd_finish_aiocb(rbd_completion_t c, RADOSCB *rcb)
{
int ret;
rcb->ret = rbd_aio_get_return_value(c);
rbd_aio_release(c);
ret = qemu_rbd_send_pipe(rcb->s, rcb);
if (ret < 0) {
error_report("failed writing to acb->s->fds");
g_free(rcb);
}
}
| 1threat |
Class can't access its own private static constexpr method - Clang bug? : <p>This code does not compile in Clang (6,7,8,9,trunk), but compiles just fine in GCC (7.1, 8.1, 9.1):</p>
<pre class="lang-cpp prettyprint-override"><code>template<class T> struct TypeHolder { using type = T; };
template<int i>
class Outer {
private:
template<class T>
static constexpr auto compute_type() {
if constexpr (i == 42) {
return TypeHolder<bool>{};
} else {
return TypeHolder<T>{};
}
}
public:
template<class T>
using TheType = typename decltype(Outer<i>::compute_type<T>())::type;
};
int main() {
Outer<42>::TheType<int> i;
}
</code></pre>
<p>Clang tells me:</p>
<pre><code><source>:17:49: error: 'compute_type' is a private member of 'Outer<42>'
</code></pre>
<p>… which of course it is, but I'm trying to access that member from <em>inside</em> the same class. I don't see why it should not be accessible there. Have I hit (and should I file) a Clang bug?</p>
<p>You can toy around with the code at <a href="https://gcc.godbolt.org/z/9NxRTU" rel="noreferrer">Godbolt's compiler explorer</a>.</p>
| 0debug |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.