problem
stringlengths
26
131k
labels
class label
2 classes
Add another user for remote access Windows 10 : <p>So, I created remote access from my lap top to server(Windows 10). Now, how can I add more users, so they can log in from their lap tops with their microsoft accounts or whatever accounts they have?</p>
0debug
C# Not responding : I would just like to say that this is my first windows form application so bare with me :) **What the application should do** This application should take the input of time (seconds, minutes and hours) and shutdown the computer after that time. It should also update the text box with how long left until the computer has shut down. **What the application actually does** I had an issue that I 'fixed' where the called ac across threads weren't safe, so I fixed it and I don't get that error now. However, the updateThread doesn't update and print the time left; and the text box doesn't get "test" appended to it. The UI also becomes Not Responding. Any help would be much appreciated. Also, if you see anything else that could be done better, please comment and explain. Thanks! using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace ShutdownPC { public partial class Form1 : Form { int inputHours; int inputMinutes; int inputSeconds; Thread sleepingThread; Thread updatingThread; NotifyIcon shutdownPCIcon; Icon defaultIcon; public Form1() { InitializeComponent(); defaultIcon = new Icon("defaultIcon.ico"); shutdownPCIcon = new NotifyIcon(); shutdownPCIcon.Icon = defaultIcon; shutdownPCIcon.Visible = true; MenuItem progNameMenuItem = new MenuItem("ShutdownPC by Conor"); MenuItem breakMenuItem = new MenuItem("-"); MenuItem quitMenuItem = new MenuItem("Quit"); ContextMenu contextMenu = new ContextMenu(); contextMenu.MenuItems.Add(progNameMenuItem); contextMenu.MenuItems.Add(breakMenuItem); contextMenu.MenuItems.Add(quitMenuItem); shutdownPCIcon.ContextMenu = contextMenu; shutdownPCIcon.Text = "ShutdownPC"; quitMenuItem.Click += QuitMenuItem_Click; } private void QuitMenuItem_Click(object sender, EventArgs e) { shutdownPCIcon.Dispose(); sleepingThread.Abort(); updatingThread.Abort(); this.Close(); } public void sleepThread() { if (this.InvokeRequired) { this.Invoke(new MethodInvoker(sleepThread)); } else { textBox1.Enabled = false; textBox2.Enabled = false; textBox3.Enabled = false; button1.Enabled = false; int totalMilliseconds = ((inputHours * 3600) + (inputMinutes * 60) + inputSeconds) * 1000; Thread.Sleep(totalMilliseconds); //Process.Start("shutdown", "/s /t 0"); richTextBox1.AppendText(String.Format("test")); } } public void updateThread() { if (this.InvokeRequired) { this.Invoke(new MethodInvoker(updateThread)); } else { int totalSeconds = (inputHours * 3600) + (inputMinutes * 60) + inputSeconds; while (totalSeconds > 0) { TimeSpan time = TimeSpan.FromSeconds(totalSeconds); string timeOutput = time.ToString(@"hh\:mm\:ss"); richTextBox1.AppendText(String.Format(timeOutput)); Thread.Sleep(1000); richTextBox1.Clear(); totalSeconds--; } } } private void textBox1_TextChanged(object sender, EventArgs e) { inputHours = Convert.ToInt32(textBox1.Text); inputHours = int.Parse(textBox1.Text); } private void textBox2_TextChanged(object sender, EventArgs e) { inputMinutes = Convert.ToInt32(textBox2.Text); inputMinutes = int.Parse(textBox2.Text); } private void textBox3_TextChanged(object sender, EventArgs e) { inputSeconds = Convert.ToInt32(textBox3.Text); inputSeconds = int.Parse(textBox3.Text); } private void button1_Click(object sender, EventArgs e) { updatingThread = new Thread(new ThreadStart(updateThread)); updatingThread.Start(); sleepingThread = new Thread(new ThreadStart(sleepThread)); sleepingThread.Start(); } private void richTextBox1_TextChanged(object sender, EventArgs e) { } } }
0debug
@CreationTimestamp and @UpdateTimestamp : <p>This is my blog class </p> <pre><code>@Entity @Component @Table public class Blog implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id private String id; private String name; private String Description; @CreationTimestamp private Date createdOn; @UpdateTimestamp private Date updatedOn; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return Description; } public void setDescription(String description) { Description = description; } public Date getCreatedOn() { return createdOn; } public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } public Date getUpdatedOn() { return updatedOn; } public void setUpdatedOn(Date updatedOn) { this.updatedOn = updatedOn; } } </code></pre> <p>timestamps createdOn and updatedOn are stored successfully when new blog is created but when existing blog is updated updatedOn field is updated whereas createdOn field becomes null. I want createdOn field to retain the timestamp on which it is created. Can someone help out ?</p>
0debug
Swift 5: 'substring(to:)' is deprecated : <p>I`m newbie in Swift and I have simple code, that cut string from the end to special characters "$2F" and returned cutted off string:</p> <pre><code> let index2 = favUrlString.range(of: "%2F", options: .backwards)?.lowerBound favUrlString = index2.map(favUrlString.substring(to:))! </code></pre> <p>How I have to update this code to Swift 5?</p>
0debug
calculate time diffrence in pl/sql with shifts : i have two table the first table contains the record of a ticket with start date and end date. start_date | End_Date 21-02-2017 07:52:32 | 22-02-2017 09:56:32 21-02-2017 09:52:32 | 23-02-2017 17:52:32 the second table contains the details of the weekly shift: shift_day | Start_Time | End_Time MON 9:00 18:00 TUE 10:00 19:00 WED 9:00 18:00 THU 10:00 19:00 FRI 9:00 18:00 I am looking to get the time difference in the first table which will only include the time as per the second table.
0debug
void ff_snow_pred_block(SnowContext *s, uint8_t *dst, uint8_t *tmp, int stride, int sx, int sy, int b_w, int b_h, BlockNode *block, int plane_index, int w, int h){ if(block->type & BLOCK_INTRA){ int x, y; const unsigned color = block->color[plane_index]; const unsigned color4 = color*0x01010101; if(b_w==32){ for(y=0; y < b_h; y++){ *(uint32_t*)&dst[0 + y*stride]= color4; *(uint32_t*)&dst[4 + y*stride]= color4; *(uint32_t*)&dst[8 + y*stride]= color4; *(uint32_t*)&dst[12+ y*stride]= color4; *(uint32_t*)&dst[16+ y*stride]= color4; *(uint32_t*)&dst[20+ y*stride]= color4; *(uint32_t*)&dst[24+ y*stride]= color4; *(uint32_t*)&dst[28+ y*stride]= color4; } }else if(b_w==16){ for(y=0; y < b_h; y++){ *(uint32_t*)&dst[0 + y*stride]= color4; *(uint32_t*)&dst[4 + y*stride]= color4; *(uint32_t*)&dst[8 + y*stride]= color4; *(uint32_t*)&dst[12+ y*stride]= color4; } }else if(b_w==8){ for(y=0; y < b_h; y++){ *(uint32_t*)&dst[0 + y*stride]= color4; *(uint32_t*)&dst[4 + y*stride]= color4; } }else if(b_w==4){ for(y=0; y < b_h; y++){ *(uint32_t*)&dst[0 + y*stride]= color4; } }else{ for(y=0; y < b_h; y++){ for(x=0; x < b_w; x++){ dst[x + y*stride]= color; } } } }else{ uint8_t *src= s->last_picture[block->ref]->data[plane_index]; const int scale= plane_index ? (2*s->mv_scale)>>s->chroma_h_shift : 2*s->mv_scale; int mx= block->mx*scale; int my= block->my*scale; const int dx= mx&15; const int dy= my&15; const int tab_index= 3 - (b_w>>2) + (b_w>>4); sx += (mx>>4) - (HTAPS_MAX/2-1); sy += (my>>4) - (HTAPS_MAX/2-1); src += sx + sy*stride; if( (unsigned)sx >= FFMAX(w - b_w - (HTAPS_MAX-2), 0) || (unsigned)sy >= FFMAX(h - b_h - (HTAPS_MAX-2), 0)){ s->vdsp.emulated_edge_mc(tmp + MB_SIZE, src, stride, b_w+HTAPS_MAX-1, b_h+HTAPS_MAX-1, sx, sy, w, h); src= tmp + MB_SIZE; } av_assert2(s->chroma_h_shift == s->chroma_v_shift); av_assert2(b_w>1 && b_h>1); av_assert2((tab_index>=0 && tab_index<4) || b_w==32); if((dx&3) || (dy&3) || !(b_w == b_h || 2*b_w == b_h || b_w == 2*b_h) || (b_w&(b_w-1)) || !s->plane[plane_index].fast_mc ) mc_block(&s->plane[plane_index], dst, src, stride, b_w, b_h, dx, dy); else if(b_w==32){ int y; for(y=0; y<b_h; y+=16){ s->h264qpel.put_h264_qpel_pixels_tab[0][dy+(dx>>2)](dst + y*stride, src + 3 + (y+3)*stride,stride); s->h264qpel.put_h264_qpel_pixels_tab[0][dy+(dx>>2)](dst + 16 + y*stride, src + 19 + (y+3)*stride,stride); } }else if(b_w==b_h) s->h264qpel.put_h264_qpel_pixels_tab[tab_index ][dy+(dx>>2)](dst,src + 3 + 3*stride,stride); else if(b_w==2*b_h){ s->h264qpel.put_h264_qpel_pixels_tab[tab_index+1][dy+(dx>>2)](dst ,src + 3 + 3*stride,stride); s->h264qpel.put_h264_qpel_pixels_tab[tab_index+1][dy+(dx>>2)](dst+b_h,src + 3 + b_h + 3*stride,stride); }else{ av_assert2(2*b_w==b_h); s->h264qpel.put_h264_qpel_pixels_tab[tab_index ][dy+(dx>>2)](dst ,src + 3 + 3*stride ,stride); s->h264qpel.put_h264_qpel_pixels_tab[tab_index ][dy+(dx>>2)](dst+b_w*stride,src + 3 + 3*stride+b_w*stride,stride); } } }
1threat
How can I add Offline google maps on website that I am creating : <p>I am building a website which will be used in sea with no internet access and I need to show google maps and draw a path on it.</p> <p>Can you tell me how can I implement the offline google maps on the website?</p> <p>Thanks in advance! Cheers</p>
0debug
Taking input of a graph from text file in java till the end of file : <p>I have an input file which contains a weighted graph.</p> <pre><code>a b 2 a c 8 a d 14 b f 19 b d 25 c d 21 d g 13 d f 17 e f 9 e g 1 f g 5 </code></pre> <p>In each line first two inputs define nodes and third input defines the weight of edge between them.There is not specification in the beginning that how many nodes and how many edges I wish to take input.It will read till the end of file by itself.I want to read this file in java.Can anyone give me the solution for this?</p>
0debug
void hmp_pci_add(Monitor *mon, const QDict *qdict) { PCIDevice *dev = NULL; const char *pci_addr = qdict_get_str(qdict, "pci_addr"); const char *type = qdict_get_str(qdict, "type"); const char *opts = qdict_get_try_str(qdict, "opts"); if (!strncmp(pci_addr, "pci_addr=", 9)) { pci_addr += 9; } if (!opts) { opts = ""; } if (!strcmp(pci_addr, "auto")) pci_addr = NULL; if (strcmp(type, "nic") == 0) { dev = qemu_pci_hot_add_nic(mon, pci_addr, opts); } else if (strcmp(type, "storage") == 0) { dev = qemu_pci_hot_add_storage(mon, pci_addr, opts); } else { monitor_printf(mon, "invalid type: %s\n", type); } if (dev) { monitor_printf(mon, "OK root bus %s, bus %d, slot %d, function %d\n", pci_root_bus_path(dev), pci_bus_num(dev->bus), PCI_SLOT(dev->devfn), PCI_FUNC(dev->devfn)); } else monitor_printf(mon, "failed to add %s\n", opts); }
1threat
ram_addr_t qemu_ram_alloc_from_ptr(ram_addr_t size, void *host, MemoryRegion *mr, Error **errp) { RAMBlock *new_block; ram_addr_t addr; Error *local_err = NULL; size = TARGET_PAGE_ALIGN(size); new_block = g_malloc0(sizeof(*new_block)); new_block->mr = mr; new_block->used_length = size; new_block->max_length = max_size; new_block->fd = -1; new_block->host = host; if (host) { new_block->flags |= RAM_PREALLOC; } addr = ram_block_add(new_block, &local_err); if (local_err) { g_free(new_block); error_propagate(errp, local_err); return -1; } return addr; }
1threat
Invalid syntax error in an `if` statement which I am unable to understand? : <p>I went line by line and came up to this error.</p> <blockquote> <p>SyntaxError: invalid syntax</p> </blockquote> <p>In, the <code>emailRegex</code> gets highlighted</p> <p><code>if cell.value and isinstance(cell.value, str) emailRegex.match(cell.value):</code></p> <p>The complete code(python3.x)</p> <pre><code>import re, openpyxl, os, sys def sort_email_from_xl(): loc = input("Please enter path of the file:") os.chdir(loc) file = input("Filename:") wb = openpyxl.load_workbook(file, use_iterators=True) sheet = input("Which Sheet do you want to email?\n") return sheet wb.get_sheet_by_name(sheet) ws = wb.get_sheet_by_name(sheet) emailRegex = re.compile(r".*?([a-zA-Z0-9\._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,4}).*?") customeremails = [] #works fine till here in idle for row in ws.iter_rows(): for cell in row: if cell.value and isinstance(cell.value, str) emailRegex.match(cell.value): mail = emailRegex.match(cell.value) if mail: mail = mail.group(0) # use parentheses to call the function cell.text = mail customeremails.append(mail) print(customeremails) </code></pre> <p>Can someone point to a resource where I can read what exactly is going wrong? I have been trying to sort this function out for almost 12 hours now, with help from SO and reading through docs.</p> <p>Is the code fine after current error?</p> <p>Thanks</p>
0debug
How to fetch a query to get the following data? : <p>List the names and designation of those employees whose salary is greater than 2000 and address is US.</p>
0debug
def check_monthnumber(monthname3): if monthname3 =="April" or monthname3== "June" or monthname3== "September" or monthname3== "November": return True else: return False
0debug
JavaScript functions fire in codepen but not JSFiddle. Why? : <p>I'm trying to run a basic JavaScript function from an external file but I'm getting inconsistent results. Basically, I can't get a button's "onclick" event to fire when I put the script in an external JS page. I can get it work in CodePen:</p> <p><a href="http://codepen.io/ThatsIsJustCrazy/pen/ezzLyK" rel="nofollow">CodePen</a></p> <pre><code>nonsense code </code></pre> <p>but NOT in JSFiddle:</p> <p><a href="https://jsfiddle.net/m7ca8sns/" rel="nofollow">JS Fiddle Examlple</a></p> <p>I can always get it work when the script is part of the HTML page but I don't want to do that. Can you help? Thanks!</p>
0debug
static void bmdma_map(PCIDevice *pci_dev, int region_num, pcibus_t addr, pcibus_t size, int type) { PCIIDEState *d = DO_UPCAST(PCIIDEState, dev, pci_dev); int i; for(i = 0;i < 2; i++) { BMDMAState *bm = &d->bmdma[i]; d->bus[i].bmdma = bm; bm->bus = d->bus+i; bm->pci_dev = d; qemu_add_vm_change_state_handler(ide_dma_restart_cb, bm); register_ioport_write(addr, 1, 1, bmdma_cmd_writeb, bm); register_ioport_write(addr + 1, 3, 1, bmdma_writeb, bm); register_ioport_read(addr, 4, 1, bmdma_readb, bm); register_ioport_write(addr + 4, 4, 1, bmdma_addr_writeb, bm); register_ioport_read(addr + 4, 4, 1, bmdma_addr_readb, bm); register_ioport_write(addr + 4, 4, 2, bmdma_addr_writew, bm); register_ioport_read(addr + 4, 4, 2, bmdma_addr_readw, bm); register_ioport_write(addr + 4, 4, 4, bmdma_addr_writel, bm); register_ioport_read(addr + 4, 4, 4, bmdma_addr_readl, bm); addr += 8; } }
1threat
static int encode_packet(Jpeg2000EncoderContext *s, Jpeg2000ResLevel *rlevel, int precno, uint8_t *expn, int numgbits) { int bandno, empty = 1; *s->buf = 0; s->bit_index = 0; for (bandno = 0; bandno < rlevel->nbands; bandno++){ if (rlevel->band[bandno].coord[0][0] < rlevel->band[bandno].coord[0][1] && rlevel->band[bandno].coord[1][0] < rlevel->band[bandno].coord[1][1]){ empty = 0; break; } } put_bits(s, !empty, 1); if (empty){ j2k_flush(s); return 0; } for (bandno = 0; bandno < rlevel->nbands; bandno++){ Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; int yi, xi, pos; int cblknw = prec->nb_codeblocks_width; if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){ for (xi = 0; xi < cblknw; xi++, pos++){ prec->cblkincl[pos].val = prec->cblk[yi * cblknw + xi].ninclpasses == 0; tag_tree_update(prec->cblkincl + pos); prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - prec->cblk[yi * cblknw + xi].nonzerobits; tag_tree_update(prec->zerobits + pos); } } for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){ for (xi = 0; xi < cblknw; xi++, pos++){ int pad = 0, llen, length; Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi; if (s->buf_end - s->buf < 20) return -1; tag_tree_code(s, prec->cblkincl + pos, 1); if (!cblk->ninclpasses) continue; tag_tree_code(s, prec->zerobits + pos, 100); putnumpasses(s, cblk->ninclpasses); length = cblk->passes[cblk->ninclpasses-1].rate; llen = av_log2(length) - av_log2(cblk->ninclpasses) - 2; if (llen < 0){ pad = -llen; llen = 0; } put_bits(s, 1, llen); put_bits(s, 0, 1); put_num(s, length, av_log2(length)+1+pad); } } } j2k_flush(s); for (bandno = 0; bandno < rlevel->nbands; bandno++){ Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; int yi, cblknw = prec->nb_codeblocks_width; for (yi =0; yi < prec->nb_codeblocks_height; yi++){ int xi; for (xi = 0; xi < cblknw; xi++){ Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi; if (cblk->ninclpasses){ if (s->buf_end - s->buf < cblk->passes[cblk->ninclpasses-1].rate) return -1; bytestream_put_buffer(&s->buf, cblk->data, cblk->passes[cblk->ninclpasses-1].rate - cblk->passes[cblk->ninclpasses-1].flushed_len); bytestream_put_buffer(&s->buf, cblk->passes[cblk->ninclpasses-1].flushed, cblk->passes[cblk->ninclpasses-1].flushed_len); } } } } return 0; }
1threat
Python: Multiple packages in one repository or one package per repository? : <p>I have a big Python 3.7+ project and I am currently in the process of splitting it into multiple packages that can be installed separately. My initial thought was to have a single Git repository with multiple packages, each with its own setup.py. However, while doing some research on Google, I found people suggesting one repository per package: (e.g., <a href="https://stackoverflow.com/questions/44020652/python-setuptools-working-on-two-dependent-packages-in-a-single-repo">Python - setuptools - working on two dependent packages (in a single repo?)</a>). However, nobody provides a good explanation as to why they prefer such structure. </p> <p>So, my question are the following: </p> <ul> <li>What are the implications of having multiple packages (each with its own setup.py) on the same GitHub repo?</li> <li>Am I going to face issues with such a setup? </li> <li>Are the common Python tools (documentation generators, pypi packaging, etc) compatible with with such a setup?</li> <li>Is there a good reason to prefer one setup over the other?</li> <li>Please keep in mind that this is not an opinion-based question. I want to know if there are any technical issues or problems with any of the two approaches.</li> </ul> <p>Also, I am aware (and please correct me if I am wrong) that setuptools now allow to install dependencies from GitHub repos, even if the GitHub URL of the setup.py is not at the root of the repository.</p>
0debug
ssize_t vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen) { ssize_t ret; #ifdef CONFIG_VNC_TLS if (vs->tls.session) { ret = vnc_client_read_tls(&vs->tls.session, data, datalen); } else { #endif ret = qemu_recv(vs->csock, data, datalen, 0); #ifdef CONFIG_VNC_TLS } #endif VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret); return vnc_client_io_error(vs, ret, socket_error()); }
1threat
static void boston_mach_init(MachineState *machine) { DeviceState *dev; BostonState *s; Error *err = NULL; const char *cpu_model; MemoryRegion *flash, *ddr, *ddr_low_alias, *lcd, *platreg; MemoryRegion *sys_mem = get_system_memory(); XilinxPCIEHost *pcie2; PCIDevice *ahci; DriveInfo *hd[6]; Chardev *chr; int fw_size, fit_err; bool is_64b; if ((machine->ram_size % G_BYTE) || (machine->ram_size > (2 * G_BYTE))) { error_report("Memory size must be 1GB or 2GB"); exit(1); } cpu_model = machine->cpu_model ?: "I6400"; dev = qdev_create(NULL, TYPE_MIPS_BOSTON); qdev_init_nofail(dev); s = BOSTON(dev); s->mach = machine; s->cps = g_new0(MIPSCPSState, 1); if (!cpu_supports_cps_smp(cpu_model)) { error_report("Boston requires CPUs which support CPS"); exit(1); } is_64b = cpu_supports_isa(cpu_model, ISA_MIPS64); object_initialize(s->cps, sizeof(MIPSCPSState), TYPE_MIPS_CPS); qdev_set_parent_bus(DEVICE(s->cps), sysbus_get_default()); object_property_set_str(OBJECT(s->cps), cpu_model, "cpu-model", &err); object_property_set_int(OBJECT(s->cps), smp_cpus, "num-vp", &err); object_property_set_bool(OBJECT(s->cps), true, "realized", &err); if (err != NULL) { error_report("%s", error_get_pretty(err)); exit(1); } sysbus_mmio_map_overlap(SYS_BUS_DEVICE(s->cps), 0, 0, 1); flash = g_new(MemoryRegion, 1); memory_region_init_rom_device(flash, NULL, &boston_flash_ops, s, "boston.flash", 128 * M_BYTE, &err); memory_region_add_subregion_overlap(sys_mem, 0x18000000, flash, 0); ddr = g_new(MemoryRegion, 1); memory_region_allocate_system_memory(ddr, NULL, "boston.ddr", machine->ram_size); memory_region_add_subregion_overlap(sys_mem, 0x80000000, ddr, 0); ddr_low_alias = g_new(MemoryRegion, 1); memory_region_init_alias(ddr_low_alias, NULL, "boston_low.ddr", ddr, 0, MIN(machine->ram_size, (256 * M_BYTE))); memory_region_add_subregion_overlap(sys_mem, 0, ddr_low_alias, 0); xilinx_pcie_init(sys_mem, 0, 0x10000000, 32 * M_BYTE, 0x40000000, 1 * G_BYTE, get_cps_irq(s->cps, 2), false); xilinx_pcie_init(sys_mem, 1, 0x12000000, 32 * M_BYTE, 0x20000000, 512 * M_BYTE, get_cps_irq(s->cps, 1), false); pcie2 = xilinx_pcie_init(sys_mem, 2, 0x14000000, 32 * M_BYTE, 0x16000000, 1 * M_BYTE, get_cps_irq(s->cps, 0), true); platreg = g_new(MemoryRegion, 1); memory_region_init_io(platreg, NULL, &boston_platreg_ops, s, "boston-platregs", 0x1000); memory_region_add_subregion_overlap(sys_mem, 0x17ffd000, platreg, 0); if (!serial_hds[0]) { serial_hds[0] = qemu_chr_new("serial0", "null"); } s->uart = serial_mm_init(sys_mem, 0x17ffe000, 2, get_cps_irq(s->cps, 3), 10000000, serial_hds[0], DEVICE_NATIVE_ENDIAN); lcd = g_new(MemoryRegion, 1); memory_region_init_io(lcd, NULL, &boston_lcd_ops, s, "boston-lcd", 0x8); memory_region_add_subregion_overlap(sys_mem, 0x17fff000, lcd, 0); chr = qemu_chr_new("lcd", "vc:320x240"); qemu_chr_fe_init(&s->lcd_display, chr, NULL); qemu_chr_fe_set_handlers(&s->lcd_display, NULL, NULL, boston_lcd_event, s, NULL, true); ahci = pci_create_simple_multifunction(&PCI_BRIDGE(&pcie2->root)->sec_bus, PCI_DEVFN(0, 0), true, TYPE_ICH9_AHCI); g_assert(ARRAY_SIZE(hd) == ICH_AHCI(ahci)->ahci.ports); ide_drive_get(hd, ICH_AHCI(ahci)->ahci.ports); ahci_ide_create_devs(ahci, hd); if (machine->firmware) { fw_size = load_image_targphys(machine->firmware, 0x1fc00000, 4 * M_BYTE); if (fw_size == -1) { error_printf("unable to load firmware image '%s'\n", machine->firmware); exit(1); } } else if (machine->kernel_filename) { fit_err = load_fit(&boston_fit_loader, machine->kernel_filename, s); if (fit_err) { error_printf("unable to load FIT image\n"); exit(1); } gen_firmware(memory_region_get_ram_ptr(flash) + 0x7c00000, s->kernel_entry, s->fdt_base, is_64b); } else if (!qtest_enabled()) { error_printf("Please provide either a -kernel or -bios argument\n"); exit(1); } }
1threat
How to dynamic custom menu "Home icon button on blogspot : Boss, I need help about Blogspot. I have created a custom menu for my client. I added home icon on home tab. But, now problem is, when i click on home icon, it not going to main page exp:"mysite.blogspot.com". It showing me others link like this--> exp: "mysite.blogspot.com/index.html" Please help me. I need your help. please help me. Thanks
0debug
C pointer arithmetic confusion : <p>I have to answer if the following code compiles and which are the results:</p> <pre><code>char *s1 = "A String"; char *s2 = "Other String"; *s1 = *s2; </code></pre> <p>I didnt really find what happens in the background when you do declarations like that. Is s1 pointing to memory looking like this?: </p> <pre><code>|A| |S|t|r|i|n|g|\0| </code></pre> <p>In my understanding <code>*s1 = *s2</code> is the same like <code>s1[0] = s2[0]</code>, right? So why do I get a memory error? Shouldnt it be?:</p> <pre><code>|O| |S|t|r|i|n|g|\0| </code></pre>
0debug
Printf with unfixed length : <p>I need to </p> <blockquote> <p>printf(%?d)</p> </blockquote> <p>Where '?' is some int. How can I do it? I'm using pure c. I've tried to work with const char* array. But there was no result.</p>
0debug
Adding item in RecyclerView Fragment : <p>Apologies first of all because it is going to be a long question.</p> <p>I am creating a to do list using 2 RecyclerViews in 2 fragments following is the code.</p> <p>MainActivity.java</p> <pre><code>public class MainActivity extends AppCompatActivity { /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link FragmentPagerAdapter} derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ private SectionsPagerAdapter mSectionsPagerAdapter; private ViewPager mViewPager; private TaskDbHelper mHelper; public Tab1 incompleteTasks; public Tab2 completedTasks; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try{ final EditText taskEditText = new EditText(MainActivity.this); AlertDialog dialog = new AlertDialog.Builder(MainActivity.this) .setTitle("Add a new task") .setMessage("What do you want to do next?") .setView(taskEditText) .setPositiveButton("Add", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try{ mHelper = new TaskDbHelper(MainActivity.this); String task = String.valueOf(taskEditText.getText()); mHelper.adddata(MainActivity.this, task); //incompleteTasks.addTask(mHelper.getAddedTask("0").get(0)); incompleteTasks.updateUI(); } catch(Exception ex1){ Toast.makeText(MainActivity.this, (String)ex1.getMessage(), Toast.LENGTH_LONG).show(); } } }) .setNegativeButton("Cancel", null) .create(); dialog.show(); }catch (Exception ex) { Log.d("MainActivity", "Exception: " + ex.getMessage()); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). switch (position){ case 0: //Tab1 incompleteTasks = new Tab1(); incompleteTasks = new Tab1(); incompleteTasks.setContext(MainActivity.this); return incompleteTasks; case 1: //Tab2 completedTasks = new Tab2(); completedTasks = new Tab2(); completedTasks.setContext(MainActivity.this); return completedTasks ; default: return null; } } @Override public int getItemPosition(Object object) { // POSITION_NONE makes it possible to reload the PagerAdapter return POSITION_NONE; } @Override public int getCount() { // Show 3 total pages. return 2; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return "Incomplete"; case 1: return "Completed"; } return null; } } </code></pre> <p>}</p> <p>RecyclerAdapter.java</p> <pre><code>public class RecyclerAdapter extends RecyclerView.Adapter&lt;RecyclerAdapter.TaskHolder&gt; { private ArrayList&lt;Task&gt; mTasks; private boolean completedStatus; private Context contextFromTab; private int lastPosition = -1; private RecyclerViewAnimator mAnimator; //1 public class TaskHolder extends RecyclerView.ViewHolder implements View.OnClickListener { //2 private TextView mTask_id; private TextView mTask_title; private TextView mTask_created_date; private ImageButton mImageButtonDone; private ImageButton mImageButtonUndo; private ImageButton mImageButtonEdit; private ImageButton mImageButtonDelete; //3 //private static final String PHOTO_KEY = "PHOTO"; //4 public TaskHolder(View v) { super(v); try{ //v.geti mTask_id = v.findViewById(R.id.task_id); mTask_title = v.findViewById(R.id.task_title); mTask_created_date = v.findViewById(R.id.task_created_date); mImageButtonDone = v.findViewById(R.id.imageButtonDone); mImageButtonUndo = v.findViewById(R.id.imageButtonUndo); mImageButtonEdit = v.findViewById(R.id.imageButtonEdit); mImageButtonDelete = v.findViewById(R.id.imageButtonDelete); v.setOnClickListener(this); mImageButtonDone.setOnClickListener(this); mImageButtonUndo.setOnClickListener(this); mImageButtonEdit.setOnClickListener(this); mImageButtonDelete.setOnClickListener(this); //v.setAnimation(); } catch (Exception ex){ Log.d("TaskHolder", ex.getMessage()); } } //5 @Override public void onClick(View v) { if(v.equals(mImageButtonDone)){ View parent = (View) v.getParent(); TextView taskTextView = (TextView) parent.findViewById(R.id.task_id); String _id = String.valueOf(taskTextView.getText()); TaskDbHelper mHelper = new TaskDbHelper(contextFromTab); mHelper.changeTaskStatus(contextFromTab,true, _id); removeAt(getAdapterPosition()); } else if(v.equals(mImageButtonUndo)) { View parent = (View) v.getParent(); TextView taskTextView = parent.findViewById(R.id.task_id); String _id = String.valueOf(taskTextView.getText()); TaskDbHelper mHelper = new TaskDbHelper(contextFromTab); mHelper.changeTaskStatus(contextFromTab,false, _id); } else if(v.equals(mImageButtonEdit)) { View parent = (View) v.getParent(); TextView taskIdTextView = (TextView) parent.findViewById(R.id.task_id); TextView taskTitleTextView = (TextView) parent.findViewById(R.id.task_title); final String _id = String.valueOf(taskIdTextView.getText()); String _title = String.valueOf(taskTitleTextView.getText()); /*Intent intent = new Intent(this, TaskDetails.class); intent.putExtra("_id", _id); intent.putExtra("_title", _title); startActivity(intent);*/ try{ final EditText taskEditText = new EditText(contextFromTab); taskEditText.setText(_title); AlertDialog dialog = new AlertDialog.Builder(contextFromTab) .setTitle("Edit task") .setView(taskEditText) .setPositiveButton("Done", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try{ TaskDbHelper mHelper = new TaskDbHelper(contextFromTab); String task = String.valueOf(taskEditText.getText()); mHelper.editTask(contextFromTab, task, _id); updateAt(getAdapterPosition(), _id); /*Tab1 tab1 = new Tab1(); tab1.setContext(MainActivity.this); tab1.updateUI();*/ } catch(Exception ex1){ Toast.makeText(contextFromTab, (String)ex1.getMessage(), Toast.LENGTH_LONG).show(); } } }) .setNegativeButton("Cancel", null) .create(); dialog.show(); }catch (Exception ex) { Log.d("MainActivity", "Exception: " + ex.getMessage()); } } else if(v.equals(mImageButtonDelete)) { View parent = (View) v.getParent(); TextView taskTextView = (TextView) parent.findViewById(R.id.task_id); String _id = String.valueOf(taskTextView.getText()); TaskDbHelper mHelper = new TaskDbHelper(contextFromTab); mHelper.deleteTask(_id); removeAt(getAdapterPosition()); } Log.d("RecyclerView", "CLICK!"); } public void bindTask(Task task, boolean completedStatus) { try{ mTask_id.setText(Integer.toString(task._id) ); mTask_title.setText(task.title); mTask_created_date.setText("created on: " + task.created_datetime); if(completedStatus){ mImageButtonDone.setVisibility(View.INVISIBLE); mImageButtonUndo.setVisibility(View.VISIBLE); }else{ mImageButtonDone.setVisibility(View.VISIBLE); mImageButtonUndo.setVisibility(View.INVISIBLE); } } catch (Exception ex){ Log.d("bindTask", ex.getMessage()); } } public void addTask(Task task){ mTasks.add(0, task); notifyItemInserted(0); //smoothScrollToPosition(0); } public void removeAt(int position) { mTasks.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position, getItemCount()); } public void updateAt(int position, String task_id){ //mTasks. //mTasks.set(position); try{ TaskDbHelper mHelper = new TaskDbHelper(contextFromTab); Task updatedTask = mHelper.getTaskById(task_id); mTasks.set(position, updatedTask); notifyItemChanged(position); } catch (Exception ex){ } } } public RecyclerAdapter(ArrayList&lt;Task&gt; tasks, boolean tasksCompletedStatus, Context context, RecyclerView recyclerView) { mTasks = tasks; completedStatus = tasksCompletedStatus; contextFromTab = context; mAnimator = new RecyclerViewAnimator(recyclerView); } @Override public RecyclerAdapter.TaskHolder onCreateViewHolder(ViewGroup parent, int viewType) { try{ View inflatedView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_todo, parent, false); mAnimator.onCreateViewHolder(inflatedView); return new TaskHolder(inflatedView); } catch(Exception ex){ Log.d("onCreateViewHolder", ex.getMessage()); return null; } } private void setAnimation(View viewToAnimate, int position) { // If the bound view wasn't previously displayed on screen, it's animated if (position &gt; lastPosition) { Animation animation = AnimationUtils.loadAnimation(contextFromTab, android.R.anim.slide_in_left); animation.setDuration(3000); viewToAnimate.startAnimation(animation); lastPosition = position; } } @Override public void onBindViewHolder(RecyclerAdapter.TaskHolder holder, int position) { try{ Task itemTask = mTasks.get(position); holder.bindTask(itemTask, completedStatus); mAnimator.onBindViewHolder(holder.itemView, position); } catch(Exception ex){ Log.d("onBindViewHolder", ex.getMessage()); } } @Override public int getItemCount() { try{ return mTasks.size(); } catch(Exception ex){ Log.d("getItemCount", ex.getMessage()); return 0; } } public ArrayList&lt;Task&gt; getListTasks(){ return mTasks; } </code></pre> <p>}</p> <p>TaskDBHelper.java</p> <pre><code>public class TaskDbHelper extends SQLiteOpenHelper{ // Table Name public static final String TABLE_NAME = "tasks"; // Table columns public static final String _ID = "_id"; public static final String COL_TASK_TITLE = "title"; public static final String COL_TASK_PARENT_ID = "parent_id"; public static final String COL_TASK_COMPLETED_STATUS = "completed_status"; public static final String COL_TASK_CREATED_DATETIME = "created_datetime"; public static final String COL_TASK_MODIFIED_DATETIME = "modified_datetime"; // Database Information static final String DB_NAME = "com.sagarmhatre.simpletodo"; // database version static final int DB_VERSION = 1; public TaskDbHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { try { String createTable = "CREATE TABLE " + TABLE_NAME + " ( " + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_TASK_TITLE + " TEXT NOT NULL," + COL_TASK_PARENT_ID + " INTEGER DEFAULT 0," + COL_TASK_COMPLETED_STATUS + " BOOLEAN DEFAULT 0," + COL_TASK_CREATED_DATETIME + " DATETIME DEFAULT (DATETIME(CURRENT_TIMESTAMP, 'LOCALTIME'))," + COL_TASK_MODIFIED_DATETIME + " DATETIME" +");"; db.execSQL(createTable); } catch (Exception ex){ Log.d("TaskDbHelper", "Exception: " + ex.getMessage()); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } //Insert Value public void adddata(Context context,String task_title) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COL_TASK_TITLE, task_title); db.insert(TABLE_NAME, null, values); db.close(); } public Task adddataWithReturnTask(Context context,String task_title) { try{ SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COL_TASK_TITLE, task_title); db.insert(TABLE_NAME, null, values); db.close(); ArrayList&lt;Task&gt; taskList = this.getAddedTask("0"); return taskList.get(0); } catch(Exception ex){ Log.d("MainActivity", "Exception: " + ex.getMessage()); return null; } } //Delete Query public void deleteTask(String id) { String deleteQuery = "DELETE FROM " + TABLE_NAME + " where " + _ID + "= " + id ; SQLiteDatabase db = this.getReadableDatabase(); db.execSQL(deleteQuery); } public void changeTaskStatus(Context context,Boolean taskStatus, String id) { try{ SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); if(taskStatus) values.put(COL_TASK_COMPLETED_STATUS, 1); else values.put(COL_TASK_COMPLETED_STATUS, 0); db.update(TABLE_NAME, values, _ID + "=" + id, null); db.close(); } catch(Exception ex){ Log.d("changeTaskStatus() ", "Exception: " + ex.getMessage()); } } // Edit task - by me public void editTask(Context context,String task_title, String id) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COL_TASK_TITLE, task_title); db.update(TABLE_NAME, values, _ID + "=" + id, null); db.close(); } //Get Row Count public int getCount() { String countQuery = "SELECT * FROM " + TABLE_NAME; int count = 0; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(countQuery, null); if(cursor != null &amp;&amp; !cursor.isClosed()){ count = cursor.getCount(); cursor.close(); } return count; } //Get FavList public ArrayList&lt;Task&gt; getTaskList(String ParentID, Boolean completedStatus){ try{ String selectQuery; if(completedStatus){ selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "+ COL_TASK_PARENT_ID + "="+ParentID+ " AND " + COL_TASK_COMPLETED_STATUS + " = " + 1 + " ORDER BY " + _ID + " DESC"; }else{ selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "+ COL_TASK_PARENT_ID + "="+ParentID+ " AND " + COL_TASK_COMPLETED_STATUS + " = " + 0 + " ORDER BY " + _ID + " DESC"; } SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); ArrayList&lt;Task&gt; TaskList = new ArrayList&lt;Task&gt;(); if (cursor.moveToFirst()) { do { Task task = new Task(); task._id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(_ID))); task.title = cursor.getString(1); task.parent_id = Integer.parseInt(cursor.getString(2)); task.completed_status = Boolean.parseBoolean(cursor .getString(3)); task.created_datetime = cursor.getString(4); task.modified_datetime = cursor.getString(5); TaskList.add(task); } while (cursor.moveToNext()); } return TaskList; } catch(Exception ex){ Log.d("getTaskList() ", "Exception: " + ex.getMessage()); return null; } } public Task getTaskById(String _id){ try{ String selectQuery; selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "+ _ID + "="+_id; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); ArrayList&lt;Task&gt; TaskList = new ArrayList&lt;Task&gt;(); if (cursor.moveToFirst()) { do { Task task = new Task(); task._id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(_ID))); task.title = cursor.getString(1); task.parent_id = Integer.parseInt(cursor.getString(2)); task.completed_status = Boolean.parseBoolean(cursor .getString(3)); task.created_datetime = cursor.getString(4); task.modified_datetime = cursor.getString(5); TaskList.add(task); } while (cursor.moveToNext()); } return TaskList.get(0); } catch(Exception ex){ Log.d("getTaskList() ", "Exception: " + ex.getMessage()); return null; } } public ArrayList&lt;Task&gt; getAddedTask(String ParentID){ try{ String selectQuery; selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "+ COL_TASK_PARENT_ID + "="+ParentID+ " AND " + COL_TASK_COMPLETED_STATUS + " = " + 0 + " ORDER BY " + _ID + " DESC"; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); ArrayList&lt;Task&gt; TaskList = new ArrayList&lt;Task&gt;(); if (cursor.moveToFirst()) { do { Task task = new Task(); task._id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(_ID))); task.title = cursor.getString(1); task.parent_id = Integer.parseInt(cursor.getString(2)); task.completed_status = Boolean.parseBoolean(cursor .getString(3)); task.created_datetime = cursor.getString(4); task.modified_datetime = cursor.getString(5); TaskList.add(task); } while (cursor.moveToNext()); } return TaskList; } catch(Exception ex){ Log.d("getTaskList() ", "Exception: " + ex.getMessage()); return null; } } </code></pre> <p>}</p> <p>Tab1.java</p> <pre><code>public class Tab1 extends Fragment { private static final String TAG = "Tab1"; private TaskDbHelper mHelper; //int listResourceID; //ViewAdapter viewAdapter; Context incompleteListContext; Toolbar toolbar; private RecyclerView mRecyclerView; private LinearLayoutManager mLinearLayoutManager; RecyclerAdapter adapter; public void setContext(Context context){ this.incompleteListContext = context; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.tab1, container, false); mRecyclerView = rootView.findViewById(R.id.list_todo); mRecyclerView.setHasFixedSize(true); //mRecyclerView.setItemAnimator(new SlideInLeftAnimator()); //SlideInUpAnimator animator = new SlideInUpAnimator(new OvershootInterpolator()); //mRecyclerView.setItemAnimator(animator); mLinearLayoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setLayoutManager(mLinearLayoutManager); updateUI(); return rootView; } //@Override //public void onViewCreated(View rootView, Bundle savedInstanceState){ //incompleteList = rootView.findViewById(R.id.list_todo_completed); //updateUI(); //} public void updateUI() { try { mHelper = new TaskDbHelper(incompleteListContext); ArrayList&lt;Task&gt; taskList = mHelper.getTaskList("0",false); adapter = new RecyclerAdapter(taskList, false, incompleteListContext, mRecyclerView); mRecyclerView.setAdapter(adapter); } catch (Exception ex) { Log.d(TAG, "Exception: " + ex.getMessage()); } } public RecyclerView getRecyclerView(){ return mRecyclerView; } </code></pre> <p>}</p> <p>So far I am successful in implementing delete and update operation without reloading the whole list in Tab1. But after adding an item I want to add it to the top and I am unable to do it as seen in most of RecyclerView tutorials. SO currently I reload the whole list (which I Know is not appropriate).</p> <p>Need a way to not load whole list and add item at the top of list. Being new to android development, any kind of help is welcome. </p>
0debug
assign variable only if it is null : <p>on Ruby one have something like this:</p> <pre><code>@var ||= 'value' </code></pre> <p>basically, it means that <code>@var</code> will be assigned <code>'value'</code> only if <code>@var</code> is not assigned yet (e.g. if <code>@var</code> is <code>nil</code>)</p> <p>I'm looking for the same on Kotlin, but so far, the closest thing would be the elvis operator. Is there something like that and I missed the documentation?</p>
0debug
How to trim unwanted fields in a JavaScript object? : For example, I have const eva = {name: "Eva", age: 3, hobby: "dance", state: "NY"}; const ann = {name: "Ann", age: 9, hobby: "read", state: "WA", schoolyear: 3}; I want to have a trim function, which only keeps the fields I want. cosnt fields = ["name", "age", "state"] and the output will be const eva2 = {name: "Eva", age: 3, state: "NY"}; const ann2 = {name: "Ann", age: 9, state: "WA"}; Thanks!
0debug
How can i clear the quantity and price field when i select no product in the drop down? : When i select product from the drop down price and quantity came out from the database and when i Select the option **SELECT MOTHERBOARD** that have no value so that quantity and price field should be empty but the quantity field show the value **1** and Total Price field show **0** instead of empty text field. How can i sort-out this issue. > When i select product from drop-down. [Image][1] > When i click on **Select Motherboard** option from drop-down [Image][2] [1]: https://i.stack.imgur.com/XbW0f.png [2]: https://i.stack.imgur.com/E6y2I.png <tr class="category motherboard" data-value="motherboard"> <td> <span>Motherboard</span> </td> <td> <select name="motherboard" id="motherboard" style="min-width: 100%;" class="select" onchange="getPrice(event)"> <option>Select Motherboard</option> <?php echo motherboard_brand($connect); ?> </select> </td> <!-- QUANTITY --> <td> <input type="number" min="0" name="email" class="quantity" oninput="setTotalPrice(event)"/> </td> <!-- per item price --> <td> <input type="text" readonly class="unit-price" > </td> <!-- Total Price --> <td> <input type="text" readonly class="total-price"> </td> </tr> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> function getPrice(e){ e.preventDefault(); grandtotal(); var id = $(e.target).val(); // console.log(id); let parent = e.target.parentNode.parentNode; // console.log(parent); let category = parent.getAttribute("data-value"); // console.log(category); $.ajax({ url:"load_data.php", method:"POST", data:{id:id}, success:function(data){ // console.log(id); let unitPrice = parent.querySelector("input.unit-price"); // console.log(unitPrice); unitPrice.value = data; $(parent).attr("data-id", id); $(parent).attr("data-quantity", 1); parent.querySelector("input.quantity").value = 1; parent.querySelector("input.total-price").value = +data * 1; grandtotal(); } }); } function setTotalPrice(e){ e.preventDefault(); // console.log(event.target); let parent = e.target.parentNode.parentNode; // console.log(parent); let unitPrice = parent.querySelector("input.unit-price").value; let quantity = parent.querySelector("input.quantity").value; $(parent).attr("data-quantity", quantity); parent.querySelector("input.total-price").value = (+unitPrice) * (+quantity); grandtotal(); } // Grand Total function grandtotal() { var sum=0; $('.total-price').each(function(){ var item_val=parseFloat($(this).val()); if(isNaN(item_val)){ item_val=0; } sum+=item_val; $('#TotalPrice').html(sum.toFixed(2)); }); } </script>
0debug
Apache Commons IO - Encrypt download from Website : <p>With Apache Commons Io you can download Files from the Internet (<code>FileUtils.copyURLToFile(URL, File)</code>). But is this download encrypted? If no how can I encrypt a download from the Internet? </p> <p>PS: I want to download from a Website/Filehost like Mediafire.</p>
0debug
roc_auc_score - Only one class present in y_true : <p>I am doing a k-fold XV on an existing dataframe, and I need to get the AUC score. The problem is - sometimes the test data only contains 0s, and not 1s!</p> <p>I tried using <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html" rel="noreferrer">this</a> example, but with different numbers:</p> <pre><code>import numpy as np from sklearn.metrics import roc_auc_score y_true = np.array([0, 0, 0, 0]) y_scores = np.array([1, 0, 0, 0]) roc_auc_score(y_true, y_scores) </code></pre> <p>And I get this exception:</p> <blockquote> <p>ValueError: Only one class present in y_true. ROC AUC score is not defined in that case.</p> </blockquote> <p>Is there any workaround that can make it work in such cases?</p>
0debug
Solving Http Status 500 Servlet Exeution threw an exeption for Simple Login Servlet : /* hi here is the code for simple login servlet in eclips which checks username and password from the existing table of database and take it to home page if exists or send to login page. When I run it on server and put information in login page it shows following error. can you help for that please. thank you. */ **[strong text][1]** ERROR TO SOLVE HTTP Status 500 - Servlet execution threw an exception ------------------------------------------------------------------------ -------- type Exception report message Servlet execution threw an exception description The server encountered an internal error that prevented it from fulfilling this request. exception javax.servlet.ServletException: Servlet execution threw an exception root cause java.lang.Error: Unresolved compilation problem: Unreachable catch block for ClassNotFoundException. This exception is never thrown from the try statement body com.loginapps.servlets.LoginServlet.doGet(LoginServlet.java:90) javax.servlet.http.HttpServlet.service(HttpServlet.java:617) javax.servlet.http.HttpServlet.service(HttpServlet.java:723) CODING package com.loginapps.servlets; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.ResultSet; import java.sql.PreparedStatement; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class LoginServlet * @param <con> */ public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; Connection con; PreparedStatement pst; public void init(ServletConfig config) throws ServletException { String dname = config.getInitParameter("drivername"); String uname = config.getInitParameter("username"); System.out.println(dname); System.out.println(uname); try { Class.forName(dname); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/logindb",uname,""); } catch(SQLException e) { e.printStackTrace(); } catch(ClassNotFoundException e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub HttpSession session = request.getSession(); String uname = request.getParameter("txtuname"); String pwd = request.getParameter("txtpwd"); session.setAttribute("username",uname); try { pst = con.prepareStatement("select * from users where username = ? and password = ?"); pst.setString(1,uname); pst.setString(2,pwd); ResultSet rs = pst.executeQuery(); if(rs.next()) { response.sendRedirect("home.jsp"); } else { response.sendRedirect("login.html"); } } catch(SQLException e) { e.printStackTrace(); } catch(ClassNotFoundException e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
0debug
BlockDriverState *bdrv_next_node(BlockDriverState *bs) { if (!bs) { return QTAILQ_FIRST(&graph_bdrv_states); } return QTAILQ_NEXT(bs, node_list); }
1threat
static void vgafb_update_display(void *opaque) { MilkymistVgafbState *s = opaque; SysBusDevice *sbd; DisplaySurface *surface = qemu_console_surface(s->con); int first = 0; int last = 0; drawfn fn; if (!vgafb_enabled(s)) { return; } sbd = SYS_BUS_DEVICE(s); int dest_width = s->regs[R_HRES]; switch (surface_bits_per_pixel(surface)) { case 0: return; case 8: fn = draw_line_8; break; case 15: fn = draw_line_15; dest_width *= 2; break; case 16: fn = draw_line_16; dest_width *= 2; break; case 24: fn = draw_line_24; dest_width *= 3; break; case 32: fn = draw_line_32; dest_width *= 4; break; default: hw_error("milkymist_vgafb: bad color depth\n"); break; } framebuffer_update_display(surface, sysbus_address_space(sbd), s->regs[R_BASEADDRESS] + s->fb_offset, s->regs[R_HRES], s->regs[R_VRES], s->regs[R_HRES] * 2, dest_width, 0, s->invalidate, fn, NULL, &first, &last); if (first >= 0) { dpy_gfx_update(s->con, 0, first, s->regs[R_HRES], last - first + 1); } s->invalidate = 0; }
1threat
static inline void t_gen_subx_carry(DisasContext *dc, TCGv d) { if (dc->flagx_known) { if (dc->flags_x) { TCGv c; c = tcg_temp_new(TCG_TYPE_TL); t_gen_mov_TN_preg(c, PR_CCS); tcg_gen_andi_tl(c, c, C_FLAG); tcg_gen_sub_tl(d, d, c); tcg_temp_free(c); } } else { TCGv x, c; x = tcg_temp_new(TCG_TYPE_TL); c = tcg_temp_new(TCG_TYPE_TL); t_gen_mov_TN_preg(x, PR_CCS); tcg_gen_mov_tl(c, x); tcg_gen_andi_tl(c, c, C_FLAG); tcg_gen_andi_tl(x, x, X_FLAG); tcg_gen_shri_tl(x, x, 4); tcg_gen_and_tl(x, x, c); tcg_gen_sub_tl(d, d, x); tcg_temp_free(x); tcg_temp_free(c); } }
1threat
Ionic - ion-item text is not vertically centered when ion-icon is bigger : <p>I have a list of ion-items with an icon followed by text. When the icon size is smaller as seen on the image below, the text seems to vertically align itself to the center of the ion-item. But when the icon is bigger, the alignment is a bit off. </p> <p><a href="https://i.stack.imgur.com/efZu7.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/efZu7.jpg" alt="enter image description here"></a></p> <p>This is all I've added:</p> <pre><code>&lt;ion-item&gt; &lt;ion-icon class="icon ion-ios-clock-outline"&gt;&lt;/ion-icon&gt; Recent &lt;/ion-item&gt; </code></pre> <p>And the CSS:</p> <pre><code>.icon { font-size: 35px; color: #ffC977; } </code></pre> <p>How can I fix this. I tried using <code>vertical-align</code>, <code>align-item</code> and <code>align-self</code>. None of them worked.</p>
0debug
Login with Facebook sdk not getting email on swift 4 : When login with Facebook sdk email not getting, only getting name and picture.
0debug
CoreData ManagedObjectContext Recursive Save Error : <p>Some users of mine are encountering a CoreData error when performing a save. I haven't been able to find any information online about this error or how to symbolicate the stack trace.</p> <p>The error message is <code>attempt to recursively call -save: on the context aborted, stack trace</code>, with the full error message below.</p> <p>Doe anyone have any hints or ideas on how to figure out what is going wrong?</p> <pre><code>Error Domain=NSCocoaErrorDomain Code=132001 "(null)" UserInfo={message=attempt to recursively call -save: on the context aborted, stack trace=( 0 CoreData 0x0000000188cbe70c + 164 1 Primetime 0x0000000100077ea4 Primetime + 130724 2 Primetime 0x00000001000ae988 Primetime + 354696 3 Primetime 0x0000000100081674 Primetime + 169588 4 Primetime 0x00000001000802ac Primetime + 164524 5 CoreData 0x0000000188d8bbd4 + 4568 6 CoreData 0x0000000188d8a9ec + 124 7 CoreFoundation 0x00000001869ac24c + 20 8 CoreFoundation 0x00000001869ab950 + 400 9 CoreFoundation 0x00000001869ab6cc + 60 10 CoreFoundation 0x0000000186a187bc + 1504 11 CoreFoundation 0x00000001868ef32c _CFXNotificationPost + 376 12 Foundation 0x000000018738296c + 68 13 CoreData 0x0000000188cc16e8 + 724 14 CoreData 0x0000000188d43ca4 + 1336 15 CoreData 0x0000000188cbfd04 + 2116 16 CoreData 0x0000000188cbe808 + 416 17 Primetime 0x0000000100077ea4 Primetime + 130724 18 Primetime 0x0000000100089968 Primetime + 203112 19 Primetime 0x00000001001d47c0 Primetime + 1558464 20 libdispatch.dylib 0x0000000186459058 + 24 21 libdispatch.dylib 0x0000000186459018 + 16 22 libdispatch.dylib 0x000000018645dbcc _dispatch_main_queue_callback_4CF + 1000 23 CoreFoundation 0x00000001869bfc48 + 12 24 CoreFoundation 0x00000001869bd834 + 1660 25 CoreFoundation 0x00000001868ed764 CFRunLoopRunSpecific + 292 26 GraphicsServices 0x00000001882f0198 GSEventRunModal + 180 27 UIKit 0x000000018c8668d0 + 664 28 UIKit 0x000000018c86163c UIApplicationMain + 208 29 Primetime 0x00000001000ada1c Primetime + 350748 30 libdyld.dylib 0x00000001864905b8 + 4 </code></pre>
0debug
it is possible to find data accoding to date in spring : I'm trying to find data according to date throw the exception **java.lang.IllegalArgumentException: null** @SuppressWarnings("deprecation") @GetMapping("/product-DateList/{pathDate}") public ModelAndView getFindByDateOfPurchase(@PathVariable("pathDate") String pathDate) { Date convertDate = new Date //Date Converted according to dataBase Format SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String strDate = sdf.format(convertDate); Date date = null; try { date = DateFormat.getInstance().parse(strDate); } catch (ParseException pe) { pe.printStackTrace(); } List<Product> dateofPurchaseList = grofersService.findByDateOfPurchase(date); Optional<List<Product>> optional = Optional.of(dateofPurchaseList); if (!optional.isPresent()) { logger.warn("Not Found Product"); return new ModelAndView("notFound"); } logger.info("Fetching Product according to Date"); return new ModelAndView("productList", "dateofPurchaseList", dateofPurchaseList); } Please suggest me how to solve this problem.
0debug
My Date Formatter Isn't Showing Correct Day : I am trying to show today's date as March 26 but it is showing as "March 85" when I use this code. I am not sure why. let formatter = DateFormatter() formatter.dateFormat = "MMMM DD" let defaultTimeZoneStr = formatter.string(from: NSDate() as Date)
0debug
static void bt_dummy_lmp_disconnect_master(struct bt_link_s *link) { fprintf(stderr, "%s: stray LMP_detach received, fixme\n", __func__); exit(-1); }
1threat
static uint32_t hpet_ram_readw(void *opaque, target_phys_addr_t addr) { printf("qemu: hpet_read w at %" PRIx64 "\n", addr); return 0; }
1threat
What is the use of autoscroll to source and and autoscroll from source features in Intellij IDEs? : <p>I was looking for how to show the open files in project view and found theses two features, I want to know what does the above mentioned features do?</p>
0debug
C# WebClient NTLM authentication starting for each request : <p>Consider a simple C# NET Framework 4.0 application, that:</p> <ul> <li>uses WebClient</li> <li>authenticates using NTLM (tested on IIS 6.0 and IIS 7.5 server)</li> <li>retrieves a string from an URL multiple times using DownloadString()</li> </ul> <p>Here's a sample that works fine:</p> <pre><code>using System; using System.Net; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string URL_status = "http://localhost/status"; CredentialCache myCache = new CredentialCache(); myCache.Add(new Uri(URL_status), "NTLM", new NetworkCredential("username", "password", "domain")); WebClient WebClient = new WebClient(); WebClient.Credentials = myCache; for (int i = 1; i &lt;= 5; i++) { string Result = WebClient.DownloadString(new Uri(URL_status)); Console.WriteLine("Try " + i.ToString() + ": " + Result); } Console.Write("Done"); Console.ReadKey(); } } } </code></pre> <p><strong>The problem:</strong></p> <p>When enabling tracing I see that the NTLM authentication does not persist.</p> <p>Each time Webclient.DownloadString is called, NTLM authentication starts (server returns "WWW-Authenticate: NTLM" header and the whole authenticate/authorize process repeats; there is no "Connection: close" header).</p> <p>Wasn't NTLM supposed to authenticate a connection, not a request?</p> <p>Is there a way to make WebClient reuse an existing connection to avoid having to re-authenticate each request?</p>
0debug
void do_migrate_set_speed(Monitor *mon, const QDict *qdict) { double d; char *ptr; FdMigrationState *s; const char *value = qdict_get_str(qdict, "value"); d = strtod(value, &ptr); switch (*ptr) { case 'G': case 'g': d *= 1024; case 'M': case 'm': d *= 1024; case 'K': case 'k': d *= 1024; default: break; } max_throttle = (uint32_t)d; s = migrate_to_fms(current_migration); if (s && s->file) { qemu_file_set_rate_limit(s->file, max_throttle); } }
1threat
static void dequantization_int_97(int x, int y, Jpeg2000Cblk *cblk, Jpeg2000Component *comp, Jpeg2000T1Context *t1, Jpeg2000Band *band) { int i, j; int w = cblk->coord[0][1] - cblk->coord[0][0]; for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) { int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x]; int *src = t1->data[j]; for (i = 0; i < w; ++i) datap[i] = (src[i] * (int64_t)band->i_stepsize + (1<<14)) >> 15; } }
1threat
Where to put images in a react-native project? : <p>I am working on a react-native project and we are putting images currently in <code>/images/</code> folder. Is it a good path for them ? Is there any best practice? </p> <p><a href="https://i.stack.imgur.com/Spym8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Spym8.png" alt="enter image description here"></a></p>
0debug
WARNING: API 'variant.getMappingFile()' is obsolete and has been replaced with 'variant.getMappingFileProvider()' : <p>I just updated Android Studio 3.5 to Android Studio 3.6 and replaced previous Gradle plugin with Gradle plugin 3.6.0 when syncing Gradle:</p> <blockquote> <p>build.gradle: API 'variant.getMappingFile()' is obsolete and has been replaced with 'variant.getMappingFileProvider()'</p> </blockquote> <p>Any suggestions on how to debug this warning. Where is it coming from? I don't see any usage of getMappingFile in my code although, might be some library. Suggestions to debug these kind of cases would be helpful </p>
0debug
static int decode(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { BC_STATUS ret; BC_DTS_STATUS decoder_status = { 0, }; CopyRet rec_ret; CHDContext *priv = avctx->priv_data; HANDLE dev = priv->dev; uint8_t *in_data = avpkt->data; int len = avpkt->size; int free_data = 0; uint8_t pic_type = 0; av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n"); if (avpkt->size == 7 && !priv->bframe_bug) { av_log(avctx, AV_LOG_INFO, "CrystalHD: Enabling work-around for packed b-frame bug\n"); priv->bframe_bug = 1; } else if (avpkt->size == 8 && priv->bframe_bug) { av_log(avctx, AV_LOG_INFO, "CrystalHD: Disabling work-around for packed b-frame bug\n"); priv->bframe_bug = 0; } if (len) { int32_t tx_free = (int32_t)DtsTxFreeSize(dev); if (priv->bsfc) { int ret = 0; AVPacket filter_packet = { 0 }; AVPacket filtered_packet = { 0 }; ret = av_packet_ref(&filter_packet, avpkt); if (ret < 0) { av_log(avctx, AV_LOG_ERROR, "CrystalHD: mpv4toannexb filter " "failed to ref input packet\n"); return ret; } ret = av_bsf_send_packet(priv->bsfc, &filter_packet); if (ret < 0) { av_log(avctx, AV_LOG_ERROR, "CrystalHD: mpv4toannexb filter " "failed to send input packet\n"); return ret; } ret = av_bsf_receive_packet(priv->bsfc, &filtered_packet); if (ret < 0) { av_log(avctx, AV_LOG_ERROR, "CrystalHD: mpv4toannexb filter " "failed to receive output packet\n"); return ret; } in_data = filtered_packet.data; len = filtered_packet.size; av_packet_unref(&filter_packet); } if (priv->parser) { int ret = 0; free_data = ret > 0; if (ret >= 0) { uint8_t *pout; int psize; int index; H264Context *h = priv->parser->priv_data; index = av_parser_parse2(priv->parser, avctx, &pout, &psize, in_data, len, avctx->internal->pkt->pts, avctx->internal->pkt->dts, 0); if (index < 0) { av_log(avctx, AV_LOG_WARNING, "CrystalHD: Failed to parse h.264 packet to " "detect interlacing.\n"); } else if (index != len) { av_log(avctx, AV_LOG_WARNING, "CrystalHD: Failed to parse h.264 packet " "completely. Interlaced frames may be " "incorrectly detected.\n"); } else { av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: parser picture type %d\n", h->picture_structure); pic_type = h->picture_structure; } } else { av_log(avctx, AV_LOG_WARNING, "CrystalHD: mp4toannexb filter failed to filter " "packet. Interlaced frames may be incorrectly " "detected.\n"); } } if (len < tx_free - 1024) { uint64_t pts = opaque_list_push(priv, avctx->internal->pkt->pts, pic_type); if (!pts) { if (free_data) { av_freep(&in_data); } return AVERROR(ENOMEM); } av_log(priv->avctx, AV_LOG_VERBOSE, "input \"pts\": %"PRIu64"\n", pts); ret = DtsProcInput(dev, in_data, len, pts, 0); if (free_data) { av_freep(&in_data); } if (ret == BC_STS_BUSY) { av_log(avctx, AV_LOG_WARNING, "CrystalHD: ProcInput returned busy\n"); usleep(BASE_WAIT); return AVERROR(EBUSY); } else if (ret != BC_STS_SUCCESS) { av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcInput failed: %u\n", ret); return -1; } avctx->has_b_frames++; } else { av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n"); len = 0; } } else { av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n"); } if (priv->skip_next_output) { av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n"); priv->skip_next_output = 0; avctx->has_b_frames--; return len; } ret = DtsGetDriverStatus(dev, &decoder_status); if (ret != BC_STS_SUCCESS) { av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n"); return -1; } if (priv->output_ready < 2) { if (decoder_status.ReadyListCount != 0) priv->output_ready++; usleep(BASE_WAIT); av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n"); return len; } else if (decoder_status.ReadyListCount == 0) { usleep(BASE_WAIT); priv->decode_wait += WAIT_UNIT; av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n"); return len; } do { rec_ret = receive_frame(avctx, data, got_frame); if (rec_ret == RET_OK && *got_frame == 0) { av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n"); avctx->has_b_frames--; } else if (rec_ret == RET_COPY_NEXT_FIELD) { av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n"); while (1) { usleep(priv->decode_wait); ret = DtsGetDriverStatus(dev, &decoder_status); if (ret == BC_STS_SUCCESS && decoder_status.ReadyListCount > 0) { rec_ret = receive_frame(avctx, data, got_frame); if ((rec_ret == RET_OK && *got_frame > 0) || rec_ret == RET_ERROR) break; } } av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n"); } else if (rec_ret == RET_SKIP_NEXT_COPY) { av_log(avctx, AV_LOG_VERBOSE, "Don't output on next decode call.\n"); priv->skip_next_output = 1; } } while (rec_ret == RET_COPY_AGAIN); usleep(priv->decode_wait); return len; }
1threat
Inline variable declaration doesn't compile when using '== false' instead of negation operator : <p>Consider the following snippets:</p> <pre><code>void Foo(object sender, EventArgs e) { if (!(sender is ComboBox comboBox)) return; comboBox.DropDownWidth = 100; } </code></pre> <p>compared to</p> <pre><code>void Bar(object sender, EventArgs e) { if ((sender is ComboBox comboBox) == false) return; comboBox.DropDownWidth = 100; } </code></pre> <p>Code including <code>Foo()</code> successfully compiles in .Net 4.6.1, while code including <code>Bar()</code> results in <code>Use of unassigned local variable 'comboBox'</code>. </p> <p>Without getting into a debate over the reasons behind using <code>== false</code> instead of the negation operator, can someone explain why one compiles and the other does not?</p>
0debug
uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len) { VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev); uint32_t emu_bits = 0, emu_val = 0, phys_val = 0, val; memcpy(&emu_bits, vdev->emulated_config_bits + addr, len); emu_bits = le32_to_cpu(emu_bits); if (emu_bits) { emu_val = pci_default_read_config(pdev, addr, len); } if (~emu_bits & (0xffffffffU >> (32 - len * 8))) { ssize_t ret; ret = pread(vdev->vbasedev.fd, &phys_val, len, vdev->config_offset + addr); if (ret != len) { error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x) failed: %m", __func__, vdev->host.domain, vdev->host.bus, vdev->host.slot, vdev->host.function, addr, len); return -errno; } phys_val = le32_to_cpu(phys_val); } val = (emu_val & emu_bits) | (phys_val & ~emu_bits); trace_vfio_pci_read_config(vdev->vbasedev.name, addr, len, val); return val; }
1threat
int ff_vaapi_commit_slices(FFVAContext *vactx) { VABufferID *slice_buf_ids; VABufferID slice_param_buf_id, slice_data_buf_id; if (vactx->slice_count == 0) return 0; slice_buf_ids = av_fast_realloc(vactx->slice_buf_ids, &vactx->slice_buf_ids_alloc, (vactx->n_slice_buf_ids + 2) * sizeof(slice_buf_ids[0])); if (!slice_buf_ids) return -1; vactx->slice_buf_ids = slice_buf_ids; slice_param_buf_id = 0; if (vaCreateBuffer(vactx->display, vactx->context_id, VASliceParameterBufferType, vactx->slice_param_size, vactx->slice_count, vactx->slice_params, &slice_param_buf_id) != VA_STATUS_SUCCESS) return -1; vactx->slice_count = 0; slice_data_buf_id = 0; if (vaCreateBuffer(vactx->display, vactx->context_id, VASliceDataBufferType, vactx->slice_data_size, 1, (void *)vactx->slice_data, &slice_data_buf_id) != VA_STATUS_SUCCESS) return -1; vactx->slice_data = NULL; vactx->slice_data_size = 0; slice_buf_ids[vactx->n_slice_buf_ids++] = slice_param_buf_id; slice_buf_ids[vactx->n_slice_buf_ids++] = slice_data_buf_id; return 0; }
1threat
can't edit .bashrc while it is already present in the directory : <p>I'm setting up zsh in my Windows subsystem for Linux in my windows 10 machine by following some tutorial which instructs on opening my bash profile by the following command </p> <pre><code>vim~/.bashrc </code></pre> <p>but it says</p> <pre><code>bash: vim~/.bashrc: No such file or directory </code></pre> <p>I've tried using </p> <pre><code>ls -la ~/ | more </code></pre> <p>which shows the file is present, even tried copying it from the /etc/skel but still no luck</p>
0debug
How run the "OSM Map Tile Packager"? : I cloned this [repository](https://github.com/osmdroid/osmdroid). I need run this project "OSM Map Tile Packager". I don't understand how to do that. How run the "OSM Map Tile Packager"? I use IDE Android Studio. That I to do?
0debug
VSTS 2015 Current user-issues in using features of VSTS 2015 : Issues using features of VSTS 2015 where if two users are connected to same VM(work station) concurrently and trying to access Visual studio 2015 (work station Name : DevBOX). could you please explain that if 2 users are accessing same VM concurrently and trying to access Visual studio 2015 at same time with single license how it really works?
0debug
How to wait Func<T>().invoike in C# : I have a method to show loading form with parameter Func<T> and in that method I use func.Invoke(); this.Close(); but in this cast this.Close(); not waiting for func.Invoke to finish. Help me please. :) private void ShowLoading<T>(Func<T> func) { func.Invoke(); this.Close(); }
0debug
Why can my ```first_pay``` not be defined? My ```second_pay``` works fine : The goal here is to calculate a salesperson's total pay for selling two vehicles, each one of any type. When they sell a new vehicle, they make $1,500. When they sell a used vehicle, they make a commission of 5% of the vehicle price. I have to make it prompt the salesperson to enter the type and selling price of each vehicle. Then, it should display the salesperson's total sales and total pay. I am not understanding what could be wrong with ```first_pay``` ```firstType = input('What is the first type of vehicle you are selling? ') firstPrice = int(input('What is the price of the first vehicle? ')) secondType = input('What is second type of vehicle you are selling? ') secondPrice = int(input('What is the price of the second vehicle? ')) if firstType == 'new': first_pay = 1500 elif firstType == 'used': first_pay = firstPrice * .05 if secondType == 'new': second_pay = 1500 elif secondType == 'used': second_pay = secondPrice * .05 totalPay = first_pay + second_pay totalSales = firstPrice + secondPrice print('Total sales: $', format(totalSales, ',.2f'), sep='') print('Total pay: $', format(totalPay, ',.2f'), sep='') ```
0debug
Downgrade kubectl version to match minikube k8s version : <p>I started minikube with k8s version 1.5.2 and I would like to downgrade my kubectl so that it is also 1.5.2. Currently when I run <code>kubectl version</code> I get:</p> <pre><code>Client Version: version.Info{Major:"1", Minor:"7", GitVersion:"v1.7.5", GitCommit:"17d7182a7ccbb167074be7a87f0a68bd00d58d97", GitTreeState:"clean", BuildDate:"2017-08-31T19:32:12Z", GoVersion:"go1.9", Compiler:"gc", Platform:"darwin/amd64"} Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.2", GitCommit:"08e099554f3c31f6e6f07b448ab3ed78d0520507", GitTreeState:"clean", BuildDate:"1970-01-01T00:00:00Z", GoVersion:"go1.7", Compiler:"gc", Platform:"linux/amd64"} </code></pre> <p>I would like to use kubectl to fetch <code>PetSets</code> but in later versions this was updated to <code>StatefulSets</code> so I cannot use the commands with my current kubectl version </p> <pre><code>kubectl get petsets the server doesn't have a resource type "petsets" </code></pre> <p>Thanks!</p>
0debug
static bool acpi_has_nvdimm(void) { PCMachineState *pcms = PC_MACHINE(qdev_get_machine()); return pcms->nvdimm; }
1threat
Keyof nested child objects : <p>I have a recursively typed object that I want to get the keys of and any child keys of a certain type.</p> <p>For instance. Below I want to get a union type of:</p> <pre><code>'/another' | '/parent' | '/child' </code></pre> <p>Example: </p> <pre><code>export interface RouteEntry { readonly name: string, readonly nested : RouteList | null } export interface RouteList { readonly [key : string] : RouteEntry } export const list : RouteList = { '/parent': { name: 'parentTitle', nested: { '/child': { name: 'child', nested: null, }, }, }, '/another': { name: 'anotherTitle', nested: null }, } </code></pre> <p>In typescript you can use keyof typeof RouteList to get the union type:</p> <pre><code>'/another' | '/parent' </code></pre> <p>Is there a method to also include the nested types</p>
0debug
How to change directory and run command on that directory? : <p>Example: I want to change directory to : C:/temp/hacking/passsword and execute a command like that : java Helloworld arg1 arg2 How can I do this with java?</p>
0debug
Can lazy-loaded modules share the same instance of a service provided by their parent? : <p>I've just run into a problem with a lazy-loaded module where parent and child module both require the same service but create an instance each. The declaration is identical for both, that is</p> <pre><code>import { MyService } from './my.service'; ... @NgModule({ ... providers: [ MyService, ... ] }); </code></pre> <p>and here's the routing setup</p> <pre><code>export parentRoutes: Routes = [ { path: ':id', component: ParentComponent, children: [ { path: '', component: ParentDetailsComponent }, { path: 'child', loadChildren: 'app/child.module#ChildModule' }, ... ]} ]; </code></pre> <p>which, of course, is then imported in the parent module as</p> <pre><code>RouterModule.forChild(parentRoutes) </code></pre> <p>How do I go about this if I wanted to share the same service instance?</p>
0debug
Sorting JS Array : I have the following Js array: myArr = [[["One"],["First","Fourth","Third"]], [["Two"],["First","Second","Third"]], [["Three"],["First","Third"]], [["One two"],["Fourth","Second","Third"]], [["One three"],["Fourth","Third"]], [["One two three"],["Second","Third"]]]; I need this sorted so I get: [[["One"],["First","Fourth","Third"]], [["One three"],["Fourth","Third"]], [["One two"],["Fourth","Second","Third"]], [["One two three"],["Second","Third"]], [["Three"],["First","Third"]], [["Two"],["First","Second","Third"]]] I assumed I could just use `myArr.sort()` and get the properly sorted array and it does work when I don't have a nested array buy why isn't this sorting properly. When i use `myArr.sort()` I get: [[["One three"],["Fourth","Third"]], [["One two three"],["Second","Third"]], [["One two"],["Fourth","Second","Third"]], [["One"],["First","Fourth","Third"]], [["Three"],["First","Third"]], [["Two"],["First","Second","Third"]]] This makes zero sense to me. How does JS sort get to that result? And how do I get the result I need.
0debug
Debounce function implemented with promises : <p>I'm trying to implement a debounce function that works with a promise in javascript. That way, each caller can consume the result of the "debounced" function using a Promise. Here is the best I have been able to come up with so far:</p> <pre><code>function debounce(inner, ms = 0) { let timer = null; let promise = null; const events = new EventEmitter(); // do I really need this? return function (...args) { if (timer == null) { promise = new Promise(resolve =&gt; { events.once('done', resolve); }); } else { clearTimeout(timer); } timer = setTimeout(() =&gt; { events.emit('done', inner(...args)); timer = null; }, ms); return promise; }; } </code></pre> <p>Ideally, I would like to implement this utility function <em>without</em> introducing a dependency on EventEmitter (or implementing my own basic version of EventEmitter), but I can't think of a way to do it. Any thoughts?</p>
0debug
static av_cold int flac_encode_init(AVCodecContext *avctx) { int freq = avctx->sample_rate; int channels = avctx->channels; FlacEncodeContext *s = avctx->priv_data; int i, level; uint8_t *streaminfo; s->avctx = avctx; dsputil_init(&s->dsp, avctx); if (avctx->sample_fmt != SAMPLE_FMT_S16) return -1; if (channels < 1 || channels > FLAC_MAX_CHANNELS) return -1; s->channels = channels; if (freq < 1) return -1; for (i = 4; i < 12; i++) { if (freq == ff_flac_sample_rate_table[i]) { s->samplerate = ff_flac_sample_rate_table[i]; s->sr_code[0] = i; s->sr_code[1] = 0; break; } } if (i == 12) { if (freq % 1000 == 0 && freq < 255000) { s->sr_code[0] = 12; s->sr_code[1] = freq / 1000; } else if (freq % 10 == 0 && freq < 655350) { s->sr_code[0] = 14; s->sr_code[1] = freq / 10; } else if (freq < 65535) { s->sr_code[0] = 13; s->sr_code[1] = freq; } else { return -1; } s->samplerate = freq; } if (avctx->compression_level < 0) s->options.compression_level = 5; else s->options.compression_level = avctx->compression_level; av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", s->options.compression_level); level = s->options.compression_level; if (level > 12) { av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n", s->options.compression_level); return -1; } s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level]; s->options.lpc_type = ((int[]){ AV_LPC_TYPE_FIXED, AV_LPC_TYPE_FIXED, AV_LPC_TYPE_FIXED, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON})[level]; s->options.min_prediction_order = ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level]; s->options.max_prediction_order = ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level]; s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG, ORDER_METHOD_SEARCH})[level]; s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level]; s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level]; #if LIBAVCODEC_VERSION_MAJOR < 53 if (avctx->use_lpc == 0) { s->options.lpc_type = AV_LPC_TYPE_FIXED; } else if (avctx->use_lpc == 1) { s->options.lpc_type = AV_LPC_TYPE_LEVINSON; } else if (avctx->use_lpc > 1) { s->options.lpc_type = AV_LPC_TYPE_CHOLESKY; s->options.lpc_passes = avctx->use_lpc - 1; } #endif if (avctx->lpc_type > AV_LPC_TYPE_DEFAULT) { if (avctx->lpc_type > AV_LPC_TYPE_CHOLESKY) { av_log(avctx, AV_LOG_ERROR, "unknown lpc type: %d\n", avctx->lpc_type); return -1; } s->options.lpc_type = avctx->lpc_type; if (s->options.lpc_type == AV_LPC_TYPE_CHOLESKY) { if (avctx->lpc_passes < 0) { s->options.lpc_passes = 2; } else if (avctx->lpc_passes == 0) { av_log(avctx, AV_LOG_ERROR, "invalid number of lpc passes: %d\n", avctx->lpc_passes); return -1; } else { s->options.lpc_passes = avctx->lpc_passes; } } } switch (s->options.lpc_type) { case AV_LPC_TYPE_NONE: av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n"); break; case AV_LPC_TYPE_FIXED: av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n"); break; case AV_LPC_TYPE_LEVINSON: av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n"); break; case AV_LPC_TYPE_CHOLESKY: av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n", s->options.lpc_passes, s->options.lpc_passes==1?"":"es"); break; } if (s->options.lpc_type == AV_LPC_TYPE_NONE) { s->options.min_prediction_order = 0; } else if (avctx->min_prediction_order >= 0) { if (s->options.lpc_type == AV_LPC_TYPE_FIXED) { if (avctx->min_prediction_order > MAX_FIXED_ORDER) { av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n", avctx->min_prediction_order); return -1; } } else if (avctx->min_prediction_order < MIN_LPC_ORDER || avctx->min_prediction_order > MAX_LPC_ORDER) { av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n", avctx->min_prediction_order); return -1; } s->options.min_prediction_order = avctx->min_prediction_order; } if (s->options.lpc_type == AV_LPC_TYPE_NONE) { s->options.max_prediction_order = 0; } else if (avctx->max_prediction_order >= 0) { if (s->options.lpc_type == AV_LPC_TYPE_FIXED) { if (avctx->max_prediction_order > MAX_FIXED_ORDER) { av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n", avctx->max_prediction_order); return -1; } } else if (avctx->max_prediction_order < MIN_LPC_ORDER || avctx->max_prediction_order > MAX_LPC_ORDER) { av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n", avctx->max_prediction_order); return -1; } s->options.max_prediction_order = avctx->max_prediction_order; } if (s->options.max_prediction_order < s->options.min_prediction_order) { av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n", s->options.min_prediction_order, s->options.max_prediction_order); return -1; } av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n", s->options.min_prediction_order, s->options.max_prediction_order); if (avctx->prediction_order_method >= 0) { if (avctx->prediction_order_method > ORDER_METHOD_LOG) { av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n", avctx->prediction_order_method); return -1; } s->options.prediction_order_method = avctx->prediction_order_method; } switch (s->options.prediction_order_method) { case ORDER_METHOD_EST: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate"); break; case ORDER_METHOD_2LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level"); break; case ORDER_METHOD_4LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level"); break; case ORDER_METHOD_8LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level"); break; case ORDER_METHOD_SEARCH: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search"); break; case ORDER_METHOD_LOG: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search"); break; } if (avctx->min_partition_order >= 0) { if (avctx->min_partition_order > MAX_PARTITION_ORDER) { av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n", avctx->min_partition_order); return -1; } s->options.min_partition_order = avctx->min_partition_order; } if (avctx->max_partition_order >= 0) { if (avctx->max_partition_order > MAX_PARTITION_ORDER) { av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n", avctx->max_partition_order); return -1; } s->options.max_partition_order = avctx->max_partition_order; } if (s->options.max_partition_order < s->options.min_partition_order) { av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n", s->options.min_partition_order, s->options.max_partition_order); return -1; } av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n", s->options.min_partition_order, s->options.max_partition_order); if (avctx->frame_size > 0) { if (avctx->frame_size < FLAC_MIN_BLOCKSIZE || avctx->frame_size > FLAC_MAX_BLOCKSIZE) { av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n", avctx->frame_size); return -1; } } else { s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms); } s->max_blocksize = s->avctx->frame_size; av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", s->avctx->frame_size); if (avctx->lpc_coeff_precision > 0) { if (avctx->lpc_coeff_precision > MAX_LPC_PRECISION) { av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n", avctx->lpc_coeff_precision); return -1; } s->options.lpc_coeff_precision = avctx->lpc_coeff_precision; } else { s->options.lpc_coeff_precision = 15; } av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n", s->options.lpc_coeff_precision); s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size, s->channels, 16); s->md5ctx = av_malloc(av_md5_size); if (!s->md5ctx) av_md5_init(s->md5ctx); streaminfo = av_malloc(FLAC_STREAMINFO_SIZE); if (!streaminfo) write_streaminfo(s, streaminfo); avctx->extradata = streaminfo; avctx->extradata_size = FLAC_STREAMINFO_SIZE; s->frame_count = 0; s->min_framesize = s->max_framesize; avctx->coded_frame = avcodec_alloc_frame(); avctx->coded_frame->key_frame = 1; return 0; }
1threat
vreader_get_reader_by_name(const char *name) { VReader *reader = NULL; VReaderListEntry *current_entry = NULL; vreader_list_lock(); for (current_entry = vreader_list_get_first(vreader_list); current_entry; current_entry = vreader_list_get_next(current_entry)) { VReader *creader = vreader_list_get_reader(current_entry); if (strcmp(creader->name, name) == 0) { reader = creader; break; } vreader_free(creader); } vreader_list_unlock(); return reader; }
1threat
Change a field in a Django REST Framework ModelSerializer based on the request type? : <p>Consider this case where I have a <code>Book</code> and <code>Author</code> model. </p> <p>serializers.py</p> <pre><code>class AuthorSerializer(serializers.ModelSerializer): class Meta: model = models.Author fields = ('id', 'name') class BookSerializer(serializers.ModelSerializer): author = AuthorSerializer(read_only=True) class Meta: model = models.Book fields = ('id', 'title', 'author') </code></pre> <p>viewsets.py</p> <pre><code>class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer </code></pre> <p>This works great if I send a <code>GET</code> request for a book. I get an output with a nested serializer containing the book details and the nested author details, which is what I want.</p> <p>However, when I want to create/update a book, I have to send a <code>POST</code>/<code>PUT</code>/<code>PATCH</code> with the nested details of the author instead of just their id. I want to be able to create/update a book object by specifying a author id and not the entire author object. </p> <p>So, something where my serializer looks like this for a <code>GET</code> request</p> <pre><code>class BookSerializer(serializers.ModelSerializer): author = AuthorSerializer(read_only=True) class Meta: model = models.Book fields = ('id', 'title', 'author') </code></pre> <p>and my serializer looks like this for a <code>POST</code>, <code>PUT</code>, <code>PATCH</code> request</p> <pre><code>class BookSerializer(serializers.ModelSerializer): author = PrimaryKeyRelatedField(queryset=Author.objects.all()) class Meta: model = models.Book fields = ('id', 'title', 'author') </code></pre> <p>I also do not want to create two entirely separate serializers for each type of request. I'd like to just modify the <code>author</code> field in the <code>BookSerializer</code>. </p> <p>Lastly, is there a better way of doing this entire thing?</p>
0debug
static void IMLT(float *pInput, float *pOutput, int odd_band) { int i; if (odd_band) { for (i=0; i<128; i++) FFSWAP(float, pInput[i], pInput[255-i]); } ff_imdct_calc(&mdct_ctx,pOutput,pInput); dsp.vector_fmul(pOutput,mdct_window,512); }
1threat
Conversion into proper date format : I've a system generated date and time format. It looks something like this, "2017-04-12-02.29.25.000000" . I want to convert this format into a standard one so that my system can read this and later on I can convert it into minutes. Someone please help to provide a code in R.
0debug
Three.js how add cicle in center of scene : i work with sphere img and use for it Threejs and i need add some small obj like aim in center of sphere, and when i will move scene this obj should be always in center of scene.
0debug
Invalid arguments ' in c++ : when i try to use get functions that I built i get that error . here is an example from my code : class Apartment{ public : class ApartmentException : public std::exception {}; class IllegalArgException : public ApartmentException {}; class OutOfApartmentBoundsException : public ApartmentException {}; enum SquareType {EMPTY, WALL, NUM_SQUARE_TYPES}; Apartment (SquareType** squares, int length, int width, int price);// done Apartment (const Apartment& apartment); // done ~Apartment(); // done Apartment& operator+=(const Apartment& apartment);// done Apartment operator+(const Apartment& apartment1,const Apartment& apartment2);//done Apartment& operator=(const Apartment& apartment); // need check Apartment& operator=(SquareType** squares, int length, int width, int price); SquareType& operator()(int row , int col); // done - need help bool operator<(const Apartment& apartment); // done - need help int getTotalArea(); // done int getPrice(); // done int getLength(); // done int getWidth(); // done private: void legalArgs(SquareType** squares, int length, int width, int price); void createSquares(SquareType** squares,int length,int width); void copySquares(SquareType** squares,int length,int width); void destroySquares(SquareType** squares,int length,int width); void legalCoordinate(int row,int col); int price; int length; int width; SquareType** squares; }; int Apartment::getLength() { return length; } int Apartment::getPrice() { return price; } int Apartment::getWidth() { return width; } int Apartment::getTotalArea() { int count=0; for(int i=0;i<width;i++) { for(int j=0;j<length;j++) { if(squares[i][j]==EMPTY) { count++; } } } return count; } bool Apartment::operator<(const Apartment& apartment) { int thisArea=this->getTotalArea(); int paramArea=apartment.getTotalArea(); // the error line is here !!! double thisRatio=((double)price)/thisArea; double paramRatio=((double)apartment.price)/paramArea; if(thisRatio==paramRatio) { return price < apartment.price; } return thisRatio<paramRatio; } have i done something wrong ? Its the first time i'm using c++ .. by the way - any comments for the rest of the code are fine as well.
0debug
static void dvbsub_parse_object_segment(AVCodecContext *avctx, const uint8_t *buf, int buf_size) { DVBSubContext *ctx = avctx->priv_data; const uint8_t *buf_end = buf + buf_size; const uint8_t *block; int object_id; DVBSubObject *object; DVBSubObjectDisplay *display; int top_field_len, bottom_field_len; int coding_method, non_modifying_color; object_id = AV_RB16(buf); buf += 2; object = get_object(ctx, object_id); if (!object) return; coding_method = ((*buf) >> 2) & 3; non_modifying_color = ((*buf++) >> 1) & 1; if (coding_method == 0) { top_field_len = AV_RB16(buf); buf += 2; bottom_field_len = AV_RB16(buf); buf += 2; if (buf + top_field_len + bottom_field_len > buf_end) { av_log(avctx, AV_LOG_ERROR, "Field data size too large\n"); return; } for (display = object->display_list; display; display = display->object_list_next) { block = buf; dvbsub_parse_pixel_data_block(avctx, display, block, top_field_len, 0, non_modifying_color); if (bottom_field_len > 0) block = buf + top_field_len; else bottom_field_len = top_field_len; dvbsub_parse_pixel_data_block(avctx, display, block, bottom_field_len, 1, non_modifying_color); } } else { av_log(avctx, AV_LOG_ERROR, "Unknown object coding %d\n", coding_method); } }
1threat
static void blend_image_rgb_pm(AVFilterContext *ctx, AVFrame *dst, const AVFrame *src, int x, int y) { blend_image_packed_rgb(ctx, dst, src, 0, x, y, 1); }
1threat
when i scroll down it always load more the same data? : Can anyone help me? i want to load more data when scroll up and down by using Asyntask.i try to use this code but it load only more 10 data when i scroll down besides that, it displays the same data. it doesn't load new data. here my code: <pre> @Nullable @Override public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.home_fragment, container, false); arraylist1 = new ArrayList<>(); adapter = new ListViewAdapter(view.getContext(), R.layout.list_view_adapter, arraylist1); listOfNews = (ListView) view.findViewById(R.id.listView); //progress bar dialog = new ProgressDialog(HotNewsFrag.this.getActivity()); dialog.setMessage("Loading News"); dialog.setCancelable(true); //class to parse data from json new ReadJSON().execute(url); return view; } </pre> Adapter <pre> public class ListViewAdapter extends ArrayAdapter<HotNews> { private final LayoutInflater mInflater; Context context; ArrayList<HotNews> arrayList; ImageView image; TextView doer; TextView date; TextView text; Days day = new Days(); public ListViewAdapter(Context context, int resource, ArrayList<HotNews> arrayList) { super(context, resource,arrayList); mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.arrayList = arrayList; this.context = context; } @Override public int getCount() { if(arrayList==null){ return 0; } return arrayList.size(); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { final HotNews news; View v = convertView; if (v==null) { v = mInflater.inflate(R.layout.list_view_adapter, parent, false); } image = (ImageView) v.findViewById(R.id.imagetitle); title = (TextView) v.findViewById(R.id.txtTitle); doer = (TextView) v.findViewById(R.id.doer); date = (TextView) v.findViewById(R.id.txtdate); text = (TextView) v.findViewById(R.id.text); news = getItem(position); Picasso.with(getContext()).load(url + news.getImage()).error(R.drawable.dap).noFade().into(image); title.setText(news.getTitle()); doer.setText("ព័ត៍មានដោយ៖"+news.getDoer()); date.setText(day.Days(news.getDate())+":"+news.getTime()); text.setText(news.getContent()); //set onItemListener listOfNews.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(getContext(), "Stop Clicking me", Toast.LENGTH_SHORT).show(); Intent detail= new Intent(getContext(),HotNewsDetail.class); detail.putExtra(newsid,String.valueOf(getItem(position).getId())); startActivity(detail); } }); listOfNews.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub int threshold = 1; int count = listOfNews.getCount(); if (scrollState == SCROLL_STATE_IDLE) { if (listOfNews.getLastVisiblePosition() >= count - threshold) { // Execute LoadMoreDataTask AsyncTask new ReadJSON().execute(url+"&"+"skip="+10); } } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // TODO Auto-generated method stub } }); return v; } } </pre>
0debug
Can anyone speed up this code : This code 8 cells from a data entry form and copies those cells to the next empty row on another worksheet that is used as a database. It works perfectly except that it takes 15 seconds to run. I know that I can speed up the code if it didn't copy to another sheet. It that scenario it think that I timed it at <7 seconds. Is there a way to significantly speed up this code without merging the two sheets which, at this point is a logistical nightmare? sub UpdateLogWorksheet1() Application.ScreenUpdating = False Application.EnableEvents = False Dim historyWks As Worksheet Dim inputWks As Worksheet Dim nextRow As Long Dim oCol As Long Dim myRng As Range Dim myCopy As String Dim myclear As String Dim myCell As Range ActiveSheet.Unprotect "sallygary" myCopy = "e4,g26,g16,g12,g18,g20,g22,g24" Set inputWks = Worksheets("Dept 1 Input") Set historyWks = Worksheets("1_Data") With historyWks nextRow = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Row End With With inputWks Set myRng = .Range(myCopy) End With With historyWks With .Cells(nextRow, "A") .Value = Now() .NumberFormat = "mm/dd/yyyy" End With .Cells(nextRow, "B").Value = Application.UserName oCol = 3 For Each myCell In myRng.Cells historyWks.Cells(nextRow, oCol).Value = myCell.Value oCol = oCol + 1 Next myCell End With With inputWks On Error Resume Next End With On Error GoTo 0 ActiveSheet.Protect "sallygary" Range("g12").Select Application.ScreenUpdating = True Application.EnableEvents = True End Sub
0debug
static int xhci_ep_nuke_one_xfer(XHCITransfer *t, TRBCCode report) { int killed = 0; if (report && (t->running_async || t->running_retry)) { t->status = report; xhci_xfer_report(t); } if (t->running_async) { usb_cancel_packet(&t->packet); t->running_async = 0; killed = 1; } if (t->running_retry) { XHCIEPContext *epctx = t->xhci->slots[t->slotid-1].eps[t->epid-1]; if (epctx) { epctx->retry = NULL; timer_del(epctx->kick_timer); } t->running_retry = 0; killed = 1; } g_free(t->trbs); t->trbs = NULL; t->trb_count = t->trb_alloced = 0; return killed; }
1threat
static void sch_handle_start_func_virtual(SubchDev *sch) { PMCW *p = &sch->curr_status.pmcw; SCSW *s = &sch->curr_status.scsw; int path; int ret; bool suspend_allowed; path = 0x80; if (!(s->ctrl & SCSW_ACTL_SUSP)) { ORB *orb = &sch->orb; s->cstat = 0; s->dstat = 0; p->intparm = orb->intparm; if (!(orb->lpm & path)) { s->flags |= SCSW_FLAGS_MASK_CC; s->ctrl &= ~SCSW_CTRL_MASK_STCTL; s->ctrl |= (SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND); return; } sch->ccw_fmt_1 = !!(orb->ctrl0 & ORB_CTRL0_MASK_FMT); s->flags |= (sch->ccw_fmt_1) ? SCSW_FLAGS_MASK_FMT : 0; sch->ccw_no_data_cnt = 0; suspend_allowed = !!(orb->ctrl0 & ORB_CTRL0_MASK_SPND); } else { s->ctrl &= ~(SCSW_ACTL_SUSP | SCSW_ACTL_RESUME_PEND); suspend_allowed = true; } sch->last_cmd_valid = false; do { ret = css_interpret_ccw(sch, sch->channel_prog, suspend_allowed); switch (ret) { case -EAGAIN: break; case 0: s->ctrl &= ~SCSW_ACTL_START_PEND; s->ctrl &= ~SCSW_CTRL_MASK_STCTL; s->ctrl |= SCSW_STCTL_PRIMARY | SCSW_STCTL_SECONDARY | SCSW_STCTL_STATUS_PEND; s->dstat = SCSW_DSTAT_CHANNEL_END | SCSW_DSTAT_DEVICE_END; s->cpa = sch->channel_prog + 8; break; case -EIO: break; case -ENOSYS: s->ctrl &= ~SCSW_ACTL_START_PEND; s->dstat = SCSW_DSTAT_UNIT_CHECK; sch->sense_data[0] = 0x80; s->ctrl &= ~SCSW_CTRL_MASK_STCTL; s->ctrl |= SCSW_STCTL_PRIMARY | SCSW_STCTL_SECONDARY | SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND; s->cpa = sch->channel_prog + 8; break; case -EFAULT: s->ctrl &= ~SCSW_ACTL_START_PEND; s->cstat = SCSW_CSTAT_DATA_CHECK; s->ctrl &= ~SCSW_CTRL_MASK_STCTL; s->ctrl |= SCSW_STCTL_PRIMARY | SCSW_STCTL_SECONDARY | SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND; s->cpa = sch->channel_prog + 8; break; case -EBUSY: s->flags &= ~SCSW_FLAGS_MASK_CC; s->flags |= (1 << 8); s->ctrl &= ~SCSW_CTRL_MASK_STCTL; s->ctrl |= SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND; break; case -EINPROGRESS: s->ctrl &= ~SCSW_ACTL_START_PEND; s->ctrl |= SCSW_ACTL_SUSP; break; default: s->ctrl &= ~SCSW_ACTL_START_PEND; s->cstat = SCSW_CSTAT_PROG_CHECK; s->ctrl &= ~SCSW_CTRL_MASK_STCTL; s->ctrl |= SCSW_STCTL_PRIMARY | SCSW_STCTL_SECONDARY | SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND; s->cpa = sch->channel_prog + 8; break; } } while (ret == -EAGAIN); }
1threat
In Mongo what is the difference between $near and $nearSphere? : <p>I read the docs and its not very clear what the difference is between the two.</p> <p>The only difference I found is that in nearSphere it explicitly says that Mongo calculates distances for $nearSphere using spherical geometry. But this is achievable using $near as well is it not?</p>
0debug
int tcg_gen_code(TCGContext *s, TranslationBlock *tb) { int i, oi, oi_next, num_insns; #ifdef CONFIG_PROFILER { int n; n = s->gen_last_op_idx + 1; s->op_count += n; if (n > s->op_count_max) { s->op_count_max = n; } n = s->nb_temps; s->temp_count += n; if (n > s->temp_count_max) { s->temp_count_max = n; } } #endif #ifdef DEBUG_DISAS if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP) && qemu_log_in_addr_range(tb->pc))) { qemu_log("OP:\n"); tcg_dump_ops(s); qemu_log("\n"); } #endif #ifdef CONFIG_PROFILER s->opt_time -= profile_getclock(); #endif #ifdef USE_TCG_OPTIMIZATIONS tcg_optimize(s); #endif #ifdef CONFIG_PROFILER s->opt_time += profile_getclock(); s->la_time -= profile_getclock(); #endif tcg_liveness_analysis(s); #ifdef CONFIG_PROFILER s->la_time += profile_getclock(); #endif #ifdef DEBUG_DISAS if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP_OPT) && qemu_log_in_addr_range(tb->pc))) { qemu_log("OP after optimization and liveness analysis:\n"); tcg_dump_ops(s); qemu_log("\n"); } #endif tcg_reg_alloc_start(s); s->code_buf = tb->tc_ptr; s->code_ptr = tb->tc_ptr; tcg_out_tb_init(s); num_insns = -1; for (oi = s->gen_first_op_idx; oi >= 0; oi = oi_next) { TCGOp * const op = &s->gen_op_buf[oi]; TCGArg * const args = &s->gen_opparam_buf[op->args]; TCGOpcode opc = op->opc; const TCGOpDef *def = &tcg_op_defs[opc]; uint16_t dead_args = s->op_dead_args[oi]; uint8_t sync_args = s->op_sync_args[oi]; oi_next = op->next; #ifdef CONFIG_PROFILER tcg_table_op_count[opc]++; #endif switch (opc) { case INDEX_op_mov_i32: case INDEX_op_mov_i64: tcg_reg_alloc_mov(s, def, args, dead_args, sync_args); break; case INDEX_op_movi_i32: case INDEX_op_movi_i64: tcg_reg_alloc_movi(s, args, dead_args, sync_args); break; case INDEX_op_insn_start: if (num_insns >= 0) { s->gen_insn_end_off[num_insns] = tcg_current_code_size(s); } num_insns++; for (i = 0; i < TARGET_INSN_START_WORDS; ++i) { target_ulong a; #if TARGET_LONG_BITS > TCG_TARGET_REG_BITS a = ((target_ulong)args[i * 2 + 1] << 32) | args[i * 2]; #else a = args[i]; #endif s->gen_insn_data[num_insns][i] = a; } break; case INDEX_op_discard: temp_dead(s, &s->temps[args[0]]); break; case INDEX_op_set_label: tcg_reg_alloc_bb_end(s, s->reserved_regs); tcg_out_label(s, arg_label(args[0]), s->code_ptr); break; case INDEX_op_call: tcg_reg_alloc_call(s, op->callo, op->calli, args, dead_args, sync_args); break; default: if (def->flags & TCG_OPF_NOT_PRESENT) { tcg_abort(); } tcg_reg_alloc_op(s, def, opc, args, dead_args, sync_args); break; } #ifndef NDEBUG check_regs(s); #endif if (unlikely((void *)s->code_ptr > s->code_gen_highwater)) { return -1; } } tcg_debug_assert(num_insns >= 0); s->gen_insn_end_off[num_insns] = tcg_current_code_size(s); if (!tcg_out_tb_finalize(s)) { return -1; } flush_icache_range((uintptr_t)s->code_buf, (uintptr_t)s->code_ptr); return tcg_current_code_size(s); }
1threat
How do I the site logo depending on the URL the request was made from? : <p>I created a product registration page using ASP.Net MVC. I need to implement the same product registration page for subsidiaries (maybe 3 or 4) with a few minor changes to the way the site looks. For example, the logo will be different and some text at the top of the page. What is the best way to use the same codebase?</p> <p>The best option I could come up with is passing HttpContext.Current.Request.URL to the view and using java script to update it. </p> <p>However, I know routing can be an option too.</p>
0debug
What is a purpose of Zap Functor and zap function in Haskell? : <p>I came across <a href="https://hackage.haskell.org/package/category-extras-0.53.5/docs/Control-Functor-Zap.html">this construction</a> in Haskell. I couldn't find any examples or explanations of how can I use <code>zap</code>/<code>zapWith</code> and <code>bizap</code>/<code>bizapWith</code> in real code. Do they in some way related to standard <code>zip</code>/<code>zipWith</code> functions? How can I use <code>Zap</code>/<code>Bizap</code> functors in Haskell code? What are the benefits of them?</p>
0debug
I want to calculate the average of the last 6 months in MySQL : [calculate the average of the last 6 months in MySQL.][1] [1]: https://i.hizliresim.com/z0ZOq9.png sample code : `select avg(dt.number_of_employees) from (select number_of_employees from my_table order by date desc limit 1,6) dt;` but did not work. How can I calculate with php?
0debug
Configure ngrok's CORS headers : <p>I am running a local webserver, which runs an XHR request to an ngrok server, also run from my PC. </p> <p>I'm getting <code>XMLHttpRequest cannot load http://foo.ngrok.io/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access</code>.</p> <p>It appears the ngrok FAQ mentions CORS headers, but only in relation to basic auth - it doesn't mention how to set the headers so I could test my app in development.</p> <p>How do I change ngrok's CORS options to allow loading requests from localhost?</p>
0debug
How to set checked item in checkedlistbox with string seprated comma - c# : I have problem to select item from string separated comma and check item in checkedlistbox **How can I select item from string separated comma and then check in checkedlistbox?** [preview my program][1] **download My project from this file** [download][2] [1]: https://i.stack.imgur.com/qnTNR.jpg [2]: https://www.dropbox.com/s/ygzr7axlhotg89n/checkItems.zip?dl=0 **How can check in checkedlistbox with textbox and seprated comma**
0debug
Why would I choose a Windows Service over a Web API service? : <p>For me, Windows Services are inconvenient and cumbersome enough to question their validity in all apps that aren't "Watch this folder for a change, react to this change."</p> <p>I understand that this oversimplification is ignorant, why would one choose a windows service over the Web API.</p>
0debug
How to avoid NRE when reading the tag of a button C# : <p>(Sobbing out of frustration)</p> <p>How do you avoid annoying NRE in this case? The output of the code is correct, but I wish to get rid of the NRE.</p> <p>Background:</p> <p>There are some buttons on a form, some of which represent seats of a classroom. The other buttons are irrelevant because I only need the seat buttons, and only the seat buttons have tags that has value.</p> <p>So, I loop through all buttons and read their tags, if it is not empty, then keep that button in a list. The rest are ignored.</p> <p>However, when the code is run, NRE pops up at the fourth line, the line starting with "try".</p> <pre><code>foreach (Button seatbutton in this.Controls) { string betta; try { betta = seatbutton.Tag.ToString(); } catch { betta = ""; } if (!string.IsNullOrEmpty(betta)) { seatbuttons.Add(seatbutton); } } </code></pre> <p>This is the shortest, most straightforward example of this type of NRE in my code. There are several more.</p> <p>I have searched the web, and most responses are among the lines of: "Bad coding habits caused this."</p> <p>As you can probably tell, I'm quite new at this whole thing and haven't even had the time to build habits yet. Can you guys help? Perhaps with some tips for GOOD coding habits?</p> <p>T_T thanks!</p>
0debug
import math def volume_sphere(r): volume=(4/3)*math.pi*r*r*r return volume
0debug
static void event_loop(VideoState *cur_stream) { SDL_Event event; double incr, pos, frac; for (;;) { double x; refresh_loop_wait_event(cur_stream, &event); switch (event.type) { case SDL_KEYDOWN: if (exit_on_keydown) { do_exit(cur_stream); break; } switch (event.key.keysym.sym) { case SDLK_ESCAPE: case SDLK_q: do_exit(cur_stream); break; case SDLK_f: toggle_full_screen(cur_stream); cur_stream->force_refresh = 1; break; case SDLK_p: case SDLK_SPACE: toggle_pause(cur_stream); break; case SDLK_s: step_to_next_frame(cur_stream); break; case SDLK_a: stream_cycle_channel(cur_stream, AVMEDIA_TYPE_AUDIO); break; case SDLK_v: stream_cycle_channel(cur_stream, AVMEDIA_TYPE_VIDEO); break; case SDLK_t: stream_cycle_channel(cur_stream, AVMEDIA_TYPE_SUBTITLE); break; case SDLK_w: toggle_audio_display(cur_stream); break; case SDLK_PAGEUP: incr = 600.0; goto do_seek; case SDLK_PAGEDOWN: incr = -600.0; goto do_seek; case SDLK_LEFT: incr = -10.0; goto do_seek; case SDLK_RIGHT: incr = 10.0; goto do_seek; case SDLK_UP: incr = 60.0; goto do_seek; case SDLK_DOWN: incr = -60.0; do_seek: if (seek_by_bytes) { if (cur_stream->video_stream >= 0 && cur_stream->video_current_pos >= 0) { pos = cur_stream->video_current_pos; } else if (cur_stream->audio_stream >= 0 && cur_stream->audio_pkt.pos >= 0) { pos = cur_stream->audio_pkt.pos; } else pos = avio_tell(cur_stream->ic->pb); if (cur_stream->ic->bit_rate) incr *= cur_stream->ic->bit_rate / 8.0; else incr *= 180000.0; pos += incr; stream_seek(cur_stream, pos, incr, 1); } else { pos = get_master_clock(cur_stream); if (isnan(pos)) pos = (double)cur_stream->seek_pos / AV_TIME_BASE; pos += incr; if (cur_stream->ic->start_time != AV_NOPTS_VALUE && pos < cur_stream->ic->start_time / (double)AV_TIME_BASE) pos = cur_stream->ic->start_time / (double)AV_TIME_BASE; stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE), (int64_t)(incr * AV_TIME_BASE), 0); } break; default: break; } break; case SDL_VIDEOEXPOSE: cur_stream->force_refresh = 1; break; case SDL_MOUSEBUTTONDOWN: if (exit_on_mousedown) { do_exit(cur_stream); break; } case SDL_MOUSEMOTION: if (cursor_hidden) { SDL_ShowCursor(1); cursor_hidden = 0; } cursor_last_shown = av_gettime(); if (event.type == SDL_MOUSEBUTTONDOWN) { x = event.button.x; } else { if (event.motion.state != SDL_PRESSED) break; x = event.motion.x; } if (seek_by_bytes || cur_stream->ic->duration <= 0) { uint64_t size = avio_size(cur_stream->ic->pb); stream_seek(cur_stream, size*x/cur_stream->width, 0, 1); } else { int64_t ts; int ns, hh, mm, ss; int tns, thh, tmm, tss; tns = cur_stream->ic->duration / 1000000LL; thh = tns / 3600; tmm = (tns % 3600) / 60; tss = (tns % 60); frac = x / cur_stream->width; ns = frac * tns; hh = ns / 3600; mm = (ns % 3600) / 60; ss = (ns % 60); fprintf(stderr, "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d) \n", frac*100, hh, mm, ss, thh, tmm, tss); ts = frac * cur_stream->ic->duration; if (cur_stream->ic->start_time != AV_NOPTS_VALUE) ts += cur_stream->ic->start_time; stream_seek(cur_stream, ts, 0, 0); } break; case SDL_VIDEORESIZE: screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0, SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL); screen_width = cur_stream->width = event.resize.w; screen_height = cur_stream->height = event.resize.h; cur_stream->force_refresh = 1; break; case SDL_QUIT: case FF_QUIT_EVENT: do_exit(cur_stream); break; case FF_ALLOC_EVENT: alloc_picture(event.user.data1); break; default: break; } } }
1threat
static int packed_vscale(SwsContext *c, SwsFilterDescriptor *desc, int sliceY, int sliceH) { VScalerContext *inst = desc->instance; int dstW = desc->dst->width; int chrSliceY = sliceY >> desc->dst->v_chr_sub_sample; int lum_fsize = inst[0].filter_size; int chr_fsize = inst[1].filter_size; uint16_t *lum_filter = inst[0].filter[0]; uint16_t *chr_filter = inst[1].filter[0]; int firstLum = FFMAX(1-lum_fsize, inst[0].filter_pos[chrSliceY]); int firstChr = FFMAX(1-chr_fsize, inst[1].filter_pos[chrSliceY]); int sp0 = firstLum - desc->src->plane[0].sliceY; int sp1 = firstChr - desc->src->plane[1].sliceY; int sp2 = firstChr - desc->src->plane[2].sliceY; int sp3 = firstLum - desc->src->plane[3].sliceY; int dp = sliceY - desc->dst->plane[0].sliceY; uint8_t **src0 = desc->src->plane[0].line + sp0; uint8_t **src1 = desc->src->plane[1].line + sp1; uint8_t **src2 = desc->src->plane[2].line + sp2; uint8_t **src3 = desc->alpha ? desc->src->plane[3].line + sp3 : NULL; uint8_t **dst = desc->dst->plane[0].line + dp; if (c->yuv2packed1 && lum_fsize == 1 && chr_fsize <= 2) { int chrAlpha = chr_fsize == 1 ? 0 : chr_filter[2 * sliceY + 1]; ((yuv2packed1_fn)inst->pfn)(c, (const int16_t*)*src0, (const int16_t**)src1, (const int16_t**)src2, (const int16_t*)(desc->alpha ? *src3 : NULL), *dst, dstW, chrAlpha, sliceY); } else if (c->yuv2packed2 && lum_fsize == 2 && chr_fsize == 2) { int lumAlpha = lum_filter[2 * sliceY + 1]; int chrAlpha = chr_filter[2 * sliceY + 1]; c->lumMmxFilter[2] = c->lumMmxFilter[3] = lum_filter[2 * sliceY] * 0x10001; c->chrMmxFilter[2] = c->chrMmxFilter[3] = chr_filter[2 * chrSliceY] * 0x10001; ((yuv2packed2_fn)inst->pfn)(c, (const int16_t**)src0, (const int16_t**)src1, (const int16_t**)src2, (const int16_t**)src3, *dst, dstW, lumAlpha, chrAlpha, sliceY); } else { ((yuv2packedX_fn)inst->pfn)(c, lum_filter + sliceY * lum_fsize, (const int16_t**)src0, lum_fsize, chr_filter + sliceY * chr_fsize, (const int16_t**)src1, (const int16_t**)src2, chr_fsize, (const int16_t**)src3, *dst, dstW, sliceY); } return 1; }
1threat
Arrow function confusion : <p>I was doing a question on codesignal and when I couldn't get the answer myself for all tests, revealed the answers and saw this one; while I understand what it's trying to do (make sure positions are not divisible by n, and if it is increment n by one) I'm having trouble understanding the arrow function syntax and, rewriting it myself from their code.</p> <pre><code>function obst(inputArray) { for (var n=1;;n+=1) if(inputArray.every(x=&gt;x%n)) return n;} </code></pre>
0debug
Tax calculation using javascript : <p>I develop E-commerce app.</p> <p>I display the List of product using this array.</p> <p>Here is my cartProduct array.</p> <pre><code> Cartproduct=[ { "P_ID": 1, "P_TITLE": "Martina", "PRICE_REGULAR": 194, "PRICE_SALE": 161, "P_TAX": [ { "NAME": "CGST", "PERCENTAGE": 9 }, { "NAME": "SGST", "PERCENTAGE": 9 }, { "NAME": "IGST", "PERCENTAGE": 18 } ], }, { "P_ID": 2, "P_TITLE": "Kristen", "P_TYPE": "simple", "PRICE_REGULAR": 130, "PRICE_SALE": 174, "P_TAX": [ { "NAME": "CGST", "PERCENTAGE": 5 }, { "NAME": "SGST", "PERCENTAGE": 5 }, { "NAME": "IGST", "PERCENTAGE": 10 } ], }] </code></pre> <p>I need to calculate Tax amount in this cartProduct array.</p> <p>Kindly advice me,</p> <p>Thanks.</p>
0debug
static void i440fx_pcihost_get_pci_hole_end(Object *obj, Visitor *v, const char *name, void *opaque, Error **errp) { I440FXState *s = I440FX_PCI_HOST_BRIDGE(obj); uint32_t value = s->pci_hole.end; visit_type_uint32(v, name, &value, errp); }
1threat
Chart.js Show labels on Pie chart : <p>I recently updated my charts.js library to the most updated version (2.5.0). This version doesn't show the labels on the chart.</p> <p>I have an example of working one on fiddler: <a href="http://jsfiddle.net/g6fajwg8" rel="noreferrer">http://jsfiddle.net/g6fajwg8</a> .</p> <p>However, I defined my chart exactly as in the example but still can not see the labels on the chart.</p> <p>Note: There are a lot of questions like this on Google and Stackoverflow but most of them are about previous versions which is working well on them.</p> <pre><code>var config = { type: 'pie', data: { datasets: [{ data: [ 1200, 1112, 533, 202, 105, ], backgroundColor: [ "#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360", ], label: 'Dataset 1' }], labels: [ "Red", "Green", "Yellow", "Grey", "Dark Grey" ] }, options: { responsive: true, legend: { position: 'top', }, title: { display: true, text: 'Chart.js Doughnut Chart' }, animation: { animateScale: true, animateRotate: true } } }; window.pPercentage = new Chart(ChartContext, config); </code></pre> <p><a href="https://i.stack.imgur.com/uyehv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uyehv.png" alt="enter image description here"></a></p>
0debug
static int mpeg_decode_frame(AVCodecContext *avctx, void *data, int *data_size, const uint8_t *buf, int buf_size) { Mpeg1Context *s = avctx->priv_data; AVFrame *picture = data; MpegEncContext *s2 = &s->mpeg_enc_ctx; dprintf(avctx, "fill_buffer\n"); if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == SEQ_END_CODE)) { if (s2->low_delay==0 && s2->next_picture_ptr) { *picture= *(AVFrame*)s2->next_picture_ptr; s2->next_picture_ptr= NULL; *data_size = sizeof(AVFrame); } return buf_size; } if(s2->flags&CODEC_FLAG_TRUNCATED){ int next= ff_mpeg1_find_frame_end(&s2->parse_context, buf, buf_size); if( ff_combine_frame(&s2->parse_context, next, (const uint8_t **)&buf, &buf_size) < 0 ) return buf_size; } #if 0 if (s->repeat_field % 2 == 1) { s->repeat_field++; if (avctx->flags & CODEC_FLAG_REPEAT_FIELD) { *data_size = sizeof(AVPicture); goto the_end; } } #endif if(s->mpeg_enc_ctx_allocated==0 && avctx->codec_tag == AV_RL32("VCR2")) vcr2_init_sequence(avctx); s->slice_count= 0; if(avctx->extradata && !avctx->frame_number) decode_chunks(avctx, picture, data_size, avctx->extradata, avctx->extradata_size); return decode_chunks(avctx, picture, data_size, buf, buf_size); }
1threat
Unity C#: Help editing script to use Right Mouse Button instead of OnMouseDrag : I am having trouble figuring out how to adjust this script to use the Middle Mouse Button instead of Left. The script currently uses OnMouseDown, OnMouseUp, and OnMouseDrag. I need those to be middle mouse instead. (mouse button 3) I appreciate any help, as I am new to coding. Everything I have tried so far has broken the script in one way or another. Thank you very much for your time. using UnityEngine; using System.Collections; public class FPH_DoorObject_Drag : MonoBehaviour { /* * This script is for doors which can be opened dragging on the screen */ public float factor = 2.0f; // How fast will be the movement public float minRot = 0.0f; public float maxRot = 90.0f; public string[] observeKind = new string[] {"Normal", "Closeup"}; public int observeInt = 0; // this variable is used inside of the Editor script public float secToOserve = 1.3f; // After this amount of seconds the text will reset public GameObject inGameCamera; public GameObject closeupCamera; public bool removeItemWhenUsed; public string hasBeenUnlockedKey; public bool canBeObserved; public AudioClip lockedSound; public string observMessage_English; public string observMessage_Italian; public string observMessage_Spanish; public string observMessage_German; public string observMessage_French; public string observMessage_Japanese; public string observMessage_Chinese; public string observMessage_Russian; public string lockedMessage_English; public string lockedMessage_Italian; public string lockedMessage_Spanish; public string lockedMessage_German; public string lockedMessage_French; public string lockedMessage_Japanese; public string lockedMessage_Chinese; public string lockedMessage_Russian; public string wrongItemMessage_English; public string wrongItemMessage_Italian; public string wrongItemMessage_Spanish; public string wrongItemMessage_German; public string wrongItemMessage_French; public string wrongItemMessage_Japanese; public string wrongItemMessage_Chinese; public string wrongItemMessage_Russian; public int doorType = 0; /* * A dor can be: * " Normally Open " - The door is always open * " Locked " - The door is always locked and CAN'T be opened * " Need Equipped Object " - The door is locked but can be opened if the player equip an object * " Need Activated Key " - The door is locked but can be opened if a PlayerPres key is " 1 " which means true */ public string[] doorTypeArray = new string[] {"Normally Open", "Locked", "Need Equipped Object", "Need Activated Key"}; public string neededObject_Name; public string neededKey; private Vector3 startRot; private float startPlayerRot; private float currRot; private float playerRot; private float delta = 0; private Transform playerTransform; private bool canbeOpen; public float openDirection; private bool hasBeenUnlocked; void Start(){ openDirection = -1.0f; playerTransform = GameObject.FindWithTag("Player").transform; startRot = this.gameObject.GetComponent<Transform>().eulerAngles; delta = 0; hasBeenUnlocked = FPH_ControlManager.LoadBool(hasBeenUnlockedKey); if(hasBeenUnlocked){ doorType = 0; } } void Update(){ if(doorType == 0){ canbeOpen = true; } if(doorType == 1){ canbeOpen = false; } if(doorType == 2){ if(FPH_InventoryManager.equippedItem != neededObject_Name && FPH_InventoryManager.equippedItem != "" && FPH_InventoryManager.equippedItem != " "){ canbeOpen = false; } if(FPH_InventoryManager.equippedItem == "" || FPH_InventoryManager.equippedItem == " "){ canbeOpen = false; } if(FPH_InventoryManager.equippedItem == neededObject_Name){ canbeOpen = true; } } if(doorType == 3){ bool boolValue = FPH_ControlManager.LoadBool(neededKey); if(boolValue){ canbeOpen = true; } else{ canbeOpen = false; } } } public void OnMouseDown(){ if(canbeOpen){ startPlayerRot = playerTransform.eulerAngles.y; } } public void OnMouseUp(){ if(doorType == 1){ StartCoroutine("PrivateLocked"); } if(doorType == 2){ if(FPH_InventoryManager.equippedItem != neededObject_Name && FPH_InventoryManager.equippedItem != "" && FPH_InventoryManager.equippedItem != " "){ StartCoroutine("PrivateWrongItem"); } if(FPH_InventoryManager.equippedItem == "" || FPH_InventoryManager.equippedItem == " "){ StartCoroutine("PrivateLocked"); } } if(doorType == 3 && !canbeOpen){ StartCoroutine("PrivateLocked"); } if(canbeOpen){ startRot.y = currRot; delta = 0; if(FPH_InventoryManager.equippedItem == neededObject_Name && !hasBeenUnlocked){ hasBeenUnlocked = true; FPH_ControlManager.SaveBool(hasBeenUnlockedKey, hasBeenUnlocked); doorType = 0; //Afte we used the item we unequip it FPH_InventoryManager.equippedItem = ""; FPH_InventoryManager.equippedItem_Index = -1; if(removeItemWhenUsed){ FPH_InventoryManager.RemoveInventoryItem(FPH_InventoryManager.equippedItem_Index); FPH_InventoryManager.SaveInventory(); } } } } void OnMouseDrag(){ if(canbeOpen){ playerRot = playerTransform.eulerAngles.y; delta = (playerRot - startPlayerRot) * openDirection; // openDirection si important or player rotation will be the inverse of door rot currRot = (startRot.y + (delta * factor)); currRot = Mathf.Clamp(currRot, minRot, maxRot); // door rotation can't be bigger or smaller than min and max rot transform.eulerAngles = new Vector3(startRot.x, currRot, startRot.z); if(FPH_InventoryManager.equippedItem == neededObject_Name && !hasBeenUnlocked){ hasBeenUnlocked = true; FPH_ControlManager.SaveBool(hasBeenUnlockedKey, hasBeenUnlocked); doorType = 0; //Afte we used the item we unequip it FPH_InventoryManager.equippedItem = ""; FPH_InventoryManager.equippedItem_Index = -1; if(removeItemWhenUsed){ FPH_InventoryManager.RemoveInventoryItem(FPH_InventoryManager.equippedItem_Index); FPH_InventoryManager.SaveInventory(); } } } } public void Observe(){ if(observeInt == 0){ StartCoroutine("PrivateObserve_Normal"); } if(observeInt == 1){ StartCoroutine("PrivateObserve_Closeup"); } } IEnumerator PrivateLocked(){ FPH_LanguageManager.static_observeTextMesh.text = ""; if(lockedSound){ GetComponent<AudioSource>().PlayOneShot(lockedSound); } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.English){ FPH_LanguageManager.static_observeTextMesh.text = lockedMessage_English; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Italian){ FPH_LanguageManager.static_observeTextMesh.text = lockedMessage_Italian; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Spanish){ FPH_LanguageManager.static_observeTextMesh.text = lockedMessage_Spanish; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.German){ FPH_LanguageManager.static_observeTextMesh.text = lockedMessage_German; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.French){ FPH_LanguageManager.static_observeTextMesh.text = lockedMessage_French; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Japanese){ FPH_LanguageManager.static_observeTextMesh.text = lockedMessage_Japanese; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Chinese){ FPH_LanguageManager.static_observeTextMesh.text = lockedMessage_Chinese; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Russian){ FPH_LanguageManager.static_observeTextMesh.text = lockedMessage_Russian; } yield return new WaitForSeconds(secToOserve); FPH_LanguageManager.static_observeTextMesh.text = ""; } IEnumerator PrivateWrongItem(){ FPH_LanguageManager.static_observeTextMesh.text = ""; if(lockedSound){ GetComponent<AudioSource>().PlayOneShot(lockedSound); } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.English){ FPH_LanguageManager.static_observeTextMesh.text = wrongItemMessage_English; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Italian){ FPH_LanguageManager.static_observeTextMesh.text = wrongItemMessage_Italian; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Spanish){ FPH_LanguageManager.static_observeTextMesh.text = wrongItemMessage_Spanish; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.German){ FPH_LanguageManager.static_observeTextMesh.text = wrongItemMessage_German; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.French){ FPH_LanguageManager.static_observeTextMesh.text = wrongItemMessage_French; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Japanese){ FPH_LanguageManager.static_observeTextMesh.text = wrongItemMessage_Japanese; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Chinese){ FPH_LanguageManager.static_observeTextMesh.text = wrongItemMessage_Chinese; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Russian){ FPH_LanguageManager.static_observeTextMesh.text = wrongItemMessage_Russian; } yield return new WaitForSeconds(secToOserve); FPH_LanguageManager.static_observeTextMesh.text = ""; } IEnumerator PrivateObserve_Normal(){ if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.English){ // If language is .... FPH_LanguageManager.static_observeTextMesh.text = observMessage_English; // Set this thext } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Italian){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_Italian; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Spanish){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_Spanish; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.German){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_German; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.French){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_French; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Japanese){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_Japanese; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Chinese){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_Chinese; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Russian){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_Russian; } yield return new WaitForSeconds(secToOserve); // After " secToOserve " ... FPH_LanguageManager.static_observeTextMesh.text = ""; // Reset the text } /* * We toggle the cameras and show a text, everything will be reset * after " secToOserve " */ IEnumerator PrivateObserve_Closeup(){ inGameCamera.SetActive(false); closeupCamera.SetActive(true); FPH_ControlManager.canBeControlled = false; yield return new WaitForSeconds(0.1f); if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.English){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_English; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Italian){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_Italian; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Spanish){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_Spanish; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.German){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_German; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.French){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_French; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Japanese){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_Japanese; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Chinese){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_Chinese; } if(FPH_LanguageManager.gameLanguage == FPH_LanguageManager.LanguagesEnum.Russian){ FPH_LanguageManager.static_observeTextMesh.text = observMessage_Russian; } yield return new WaitForSeconds(secToOserve); FPH_LanguageManager.static_observeTextMesh.text = ""; yield return new WaitForSeconds(0.3f); inGameCamera.SetActive(true); closeupCamera.SetActive(false); FPH_ControlManager.canBeControlled = true; } }
0debug
static void acquire_privilege(const char *name, Error **errp) { HANDLE token = NULL; TOKEN_PRIVILEGES priv; Error *local_err = NULL; if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token)) { if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) { error_setg(&local_err, QERR_QGA_COMMAND_FAILED, "no luid for requested privilege"); goto out; } priv.PrivilegeCount = 1; priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) { error_setg(&local_err, QERR_QGA_COMMAND_FAILED, "unable to acquire requested privilege"); goto out; } } else { error_setg(&local_err, QERR_QGA_COMMAND_FAILED, "failed to open privilege token"); } out: if (token) { CloseHandle(token); } if (local_err) { error_propagate(errp, local_err); } }
1threat
Why does (2/3) evaluate to 0 in rails? : <p>I'm building a sort of number balancer, but I am running into a problem where even in my console (2/3) evaluates to 0... which makes no sense. I'm fairly sure I'm working with floats, or integers, but why would it fail in the console? Anyways, any help is appreciated, I'm just trying write something to help me get the percentage of the total. (I.E. 2 of 3 is 66.6666%)</p>
0debug
REGEX - How can I return text between two strings : <p>Link <a href="https://regex101.com/r/7j7eWy/1" rel="nofollow noreferrer">Regex101</a> I am using (FD.*?)FD however I am missing every second expression - see regex. Any ideas?</p>
0debug
static void start_output(DBDMA_channel *ch, int key, uint32_t addr, uint16_t req_count, int is_last) { DBDMA_DPRINTF("start_output\n"); DBDMA_DPRINTF("addr 0x%x key 0x%x\n", addr, key); if (!addr || key > KEY_STREAM3) { kill_channel(ch); return; } ch->io.addr = addr; ch->io.len = req_count; ch->io.is_last = is_last; ch->io.dma_end = dbdma_end; ch->io.is_dma_out = 1; ch->processing = 1; ch->rw(&ch->io); }
1threat
Hi everyone,i'm tryng to retreive the serial number of a hard drive or a battery tag : h[here is what i get when i compile it ][1] `#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <string.h> #include <process.h> #include <WinIoCtl.h> #include <Winbase.h> typedef struct _MEDIA_SERIAL_NUMBER_DATA { ULONG SerialNumberLength; ULONG Result; ULONG Retreived; DWORD SerialNumberData[]; }MEDIA_SERIAL_NUMBER_DATA, *PMEDIA_SERIAL_NUMBER_DATA; // the structure of IOCTL_MEDIA_SERIAL_NUMBER_DATA int main() { HANDLE hard; bool result; MEDIA_SERIAL_NUMBER_DATA val; char buf[sizeof(MEDIA_SERIAL_NUMBER_DATA)]; MEDIA_SERIAL_NUMBER_DATA * p = (MEDIA_SERIAL_NUMBER_DATA *) buf; hard = CreateFile(L"\\\\.\\C:", 0, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); result = DeviceIoControl(hard, IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER, NULL, 0, buf, sizeof buf, 0, NULL); if (hard == INVALID_HANDLE_VALUE) printf("Terminal error : invalid handle value \n"); printf("valeur Handle : %c \n", hard); printf("valeur retour : %d \n", result); printf("valeur serial : %d \n", p->SerialNumberData); printf("valeur longeur num serie : %d \n", p->SerialNumberLength); CloseHandle(hard); // free the Handle system("pause"); return 0; }` 1. List item [1]: https://i.stack.imgur.com/GvnJz.png
0debug
@SpringBootTest vs @ContextConfiguration vs @Import in Spring Boot Unit Test : <p>I'm working on a Spring Boot project. I'm writing a "Unit Test" code based on "TDD," which is a little bit difficult. </p> <p>@SpringBootTest loaded all BEANs, which led to longer test times. </p> <p>So I used the @SpringBootTest's class designation.</p> <p>I completed the test normally, but I am not sure the difference between using @ContextConfiguration and using @Import.</p> <p>All three options run normally. I want to know which choice is the best.</p> <pre class="lang-java prettyprint-override"><code>@Service public class CoffeeService { private final CoffeeRepository coffeeRepository; public CoffeeService(CoffeeRepository coffeeRepository) { this.coffeeRepository = coffeeRepository; } public String getCoffee(String name){ return coffeeRepository.findByName(name); } } public interface CoffeeRepository { String findByName(String name); } @Repository public class SimpleCoffeeRepository implements CoffeeRepository { @Override public String findByName(String name) { return "mocha"; } } Option 1(SpringBootTest Annotation) - OK @RunWith(SpringRunner.class) @SpringBootTest(classes = {CoffeeService.class, SimpleCoffeeRepository.class}) public class CoffeeServiceTest { @Autowired private CoffeeService coffeeService; @Test public void getCoffeeTest() { String value = coffeeService.getCoffee("mocha"); assertEquals("mocha", value); } } Option 2 (ContextConfiguration Annoation) - OK @RunWith(SpringRunner.class) @ContextConfiguration(classes = {SimpleCoffeeRepository.class, CoffeeService.class}) public class CoffeeServiceTest { @Autowired private CoffeeService coffeeService; @Test public void getCoffeeTest() { String value = coffeeService.getCoffee("mocha"); assertEquals("mocha", value); } } Option 3 (Import Annoation) - OK @RunWith(SpringRunner.class) @Import({SimpleCoffeeRepository.class, CoffeeService.class}) public class CoffeeServiceTest { @Autowired private CoffeeService coffeeService; @Test public void getCoffeeTest() { String value = coffeeService.getCoffee("mocha"); assertEquals("mocha", value); } </code></pre>
0debug
Laravel 5 Migration change length of existed column : <p>It not work, I search so many ways, How can I change length of value in laravel 5</p> <pre><code>public function up() { Schema::table('articles', function (Blueprint $table) { $table-&gt;string('name',50)-&gt;change(); }); } </code></pre> <p>Thank you all for reading!</p>
0debug
What is the method ".getChildren()" used for in Java? : <p>For example if I were to add a line of code such as-</p> <pre><code>hbox.getChildren().add(calculateButton); </code></pre> <p>what significance does .getChildren hold and what happens if it not used in a program?</p>
0debug