problem
stringlengths
26
131k
labels
class label
2 classes
Can't listen my new button with javascript : <p>I'm load a button from script template:</p> <pre><code>&lt;script type="text/html" id="addButton"&gt; &lt;button class="btn btn-default" id="element-empty"&gt; ELEMENT &lt;/button&gt; &lt;/script&gt; </code></pre> <p>this button already loaded to the page by "load" button. now i want to listener this button ("element-empty") from javascript and use jquery</p> <pre><code>$( '#element-empty' ).click(function() { $(this).attr('class','myClass'); }); </code></pre> <p>the problem, button "element-empty" can't detect from javascript. anyone know the solution???</p>
0debug
static int bmdma_prepare_buf(IDEDMA *dma, int is_write) { BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma); IDEState *s = bmdma_active_if(bm); PCIDevice *pci_dev = PCI_DEVICE(bm->pci_dev); struct { uint32_t addr; uint32_t size; } prd; int l, len; pci_dma_sglist_init(&s->sg, pci_dev, s->nsector / (BMDMA_PAGE_SIZE / 512) + 1); s->io_buffer_size = 0; for(;;) { if (bm->cur_prd_len == 0) { if (bm->cur_prd_last || (bm->cur_addr - bm->addr) >= BMDMA_PAGE_SIZE) return s->io_buffer_size != 0; pci_dma_read(pci_dev, bm->cur_addr, &prd, 8); bm->cur_addr += 8; prd.addr = le32_to_cpu(prd.addr); prd.size = le32_to_cpu(prd.size); len = prd.size & 0xfffe; if (len == 0) len = 0x10000; bm->cur_prd_len = len; bm->cur_prd_addr = prd.addr; bm->cur_prd_last = (prd.size & 0x80000000); } l = bm->cur_prd_len; if (l > 0) { qemu_sglist_add(&s->sg, bm->cur_prd_addr, l); bm->cur_prd_addr += l; bm->cur_prd_len -= l; s->io_buffer_size += l; } } return 1; }
1threat
c# pass method into parameter for logging : <p>I am implementing simple logging, and I would like to do something like below</p> <pre><code>public int SomeMethod(int x) { Log(SomeMethod,"here is a log entry); } </code></pre> <p>In the Log method, I would like to parse out the class name from the method and print to the log file the method name and class name.</p> <p>Is it possible to do something that would look as simple as above or something similar?</p>
0debug
def palindrome_lambda(texts): result = list(filter(lambda x: (x == "".join(reversed(x))), texts)) return result
0debug
How to detect who is move white or black in python-chess library? : <p>I am created some chess program and want to detect who have move white or black. Which objects stores information which pieces will move <strong>Board</strong>, <strong>GameNode</strong>?</p> <pre><code>import chess.pgn import chess.uci # ??? Board().is_white_move()? # ??? GameNode.is_white_move()? </code></pre> <p>I analysed code but not found good explanation.</p>
0debug
static void moxie_cpu_realizefn(DeviceState *dev, Error **errp) { MoxieCPU *cpu = MOXIE_CPU(dev); MoxieCPUClass *mcc = MOXIE_CPU_GET_CLASS(dev); cpu_reset(CPU(cpu)); mcc->parent_realize(dev, errp); }
1threat
Dynamic java object creation : public class Test{ public void setMembersValues(List list){ List<Member> memberList = new ArrayList<Member>(); for(Object o : list){ String[] str = o.split("\n"); if(str.equalsIgnoreCase("<member>")){ /**I want to create separate member objects for each list iterration.But member refers same object.**/ Member member = new Member(); for(int i =0; i<str.length;i++){ if(str[i].equalsIgnoreCase("<member/>")){ memberList.add(member); break; }else{ if(str[i].equalsIgnoreCase("name")) member.setName(str[i].split("//")[1]); }else if(str[i].equalsIgnoreCase("Address")){ member.setAddress(str[i].split("//")[1]); } } } } } } There are two lists here, but only one member object is created. I want to create separate member objects for each iteration and add it to memberList. How can I do it, please?.
0debug
static void adaptive_quantization(MpegEncContext *s, double q){ int i; const float lumi_masking= s->avctx->lumi_masking / (128.0*128.0); const float dark_masking= s->avctx->dark_masking / (128.0*128.0); const float temp_cplx_masking= s->avctx->temporal_cplx_masking; const float spatial_cplx_masking = s->avctx->spatial_cplx_masking; const float p_masking = s->avctx->p_masking; float bits_sum= 0.0; float cplx_sum= 0.0; float cplx_tab[s->mb_num]; float bits_tab[s->mb_num]; const int qmin= 2; const int qmax= 31; Picture * const pic= &s->current_picture; for(i=0; i<s->mb_num; i++){ float temp_cplx= sqrt(pic->mc_mb_var[i]); float spat_cplx= sqrt(pic->mb_var[i]); const int lumi= pic->mb_mean[i]; float bits, cplx, factor; if(spat_cplx < q/3) spat_cplx= q/3; if(temp_cplx < q/3) temp_cplx= q/3; if((s->mb_type[i]&MB_TYPE_INTRA)){ cplx= spat_cplx; factor= 1.0 + p_masking; }else{ cplx= temp_cplx; factor= pow(temp_cplx, - temp_cplx_masking); } factor*=pow(spat_cplx, - spatial_cplx_masking); if(lumi>127) factor*= (1.0 - (lumi-128)*(lumi-128)*lumi_masking); else factor*= (1.0 - (lumi-128)*(lumi-128)*dark_masking); if(factor<0.00001) factor= 0.00001; bits= cplx*factor; cplx_sum+= cplx; bits_sum+= bits; cplx_tab[i]= cplx; bits_tab[i]= bits; } if(s->flags&CODEC_FLAG_NORMALIZE_AQP){ for(i=0; i<s->mb_num; i++){ float newq= q*cplx_tab[i]/bits_tab[i]; newq*= bits_sum/cplx_sum; if (newq > qmax){ bits_sum -= bits_tab[i]; cplx_sum -= cplx_tab[i]*q/qmax; } else if(newq < qmin){ bits_sum -= bits_tab[i]; cplx_sum -= cplx_tab[i]*q/qmin; } } } for(i=0; i<s->mb_num; i++){ float newq= q*cplx_tab[i]/bits_tab[i]; int intq; if(s->flags&CODEC_FLAG_NORMALIZE_AQP){ newq*= bits_sum/cplx_sum; } if(i && ABS(pic->qscale_table[i-1] - newq)<0.75) intq= pic->qscale_table[i-1]; else intq= (int)(newq + 0.5); if (intq > qmax) intq= qmax; else if(intq < qmin) intq= qmin; pic->qscale_table[i]= intq; } }
1threat
Excel VBA Sort bug : I've been writing macros in Excel VBA for the last couple weeks (mostly successfully) for my internship and have come to bug "wall," conveniently right before the deadline for this project I'm working on. Here's the code that I believe has the bug, any feedback is appreciated. Thanks! [screenshot of code][1] [1]: https://i.stack.imgur.com/Tzq1T.png
0debug
I dont understand how to write functions recursively : So I need to call one function recursively in another function. I have some array, and first 2 parameters in function are pointers on beggining of array and behind the end of array. Third parameter is function which I need to call recursively, and 4th parameter is parameter with default value, and I named it a_0; Suppose that array has elements: a_1, a_2, a_3, ... , a_n. My function Result need to calculate this: f(...f(f(f(a_0,a_1),a_2),a_3),...,a_n) This is task for practice, for exam, and I dont understand really principle of recursion(I understand for Factoriel) but I dont understand this example. int Result(int *p, int *q,int (*f)(int, int), int a_0=0) { ...... }
0debug
void mips_r4k_init(MachineState *machine) { ram_addr_t ram_size = machine->ram_size; const char *cpu_model = machine->cpu_model; const char *kernel_filename = machine->kernel_filename; const char *kernel_cmdline = machine->kernel_cmdline; const char *initrd_filename = machine->initrd_filename; char *filename; MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); MemoryRegion *bios; MemoryRegion *iomem = g_new(MemoryRegion, 1); MemoryRegion *isa_io = g_new(MemoryRegion, 1); MemoryRegion *isa_mem = g_new(MemoryRegion, 1); int bios_size; MIPSCPU *cpu; CPUMIPSState *env; ResetData *reset_info; int i; qemu_irq *i8259; ISABus *isa_bus; DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS]; DriveInfo *dinfo; int be; if (cpu_model == NULL) { #ifdef TARGET_MIPS64 cpu_model = "R4000"; #else cpu_model = "24Kf"; #endif } cpu = cpu_mips_init(cpu_model); if (cpu == NULL) { fprintf(stderr, "Unable to find CPU definition\n"); exit(1); } env = &cpu->env; reset_info = g_malloc0(sizeof(ResetData)); reset_info->cpu = cpu; reset_info->vector = env->active_tc.PC; qemu_register_reset(main_cpu_reset, reset_info); if (ram_size > (256 << 20)) { fprintf(stderr, "qemu: Too much memory for this machine: %d MB, maximum 256 MB\n", ((unsigned int)ram_size / (1 << 20))); exit(1); } memory_region_allocate_system_memory(ram, NULL, "mips_r4k.ram", ram_size); memory_region_add_subregion(address_space_mem, 0, ram); memory_region_init_io(iomem, NULL, &mips_qemu_ops, NULL, "mips-qemu", 0x10000); memory_region_add_subregion(address_space_mem, 0x1fbf0000, iomem); if (bios_name == NULL) bios_name = BIOS_FILENAME; filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name); if (filename) { bios_size = get_image_size(filename); } else { bios_size = -1; } #ifdef TARGET_WORDS_BIGENDIAN be = 1; #else be = 0; #endif if ((bios_size > 0) && (bios_size <= BIOS_SIZE)) { bios = g_new(MemoryRegion, 1); memory_region_init_ram(bios, NULL, "mips_r4k.bios", BIOS_SIZE, &error_abort); vmstate_register_ram_global(bios); memory_region_set_readonly(bios, true); memory_region_add_subregion(get_system_memory(), 0x1fc00000, bios); load_image_targphys(filename, 0x1fc00000, BIOS_SIZE); } else if ((dinfo = drive_get(IF_PFLASH, 0, 0)) != NULL) { uint32_t mips_rom = 0x00400000; if (!pflash_cfi01_register(0x1fc00000, NULL, "mips_r4k.bios", mips_rom, blk_by_legacy_dinfo(dinfo), sector_len, mips_rom / sector_len, 4, 0, 0, 0, 0, be)) { fprintf(stderr, "qemu: Error registering flash memory.\n"); } } else if (!qtest_enabled()) { fprintf(stderr, "qemu: Warning, could not load MIPS bios '%s'\n", bios_name); } g_free(filename); if (kernel_filename) { loaderparams.ram_size = ram_size; loaderparams.kernel_filename = kernel_filename; loaderparams.kernel_cmdline = kernel_cmdline; loaderparams.initrd_filename = initrd_filename; reset_info->vector = load_kernel(); } cpu_mips_irq_init_cpu(env); cpu_mips_clock_init(env); memory_region_init_alias(isa_io, NULL, "isa-io", get_system_io(), 0, 0x00010000); memory_region_init(isa_mem, NULL, "isa-mem", 0x01000000); memory_region_add_subregion(get_system_memory(), 0x14000000, isa_io); memory_region_add_subregion(get_system_memory(), 0x10000000, isa_mem); isa_bus = isa_bus_new(NULL, isa_mem, get_system_io()); i8259 = i8259_init(isa_bus, env->irq[2]); isa_bus_irqs(isa_bus, i8259); rtc_init(isa_bus, 2000, NULL); pit = pit_init(isa_bus, 0x40, 0, NULL); serial_hds_isa_init(isa_bus, MAX_SERIAL_PORTS); isa_vga_init(isa_bus); if (nd_table[0].used) isa_ne2000_init(isa_bus, 0x300, 9, &nd_table[0]); ide_drive_get(hd, ARRAY_SIZE(hd)); for(i = 0; i < MAX_IDE_BUS; i++) isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i], ide_irq[i], hd[MAX_IDE_DEVS * i], hd[MAX_IDE_DEVS * i + 1]); isa_create_simple(isa_bus, "i8042"); }
1threat
posting complex data is object returning null when pass to controller in asp.net mvc by ajax : // Ajax Call $.ajax({ type: "POST", url: $rootScope.settings.webApis.RealTimeAIAPIService.url, dataType: "json", contentType: "application/json; charset=utf-8", data: JSON.stringify(realTimeAIConfig), }).done(function (result, response) { if (response == "success") { } }); //Controller Method [HttpPost] [EnableCors("*", "*", "*")] public async Task<IHttpActionResult> Post(RealTimeAIConfig realTimeAIConfig) { if (!ModelState.IsValid) { return BadRequest(ModelState); } try { if (realTimeAIConfig.ID != 1) { _RealTimeAIConfigService.CreateAsync(realTimeAIConfig); } return null; } catch { } return Created(realTimeAIConfig); }
0debug
Address is not incrementing? : <p>It is said that,in c,b++; is equal to b=b+1; if this is the fact test++ in my code why generate a compile time error. test+1 is working well but test++ is not working.but why?</p> <pre><code>#include&lt;stdio.h&gt; int main(void) { char test[80]="This is a test"; int a=13; for(;a&gt;=0;a--) { printf("%c",*(test++); } } </code></pre>
0debug
How to get user's high resolution profile picture on Twitter? : <p>I was reading the Twitter documentation at <a href="https://dev.twitter.com/overview/general/user-profile-images-and-banners" rel="noreferrer">https://dev.twitter.com/overview/general/user-profile-images-and-banners</a> and it clearly states that:</p> <blockquote> <p>Alternative image sizes for user profile images You can obtain a user’s most recent profile image, along with the other components comprising their identity on Twitter, from GET users/show. Within the user object, you’ll find the profile_image_url and profile_image_url_https fields. These fields will contain the resized “normal” variant of the user’s uploaded image. This “normal” variant is typically 48px by 48px.</p> <p>By modifying the URL, you can retrieve other variant sizings such as “bigger”, “mini”, and “original”. Consult the table below for more examples:</p> <p>Variant Dimensions Example URL normal 48px by 48px <a href="http://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png" rel="noreferrer">http://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png</a> <a href="https://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png" rel="noreferrer">https://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png</a> bigger 73px by 73px <a href="http://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_bigger.png" rel="noreferrer">http://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_bigger.png</a> <a href="https://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_bigger.png" rel="noreferrer">https://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_bigger.png</a> mini 24px by 24px <a href="http://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_mini.png" rel="noreferrer">http://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_mini.png</a> <a href="https://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_mini.png" rel="noreferrer">https://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_mini.png</a> original original <a href="http://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3.png" rel="noreferrer">http://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3.png</a> <a href="https://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3.png" rel="noreferrer">https://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3.png</a> Omit the underscore and variant to retrieve the original image. The images can be very large.</p> </blockquote> <p>Twitter API's response is like this for my own account: </p> <pre><code>{ .... "profile_image_url_https" = "https://pbs.twimg.com/profile_images/559415382457348097/qSYxxIAo_normal.png"; ... } </code></pre> <p>That image URL works, but it's too small. I need the highest resolution available. I do exactly what Twitter says, and omit the <code>_normal</code> suffix, and try this URL:</p> <p><a href="https://pbs.twimg.com/profile_images/559415382457348097/qSYxxIAo.png" rel="noreferrer">https://pbs.twimg.com/profile_images/559415382457348097/qSYxxIAo.png</a></p> <p>But it's not found. Is Twitter docs outdated or am I missing a point?</p> <p><strong>UPDATE:</strong> I've tried with a few friends' profiles and most of them seem to work, and removing any suffixes and adding <code>_400x400.[jpg|png]</code> also seems to work, but it's undocumented and unreliable, so I really doubt that I should be using this undocumented API in production.</p> <p><strong>UPDATE 2:</strong> I've refreshed my user object as Twitter also states in case of outdated images, but nothing has changed.</p>
0debug
Dynamic allocated 2d array in c++ : I have in my Class 2 const int variables: const int m_width; const int m_height; In my constructor I have set the variables and I want to create a 2D array with exactly this size that will be passed by value from the player. I am trying to make a TicTacToe game. I need the input of the user to determine the size of the playing field(in this case the width and height of it). How do I dynamically declare a 2D array in my situation? Thank you in advance.
0debug
static inline void copy_backptr(LZOContext *c, int back, int cnt) { register const uint8_t *src = &c->out[-back]; register uint8_t *dst = c->out; if (src < c->out_start || src > dst) { c->error |= AV_LZO_INVALID_BACKPTR; return; } if (cnt > c->out_end - dst) { cnt = FFMAX(c->out_end - dst, 0); c->error |= AV_LZO_OUTPUT_FULL; } av_memcpy_backptr(dst, back, cnt); c->out = dst + cnt; }
1threat
estimate change in R of lineair model : I'm making the statistical analysis of my thesis with a lineair mixed model, using the package nlme. Now I work with several orientations (west, east, north), and R takes the estimate as the alphabetically first value, however I want the estimate to be the lowest value. Does somebody know how to do this? thx
0debug
Execute Statement in Python error Name Not Defined : <p>I am trying to use a Python list comprehension to get the Variable Name SW1 to equal the string "sw1" but I keep getting an error saying sw1 not defined</p> <pre><code> VarList = ["SW1"] VarListEnd = ["sw1"] list3 = [exec("%s="%x + "%s"%y) for x in VarList for y in VarListEnd] list3 </code></pre> <p>How do I amend the exec statement because that is where I think the error is? Really appreciate your help. Thanks in advance.</p>
0debug
APKs to retain in Google Play Developer Console : <p>Today one feature was added by Google Play Developer Console Team for managing the releases. </p> <p>It has three options there for releases :- </p> <blockquote> <p>APKs to add - </p> </blockquote> <p>I understand from this that When you upload new app or update your app then it will roll out on Google Play depends on the staged roll out percentage &amp; it will deactivate previous APK's from production. </p> <blockquote> <p>APKs to deactivate</p> </blockquote> <p>This will list a set of APK's which were deactivated and no longer served on Google Play.</p> <blockquote> <p>APKs to retain</p> </blockquote> <p>I could not understand meaning of this new feature ? Can anybody help me for this ?</p> <p>Thanks in advance.</p>
0debug
How to get row number in dataframe in Pandas? : <p>How can I get the number of the row in a dataframe that contains a certain value in a certain column using Pandas? For example, I have the following dataframe:</p> <pre><code> ClientID LastName 0 34 Johnson 1 67 Smith 2 53 Brows </code></pre> <p>How can I find the number of the row that has 'Smith' in 'LastName' column?</p>
0debug
Create CSV file with data from my model : <p>I have a user model with name and id.</p> <p>I want to store the of all the columns in users to a csv file.</p> <p>How do I use CSV.generate function to do that?</p>
0debug
The `.create()` method does not support writable nested fields by default. : <p>I have a big problem regarding the serialization of a Many to Many relationship with intermediate model in DRF: If the request method is get everything works perfectly. But as soon as i try to POST or PUT Data to the API I get the following Error: </p> <pre><code>Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/views.py", line 477, in dispatch response = self.handle_exception(exc) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/views.py", line 437, in handle_exception self.raise_uncaught_exception(exc) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/views.py", line 474, in dispatch response = handler(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/generics.py", line 243, in post return self.create(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/mixins.py", line 21, in create self.perform_create(serializer) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/mixins.py", line 26, in perform_create serializer.save() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/serializers.py", line 214, in save self.instance = self.create(validated_data) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/serializers.py", line 888, in create raise_errors_on_nested_writes('create', self, validated_data) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/serializers.py", line 780, in raise_errors_on_nested_writes class_name=serializer.__class__.__name__ AssertionError: The `.create()` method does not support writable nested fields by default. Write an explicit `.create()` method for serializer `manager.serializers.EquipmentSerializer`, or set `read_only=True` on nested serializer fields. </code></pre> <p>I am not really sure how to write proper create and update functions and i don´t really understand it, how it is explained in the documentation. </p> <p>Code: </p> <p>views.py: </p> <pre><code>from django.shortcuts import render from django.contrib.auth.models import User, Group from manager.serializers import * from rest_framework import generics from rest_framework import viewsets from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.views import APIView from django.forms.models import model_to_dict class OrderSetDetails(generics.RetrieveUpdateDestroyAPIView): queryset = Order.objects.all() serializer_class = OrderSerializer class OrderSetList(generics.ListCreateAPIView): queryset = Order.objects.all() serializer_class = OrderSerializer class EquipmentSetDetails(generics.RetrieveUpdateDestroyAPIView): queryset = Equipment.objects.all() serializer_class = EquipmentSerializer class EquipmentSetList(generics.ListCreateAPIView): queryset = Equipment.objects.all() serializer_class = EquipmentSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): queryset = Group.objects.all() serializer_class = GroupSerializer class ClientList(generics.ListCreateAPIView): queryset = client.objects.all() serializer_class = ClientSerializer </code></pre> <p>serializers.py </p> <pre><code>from rest_framework import serializers from django.contrib.auth.models import User, Group from storage.models import * class AssignmentSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField(source = 'Order.id') name = serializers.ReadOnlyField(source = 'Order.name') class Meta: model = Assignment fields = ('id', 'name', 'quantity') class EquipmentSerializer(serializers.ModelSerializer): event = AssignmentSerializer(source= 'assignment_set', many = True) class Meta: model = Equipment fields = '__all__' class ClientSerializer(serializers.ModelSerializer): class Meta: model = client fields = '__all__' class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name') class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' </code></pre> <p>models.py: </p> <pre><code>from __future__ import unicode_literals from django.db import models from storage.choices import * # Create your models here. class Equipment(models.Model): name = models.CharField(max_length=30) fabricator = models.CharField(max_length=30, default='-') storeplace = models.IntegerField() labor = models.CharField(max_length=1, choices=labor_choices) event = models.ManyToManyField('Order', blank = True, through= 'Assignment', through_fields=('Equipment', 'Order')) max_quantity = models.IntegerField(default=1, null = True) status = models.CharField(max_length=8, choices = STATUS_CHOICES, default = 'im Lager') def __str__(self): return self.name class client(models.Model): firstname = models.CharField(max_length=30) secondname = models.CharField(max_length=30) email = models.EmailField() post_code = models.IntegerField() city = models.CharField(max_length=30) street= models.CharField(max_length=30) def __str__(self): return "%s %s" % (self.firstname, self.secondname) class Order(models.Model): name = models.CharField(max_length=30) Type = models.CharField( max_length=2, choices=TYPE_CHOICES, default='Rental', ) city = models.CharField(max_length=30) street= models.CharField(max_length=30) date = models.DateField() GuestNumber = models.IntegerField() description = models.TextField() client = models.ForeignKey("client", on_delete=models.CASCADE, blank = True, null = True) status = models.CharField(max_length=30, choices=order_choices, default='glyphicon glyphicon-remove') def __str__(self): return self.name class Assignment(models.Model): Equipment = models.ForeignKey('Equipment', on_delete=models.CASCADE) Order = models.ForeignKey('Order', on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) </code></pre> <p>Thanks in Advance.</p>
0debug
How to understand the following bash script : a.sh: #! /bin/sh arg=("${@/a/b}") arg=("${arg[@]/c/d}") echo $arg echo ${arg[@]} As I run the above a.sh script with different argument, the result is shown in the following: $ ./a.sh a b b $ ./a.sh a w b b w From the result, the script replace the 'a' in argument with 'b'. It is confusing for me the function of slash '/' here. And I can not understand the expression of arg[@].
0debug
How do I create a reminder using Google Calendar API? : <p>In the regular web UI for Google Calendar, when I add an event, I can choose to make it a "reminder", rather than an "event".</p> <p>I'm trying to replicate that with the Python API, but can't seem to find info on how to do that. All the documentation I'm finding pertains to reminders on events (i.e. "remind half an hour before the event"), rather than the "pure" reminders.</p> <p>How does one add just a pure reminder?</p> <p><a href="https://i.stack.imgur.com/GdRi6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GdRi6.png" alt="Pure reminder (not event reminder)"></a></p>
0debug
Retrieve CASE SENSITIVE Windows/DOS command 'whoami' Username : I am using WinAutomation and I am trying to point to and open a file on any computer that my software is placed on without having to hard-code the username in the path, so I am looking for a way to retrieve the logged in Username, that will be case sensitive so I can grab that variable. Using DOS, (which I can run invisible to the user in the background) if the username in the file tree is "User Name", whoami in DOS will return "user name" and then, If I point to a file C:\Users\%pcName%\Desktop\Masterlist.xlsx with that %pcName% not correctly capitalized it will not work... I saw a question about Pythonic way to retrieve case sensitive path but I can't use Python for this. I am open to creative ways to get the case sensitive User Name but I keep seeing people deciding to enforce lowercase usernames as a solution. **Is there a way to find the case-sensitive logged in users name for use in file path references?** *I'm open to being creative at this point!!*
0debug
Create WPF application that plays a browser game : <p>Hi :) I'd like to create a WPF application that can play a browser game on it's own (<a href="https://slowotok.pl/" rel="nofollow noreferrer">https://slowotok.pl/</a>). How can I go about it? I'm very new to all .NET stuff.</p>
0debug
static int vcr2_init_sequence(AVCodecContext *avctx) { Mpeg1Context *s1 = avctx->priv_data; MpegEncContext *s = &s1->mpeg_enc_ctx; int i, v, ret; s->out_format = FMT_MPEG1; if (s1->mpeg_enc_ctx_allocated) { ff_mpv_common_end(s); } s->width = avctx->coded_width; s->height = avctx->coded_height; avctx->has_b_frames = 0; s->low_delay = 1; avctx->pix_fmt = mpeg_get_pixelformat(avctx); #if FF_API_XVMC if ((avctx->pix_fmt == AV_PIX_FMT_XVMC_MPEG2_IDCT || avctx->hwaccel) && avctx->idct_algo == FF_IDCT_AUTO) #else if (avctx->hwaccel && avctx->idct_algo == FF_IDCT_AUTO) #endif avctx->idct_algo = FF_IDCT_SIMPLE; ff_mpv_idct_init(s); if ((ret = ff_mpv_common_init(s)) < 0) return ret; s1->mpeg_enc_ctx_allocated = 1; for (i = 0; i < 64; i++) { int j = s->idsp.idct_permutation[i]; v = ff_mpeg1_default_intra_matrix[i]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; v = ff_mpeg1_default_non_intra_matrix[i]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } s->progressive_sequence = 1; s->progressive_frame = 1; s->picture_structure = PICT_FRAME; s->frame_pred_frame_dct = 1; s->chroma_format = 1; s->codec_id = s->avctx->codec_id = AV_CODEC_ID_MPEG2VIDEO; s1->save_width = s->width; s1->save_height = s->height; s1->save_progressive_seq = s->progressive_sequence; return 0; }
1threat
I want to develop 2d web game. What game engine should I choose? : <p>I want to write in compiled language.</p> <p>Please suggest me some engines those run on web browser.</p> <p>Please don't suggest Unity and Unreal Engine because they require web player and this web player does not support Linux</p>
0debug
Popup in android after i scan : [enter image description here][1] i want to add a popup like this in my app in android after i scan a HR code[enter image description here][2]. [1]: http://i.stack.imgur.com/gQjtJ.jpg [2]: http://i.stack.imgur.com/T7IPC.jpg
0debug
static int decode_pal(MSS12Context *ctx, ArithCoder *acoder) { int i, ncol, r, g, b; uint32_t *pal = ctx->pal + 256 - ctx->free_colours; if (!ctx->free_colours) return 0; ncol = arith_get_number(acoder, ctx->free_colours + 1); for (i = 0; i < ncol; i++) { r = arith_get_bits(acoder, 8); g = arith_get_bits(acoder, 8); b = arith_get_bits(acoder, 8); *pal++ = (0xFF << 24) | (r << 16) | (g << 8) | b; } return !!ncol; }
1threat
how i can find ordim.jar for my java project? : <p>i didn't find ordim.jar for my java project to manipuate Multimedia object " Type ORDSource type and OrdMediaUtil class" using oracle 11g </p>
0debug
void *qemu_ram_mmap(int fd, size_t size, size_t align, bool shared) { size_t total = size + align; #if defined(__powerpc64__) && defined(__linux__) int anonfd = fd == -1 || qemu_fd_getpagesize(fd) == getpagesize() ? -1 : fd; int flags = anonfd == -1 ? MAP_ANONYMOUS : MAP_NORESERVE; void *ptr = mmap(0, total, PROT_NONE, flags | MAP_PRIVATE, anonfd, 0); #else void *ptr = mmap(0, total, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); #endif size_t offset = QEMU_ALIGN_UP((uintptr_t)ptr, align) - (uintptr_t)ptr; void *ptr1; if (ptr == MAP_FAILED) { return MAP_FAILED; } assert(!(align & (align - 1))); assert(align >= getpagesize()); ptr1 = mmap(ptr + offset, size, PROT_READ | PROT_WRITE, MAP_FIXED | (fd == -1 ? MAP_ANONYMOUS : 0) | (shared ? MAP_SHARED : MAP_PRIVATE), fd, 0); if (ptr1 == MAP_FAILED) { munmap(ptr, total); return MAP_FAILED; } ptr += offset; total -= offset; if (offset > 0) { munmap(ptr - offset, offset); } if (total > size + getpagesize()) { munmap(ptr + size + getpagesize(), total - size - getpagesize()); } return ptr; }
1threat
Free dynamic memory with free() : <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; int main() { char **last_names; // last_names has been assigned a char * array of length 4. Each element of the array has // been assigned a char array of length 20. // // All of these memory has been allocated on the heap. // Free all of the allocated memory (hint: 5 total arrays). return 0; } </code></pre> <p>I know the free() method and this is my approach;</p> <pre><code>free(*last_names); free(last_names); </code></pre> <p>but it's not true. Any help will be appreciated</p>
0debug
static void vfio_probe_igd_bar4_quirk(VFIOPCIDevice *vdev, int nr) { struct vfio_region_info *rom = NULL, *opregion = NULL, *host = NULL, *lpc = NULL; VFIOQuirk *quirk; VFIOIGDQuirk *igd; PCIDevice *lpc_bridge; int i, ret, ggms_mb, gms_mb = 0, gen; uint64_t *bdsm_size; uint32_t gmch; uint16_t cmd_orig, cmd; Error *err = NULL; if (!vfio_pci_is(vdev, PCI_VENDOR_ID_INTEL, PCI_ANY_ID) || !vfio_is_vga(vdev) || nr != 4) { return; } gen = igd_gen(vdev); if (gen != 6 && gen != 8) { error_report("IGD device %s is unsupported by IGD quirks, " "try SandyBridge or newer", vdev->vbasedev.name); return; } gmch = vfio_pci_read_config(&vdev->pdev, IGD_GMCH, 4); gmch &= ~((gen < 8 ? 0x1f : 0xff) << (gen < 8 ? 3 : 8)); pci_set_long(vdev->pdev.config + IGD_GMCH, gmch); pci_set_long(vdev->pdev.wmask + IGD_GMCH, 0); pci_set_long(vdev->emulated_config_bits + IGD_GMCH, ~0); if (&vdev->pdev != pci_find_device(pci_device_root_bus(&vdev->pdev), 0, PCI_DEVFN(0x2, 0))) { return; } lpc_bridge = pci_find_device(pci_device_root_bus(&vdev->pdev), 0, PCI_DEVFN(0x1f, 0)); if (lpc_bridge && !object_dynamic_cast(OBJECT(lpc_bridge), "vfio-pci-igd-lpc-bridge")) { error_report("IGD device %s cannot support legacy mode due to existing " "devices at address 1f.0", vdev->vbasedev.name); return; } ret = vfio_get_region_info(&vdev->vbasedev, VFIO_PCI_ROM_REGION_INDEX, &rom); if ((ret || !rom->size) && !vdev->pdev.romfile) { error_report("IGD device %s has no ROM, legacy mode disabled", vdev->vbasedev.name); goto out; } if (vdev->pdev.qdev.hotplugged) { error_report("IGD device %s hotplugged, ROM disabled, " "legacy mode disabled", vdev->vbasedev.name); vdev->rom_read_failed = true; goto out; } ret = vfio_get_dev_region_info(&vdev->vbasedev, VFIO_REGION_TYPE_PCI_VENDOR_TYPE | PCI_VENDOR_ID_INTEL, VFIO_REGION_SUBTYPE_INTEL_IGD_OPREGION, &opregion); if (ret) { error_report("IGD device %s does not support OpRegion access," "legacy mode disabled", vdev->vbasedev.name); goto out; } ret = vfio_get_dev_region_info(&vdev->vbasedev, VFIO_REGION_TYPE_PCI_VENDOR_TYPE | PCI_VENDOR_ID_INTEL, VFIO_REGION_SUBTYPE_INTEL_IGD_HOST_CFG, &host); if (ret) { error_report("IGD device %s does not support host bridge access," "legacy mode disabled", vdev->vbasedev.name); goto out; } ret = vfio_get_dev_region_info(&vdev->vbasedev, VFIO_REGION_TYPE_PCI_VENDOR_TYPE | PCI_VENDOR_ID_INTEL, VFIO_REGION_SUBTYPE_INTEL_IGD_LPC_CFG, &lpc); if (ret) { error_report("IGD device %s does not support LPC bridge access," "legacy mode disabled", vdev->vbasedev.name); goto out; } if (!(gmch & 0x2) && !vdev->vga && vfio_populate_vga(vdev, &err)) { error_reportf_err(err, ERR_PREFIX, vdev->vbasedev.name); error_report("IGD device %s failed to enable VGA access, " "legacy mode disabled", vdev->vbasedev.name); goto out; } ret = vfio_pci_igd_lpc_init(vdev, lpc); if (ret) { error_report("IGD device %s failed to create LPC bridge, " "legacy mode disabled", vdev->vbasedev.name); goto out; } ret = vfio_pci_igd_host_init(vdev, host); if (ret) { error_report("IGD device %s failed to modify host bridge, " "legacy mode disabled", vdev->vbasedev.name); goto out; } ret = vfio_pci_igd_opregion_init(vdev, opregion, &err); if (ret) { error_append_hint(&err, "IGD legacy mode disabled\n"); error_reportf_err(err, ERR_PREFIX, vdev->vbasedev.name); goto out; } quirk = g_malloc0(sizeof(*quirk)); quirk->mem = g_new0(MemoryRegion, 2); quirk->nr_mem = 2; igd = quirk->data = g_malloc0(sizeof(*igd)); igd->vdev = vdev; igd->index = ~0; igd->bdsm = vfio_pci_read_config(&vdev->pdev, IGD_BDSM, 4); igd->bdsm &= ~((1 << 20) - 1); memory_region_init_io(&quirk->mem[0], OBJECT(vdev), &vfio_igd_index_quirk, igd, "vfio-igd-index-quirk", 4); memory_region_add_subregion_overlap(vdev->bars[nr].region.mem, 0, &quirk->mem[0], 1); memory_region_init_io(&quirk->mem[1], OBJECT(vdev), &vfio_igd_data_quirk, igd, "vfio-igd-data-quirk", 4); memory_region_add_subregion_overlap(vdev->bars[nr].region.mem, 4, &quirk->mem[1], 1); QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next); ggms_mb = (gmch >> (gen < 8 ? 8 : 6)) & 0x3; if (gen > 6) { ggms_mb = 1 << ggms_mb; } if (vdev->igd_gms) { if (vdev->igd_gms <= 0x10) { gms_mb = vdev->igd_gms * 32; gmch |= vdev->igd_gms << (gen < 8 ? 3 : 8); pci_set_long(vdev->pdev.config + IGD_GMCH, gmch); } else { error_report("Unsupported IGD GMS value 0x%x", vdev->igd_gms); vdev->igd_gms = 0; } } bdsm_size = g_malloc(sizeof(*bdsm_size)); *bdsm_size = cpu_to_le64((ggms_mb + gms_mb) * 1024 * 1024); fw_cfg_add_file(fw_cfg_find(), "etc/igd-bdsm-size", bdsm_size, sizeof(*bdsm_size)); pci_set_long(vdev->pdev.config + IGD_BDSM, 0); pci_set_long(vdev->pdev.wmask + IGD_BDSM, ~0); pci_set_long(vdev->emulated_config_bits + IGD_BDSM, ~0); if (pread(vdev->vbasedev.fd, &cmd_orig, sizeof(cmd_orig), vdev->config_offset + PCI_COMMAND) != sizeof(cmd_orig)) { error_report("IGD device %s - failed to read PCI command register", vdev->vbasedev.name); } cmd = cmd_orig | PCI_COMMAND_IO; if (pwrite(vdev->vbasedev.fd, &cmd, sizeof(cmd), vdev->config_offset + PCI_COMMAND) != sizeof(cmd)) { error_report("IGD device %s - failed to write PCI command register", vdev->vbasedev.name); } for (i = 1; i < vfio_igd_gtt_max(vdev); i += 4) { vfio_region_write(&vdev->bars[4].region, 0, i, 4); vfio_region_write(&vdev->bars[4].region, 4, 0, 4); } if (pwrite(vdev->vbasedev.fd, &cmd_orig, sizeof(cmd_orig), vdev->config_offset + PCI_COMMAND) != sizeof(cmd_orig)) { error_report("IGD device %s - failed to restore PCI command register", vdev->vbasedev.name); } trace_vfio_pci_igd_bdsm_enabled(vdev->vbasedev.name, ggms_mb + gms_mb); out: g_free(rom); g_free(opregion); g_free(host); g_free(lpc); }
1threat
npm with node-sass and autoprefixer : <p>I use node-sass to compile all my Sass files to a master.css. This works well but now I want to add prefixes. I would like to use only the npm, no Gulp or Grunt.</p> <p>Here my package.json file:</p> <pre><code>{ "name": "xxxxxx.com", "version": "1.0.0", "description": "", "watches": { "sass": "src/scss/**" }, "scripts": { "sass": "node-sass src/scss/master.scss -o dist/css/ --style compressed", "prefix": "postcss --use autoprefixer dist/css/master.css -d dist/css/master.css", "dev": "rerun-script" }, "author": "Jan", "license": "ISC", "devDependencies": { "autoprefixer": "^6.3.1", "browserify": "^13.0.0", "clean-css": "^3.4.9", "node-sass": "^3.4.2", "postcss-cli": "^2.5.0", "rerun-script": "^0.6.0", "uglifyjs": "^2.4.10" } } </code></pre> <p>I do not get it to run. I use autoprefixer and postcss-cli. The modules have been installed locally in the project directory. I think my "script" part is false. How would that look right?</p>
0debug
static void apic_common_class_init(ObjectClass *klass, void *data) { ICCDeviceClass *idc = ICC_DEVICE_CLASS(klass); DeviceClass *dc = DEVICE_CLASS(klass); dc->vmsd = &vmstate_apic_common; dc->reset = apic_reset_common; dc->props = apic_properties_common; idc->realize = apic_common_realize; dc->cannot_instantiate_with_device_add_yet = true; }
1threat
copying label text to clipboard when clicked : <p>first I have to make UILabel clickable and when it clicked it should copy its text to clipboard. I am using Xcode 10 with swift 5.1.</p> <p>so firstly I am expecting label to be clickable and after that, this click action copy its text to clipboard. this is a basic level program.</p>
0debug
Stream object directly into a std::string : <p>Given some type that is streamable:</p> <pre><code>struct X { int i; friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, X const&amp; x) { return os &lt;&lt; "X(" &lt;&lt; x.i &lt;&lt; ')'; } }; </code></pre> <p>I want to append this onto a <code>std::string</code>. I can implement this as:</p> <pre><code>void append(std::string&amp; s, X const&amp; x) { std::ostringstream os; os &lt;&lt; x; s.append(os.str()); } </code></pre> <p>But this seems lame since I'm writing data into one stream just to then allocate a new string just for the purposes of appending it onto a different one. Is there a more direct route? </p>
0debug
Generating Barcode Using AngularJS : <p>I am developing a POS system for my <strong>dry cleaning business</strong>(Related to clothes).</p> <p>I already have a system which generates a collection receipt when the customer visits our shop. Describing each cloth and its count and each cloth has some service value.</p> <p><strong>Requirement:</strong> Suppose a customer comes with 5 cloths, our present system generates a collection receipt and handed it over to the customer, each receipt has unique tracking ID. Now at the same time, we need to be able to generate 5 barcodes corresponding to each cloth so that we can identify it using the barcode scanner.</p> <p>Backend: Using Java on Google App Engine, Front end is using AngularJS.</p> <p><strong>Planned to buy:</strong> Barcode Printer TSC TTP244 Pro <strong>Planned to buy:</strong> Barcode Scanner TVS BSC101</p> <p>We are using MAC Mini at our Service Desk. </p> <p>Please suggest which Angular API would be suitable and will solve my problem, using these devices with MAC Computer(compatibility). </p> <p>Thanks, Shashank Pratap </p>
0debug
Excel VBA Copy and Paste Rows with Variable Cell Ranges) : I have the code Attached: I get runtime error 1004 on the first xsheet.range, and I am sure the error would occur on the 2 following, in the For Loop. CPC has Value and so does row. In worked in a test sheet but there was no loop. No I lost the test sheet. I would appreciate any help possible. All the best Jim[![Snipit Code][1]][1] [1]: https://i.stack.imgur.com/o8vGv.png
0debug
static BlockDriverAIOCB *rbd_start_aio(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, BlockDriverCompletionFunc *cb, void *opaque, RBDAIOCmd cmd) { RBDAIOCB *acb; RADOSCB *rcb; rbd_completion_t c; int64_t off, size; char *buf; int r; BDRVRBDState *s = bs->opaque; acb = qemu_aio_get(&rbd_aiocb_info, bs, cb, opaque); acb->cmd = cmd; acb->qiov = qiov; if (cmd == RBD_AIO_DISCARD || cmd == RBD_AIO_FLUSH) { acb->bounce = NULL; } else { acb->bounce = qemu_blockalign(bs, qiov->size); } acb->ret = 0; acb->error = 0; acb->s = s; acb->cancelled = 0; acb->bh = NULL; acb->status = -EINPROGRESS; if (cmd == RBD_AIO_WRITE) { qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size); } buf = acb->bounce; off = sector_num * BDRV_SECTOR_SIZE; size = nb_sectors * BDRV_SECTOR_SIZE; rcb = g_malloc(sizeof(RADOSCB)); rcb->done = 0; rcb->acb = acb; rcb->buf = buf; rcb->s = acb->s; rcb->size = size; r = rbd_aio_create_completion(rcb, (rbd_callback_t) rbd_finish_aiocb, &c); if (r < 0) { goto failed; } switch (cmd) { case RBD_AIO_WRITE: r = rbd_aio_write(s->image, off, size, buf, c); break; case RBD_AIO_READ: r = rbd_aio_read(s->image, off, size, buf, c); break; case RBD_AIO_DISCARD: r = rbd_aio_discard_wrapper(s->image, off, size, c); break; case RBD_AIO_FLUSH: r = rbd_aio_flush_wrapper(s->image, c); break; default: r = -EINVAL; } if (r < 0) { goto failed; } return &acb->common; failed: g_free(rcb); qemu_aio_release(acb); return NULL; }
1threat
void helper_lcall_real_T0_T1(int shift, int next_eip) { int new_cs, new_eip; uint32_t esp, esp_mask; uint8_t *ssp; new_cs = T0; new_eip = T1; esp = env->regs[R_ESP]; esp_mask = 0xffffffff; if (!(env->segs[R_SS].flags & DESC_B_MASK)) esp_mask = 0xffff; ssp = env->segs[R_SS].base; if (shift) { esp -= 4; stl(ssp + (esp & esp_mask), env->segs[R_CS].selector); esp -= 4; stl(ssp + (esp & esp_mask), next_eip); } else { esp -= 2; stw(ssp + (esp & esp_mask), env->segs[R_CS].selector); esp -= 2; stw(ssp + (esp & esp_mask), next_eip); } if (!(env->segs[R_SS].flags & DESC_B_MASK)) env->regs[R_ESP] = (env->regs[R_ESP] & ~0xffff) | (esp & 0xffff); else env->regs[R_ESP] = esp; env->eip = new_eip; env->segs[R_CS].selector = new_cs; env->segs[R_CS].base = (uint8_t *)(new_cs << 4); }
1threat
How to find percentage value from a table column : <p>I am trying to find the a percentage value of every numeric value with the same id in my table. For example, if my table consists of this:</p> <pre><code>id answer points 1 answer 1 3 1 answer 2 1 1 answer 3 10 1 answer 4 5 1 answer 5 6 1 answer 6 10 1 answer 7 10 1 answer 8 2 </code></pre> <p>If max points are 80, how can I display the current result (point) from database in percentage form?</p>
0debug
void vga_hw_invalidate(void) { if (active_console->hw_invalidate) active_console->hw_invalidate(active_console->hw); }
1threat
how to create a home button on tkinter that can be used on ever single window to direct myself to home in python without OOP. Thank you : i am doing a programming project i would like to create a home button that can be used on every window and direct me back to home. thank you in advance
0debug
Convert float to int in Julia Lang : <p>Is there a way to convert a floating number to int in Julia? I'm trying to convert a floating point number to a fixed precision number with the decimal part represented as 8bit integer. In order to do this, I need to truncate just the decimal part of the number and I figured the best way to do this would be to subtract the converted integer of x from floating point x:</p> <pre><code> x = 1.23455 y = x - Int(x) println(y) </code></pre> <p>y = 0.23455</p>
0debug
HashMap Java error "null", help me please guys : Hello I am making a project work for my Java courses. I wrote a TicTacToe programm, but I didn`t checked all methods, but only put method and sout method I have a null HashMap instead of 1 in it. This is what I have in the console: Input your column 1 Input your row 1 null (ticTacToe.toConsole();) Where is a mistake? TicTacToe test class: package TicTac; import java.util.Scanner; public class TicTacToeTest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); TicTacToe ticTacToe = new TicTacToe(); System.out.println("Input your column"); int column = scanner.nextInt(); System.out.println("Input your row"); int row = scanner.nextInt(); ticTacToe.selection(column,row); ticTacToe.toConsole(); } } And main TicTacToe class: package TicTac; import java.util.ArrayList; import java.util.HashMap; public class TicTacToe { HashMap<Integer, String> board = new HashMap<>(); public void selection(int column, int row) { String xOrO = "x"; if (column == 1 && row == 1) { board.put(1,xOrO); } else if (column == 1 && row == 2) { board.put(2,xOrO); } else if (column == 1 && row == 3) { board.put(3,xOrO); } else if (column == 2 && row == 1) { board.put(4,xOrO); } else if (column == 2 && row == 2) { board.put(5,xOrO); } else if (column == 2 && row == 3) { board.put(6,xOrO); } else if (column == 3 && row == 1) { board.put(7,xOrO); } else if (column == 3 && row == 2) { board.put(8, xOrO); } else if (column == 3 && row == 3) { board.put(9,xOrO); } else { System.out.println("Wrong data"); } } public void checker() { for (int i = 1; i < 2; i++) { if (board.get(1).equals(board.get(2)) && board.get(2).equals(board.get(3))){ System.out.println(board.get(1) + " player won!"); } else if (board.get(4).equals(board.get(5)) && board.get(5).equals(board.get(6))){ System.out.println(board.get(4) + " player won!"); } else if (board.get(7).equals(board.get(8)) && board.get(8).equals(board.get(9))) { System.out.println(board.get(7) + " player won!"); } else if (board.get(1).equals(board.get(4)) && board.get(4).equals(board.get(7))) { System.out.println(board.get(1) + " player won!"); } else if (board.get(2).equals(board.get(5)) && board.get(5).equals(board.get(8))) { System.out.println(board.get(2) + " player won!"); } else if (board.get(3).equals(board.get(6)) && board.get(6).equals(board.get(9))) { System.out.println(board.get(3) + " player won!"); } else if (board.get(1).equals(board.get(5)) && board.get(5).equals(board.get(8))) { System.out.println(board.get(1) + " player won!"); } else if (board.get(3).equals(board.get(5)) && board.get(5).equals(board.get(7))) { System.out.println(board.get(3) + " player won!"); } } } public void toConsole(){ for (int i = 0; i < board.size(); i++) { System.out.println(board.get(i)); } } }
0debug
int ff_mpeg4_encode_picture_header(MpegEncContext *s, int picture_number) { int time_incr; int time_div, time_mod; if (s->pict_type == AV_PICTURE_TYPE_I) { if (!(s->avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) { if (s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT) mpeg4_encode_visual_object_header(s); if (s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT || picture_number == 0) mpeg4_encode_vol_header(s, 0, 0); } if (!(s->workaround_bugs & FF_BUG_MS)) mpeg4_encode_gop_header(s); } s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B; put_bits(&s->pb, 16, 0); put_bits(&s->pb, 16, VOP_STARTCODE); put_bits(&s->pb, 2, s->pict_type - 1); time_div = FFUDIV(s->time, s->avctx->time_base.den); time_mod = FFUMOD(s->time, s->avctx->time_base.den); time_incr = time_div - s->last_time_base; av_assert0(time_incr >= 0); if (time_incr > 3600) { av_log(s->avctx, AV_LOG_ERROR, "time_incr %d too large\n", time_incr); return AVERROR(EINVAL); } while (time_incr--) put_bits(&s->pb, 1, 1); put_bits(&s->pb, 1, 0); put_bits(&s->pb, 1, 1); put_bits(&s->pb, s->time_increment_bits, time_mod); put_bits(&s->pb, 1, 1); put_bits(&s->pb, 1, 1); if (s->pict_type == AV_PICTURE_TYPE_P) { put_bits(&s->pb, 1, s->no_rounding); } put_bits(&s->pb, 3, 0); if (!s->progressive_sequence) { put_bits(&s->pb, 1, s->current_picture_ptr->f->top_field_first); put_bits(&s->pb, 1, s->alternate_scan); } put_bits(&s->pb, 5, s->qscale); if (s->pict_type != AV_PICTURE_TYPE_I) put_bits(&s->pb, 3, s->f_code); if (s->pict_type == AV_PICTURE_TYPE_B) put_bits(&s->pb, 3, s->b_code); return 0; }
1threat
CS0201 and CS0161 : This code is for a clicker game. There are 2 problems, the first one is in line 19 at "instance == this;" (Error CS0201), and the second one is in line 23 at "public string GetCurrencyIntoString(float valueToConvert){"(Error CS0161) how do i fix them? (I´m sorry, i´m new into Coding) using System.Collections; using UnityEngine; public class CurrencyConverter : MonoBehaviour { private static CurrencyConverter instance; public static CurrencyConverter Instance { get { return instance; } } void Awake(){ CreateInstance (); } void CreateInstance () { if (instance == null) { instance == this; } } public string GetCurrencyIntoString(float valueToConvert){ string converted; if (valueToConvert >= 1000000) { converted = (valueToConvert / 1000f).ToString ("f3") + " Mil"; } else if (valueToConvert >= 1000) { converted = (valueToConvert / 1000f).ToString ("f3") + " K"; } else { converted = ("f0") + "" + valueToConvert; } }
0debug
static GenericList *qmp_input_next_list(Visitor *v, GenericList **list, Error **errp) { QmpInputVisitor *qiv = to_qiv(v); GenericList *entry; StackObject *so = &qiv->stack[qiv->nb_stack - 1]; if (so->entry == NULL) { return NULL; } entry = g_malloc0(sizeof(*entry)); if (*list) { so->entry = qlist_next(so->entry); if (so->entry == NULL) { g_free(entry); return NULL; } (*list)->next = entry; } return entry; }
1threat
void ffserver_parse_acl_row(FFServerStream *stream, FFServerStream* feed, FFServerIPAddressACL *ext_acl, const char *p, const char *filename, int line_num) { char arg[1024]; FFServerIPAddressACL acl; FFServerIPAddressACL *nacl; FFServerIPAddressACL **naclp; ffserver_get_arg(arg, sizeof(arg), &p); if (av_strcasecmp(arg, "allow") == 0) acl.action = IP_ALLOW; else if (av_strcasecmp(arg, "deny") == 0) acl.action = IP_DENY; else { fprintf(stderr, "%s:%d: ACL action '%s' should be ALLOW or DENY.\n", filename, line_num, arg); ffserver_get_arg(arg, sizeof(arg), &p); if (resolve_host(&acl.first, arg)) { fprintf(stderr, "%s:%d: ACL refers to invalid host or IP address '%s'\n", filename, line_num, arg); acl.last = acl.first; ffserver_get_arg(arg, sizeof(arg), &p); if (arg[0]) { if (resolve_host(&acl.last, arg)) { fprintf(stderr, "%s:%d: ACL refers to invalid host or IP address '%s'\n", filename, line_num, arg); nacl = av_mallocz(sizeof(*nacl)); naclp = 0; acl.next = 0; *nacl = acl; if (stream) naclp = &stream->acl; else if (feed) naclp = &feed->acl; else if (ext_acl) naclp = &ext_acl; else fprintf(stderr, "%s:%d: ACL found not in <Stream> or <Feed>\n", filename, line_num); if (naclp) { while (*naclp) naclp = &(*naclp)->next; *naclp = nacl; } else av_free(nacl); bail: return;
1threat
How do I make a JavaScript login form? : <p>I have a regular HTML form with a text field, which is for a password. The idea is that every user logs in with the same password, therefore there is only one password for the site.</p> <p>I'm trying to make some JavaScript to check this password, and if it's the correct password, redirect to another page, meaning that anyone who knew their way around basic JavaScript/had common sense could figure out the password by looking at the source code (it's weird I know).</p> <p>It's really hard to find a tutorial for this, probably because nobody would want to create a password that anyone could easily find out.</p> <p>Thanks in advance for your help. Also, I know the title is a bit misleading; I couldn't figure out how to describe it in less than three sentences.</p>
0debug
Does the command systemctl and service exists on linux only and not mac? : <p>Hi I'm trying to see the status of my apache services on my Mac. I tried the command </p> <pre><code>sudo service httpd status </code></pre> <p>but command not found</p> <p>I look up in Google and discover <code>systemctl</code> so I try that</p> <pre><code>sudo man systemctl </code></pre> <p>and it shows no manual entry for <code>systemctl</code></p> <p>I noticed that I didn't see much mac os and only see linux in the websites on Google.</p> <p>Does the command <code>systemctl</code> and <code>service</code> exists on linux only and not Mac?</p> <p>If so, what is the mac version of these command?</p>
0debug
Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies : <p>I am using Visual Studio 2017 and am trying to create a .Net Standard 1.5 library and use it in a .Net 4.6.2 nUnit test project. </p> <p>I am getting the following error...</p> <blockquote> <p>Could not load file or assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.</p> </blockquote> <p>I have tried the following:</p> <ol> <li><strong>Reference Std library as project reference.</strong> Error: gives me the previous error.</li> <li><strong>Create a NuGet pkg for my Std library and reference that.</strong> Error: The type is System.String, expecting System.String. This is because System.Runtime ended up getting referenced by the project and it has definitions for all the standard types.</li> <li><strong>Reference NuGet pkg NetStandard.Library.</strong> Error: give me the same error as # ("The type is System.String, expecting System.String"). NOTE: Before I did this, I cleared ALL NuGet packages from the project and then added just the nUnit and NetStandard.Library packages (which installed 45 other packages).</li> </ol> <p>Is this a bug? Is there a work-around? Any help is appreciated.</p>
0debug
how to set tablayout icon using fontawesome in android studio : I am a beginner in android.I am using font-awesome library for icons. I want to set the icon using font-awesome in tablyout using view pager Thanks
0debug
static void process_param(float *bc, EqParameter *param, float fs) { int i; for (i = 0; i <= NBANDS; i++) { param[i].lower = i == 0 ? 0 : bands[i - 1]; param[i].upper = i == NBANDS - 1 ? fs : bands[i]; param[i].gain = bc[i]; } }
1threat
static int cpu_x86_register (CPUX86State *env, const char *cpu_model) { x86_def_t def1, *def = &def1; if (cpu_x86_find_by_name(def, cpu_model) < 0) return -1; if (def->vendor1) { env->cpuid_vendor1 = def->vendor1; env->cpuid_vendor2 = def->vendor2; env->cpuid_vendor3 = def->vendor3; } else { env->cpuid_vendor1 = CPUID_VENDOR_INTEL_1; env->cpuid_vendor2 = CPUID_VENDOR_INTEL_2; env->cpuid_vendor3 = CPUID_VENDOR_INTEL_3; } env->cpuid_vendor_override = def->vendor_override; env->cpuid_level = def->level; if (def->family > 0x0f) env->cpuid_version = 0xf00 | ((def->family - 0x0f) << 20); else env->cpuid_version = def->family << 8; env->cpuid_version |= ((def->model & 0xf) << 4) | ((def->model >> 4) << 16); env->cpuid_version |= def->stepping; env->cpuid_features = def->features; env->pat = 0x0007040600070406ULL; env->cpuid_ext_features = def->ext_features; env->cpuid_ext2_features = def->ext2_features; env->cpuid_xlevel = def->xlevel; env->cpuid_ext3_features = def->ext3_features; { const char *model_id = def->model_id; int c, len, i; if (!model_id) model_id = ""; len = strlen(model_id); for(i = 0; i < 48; i++) { if (i >= len) c = '\0'; else c = (uint8_t)model_id[i]; env->cpuid_model[i >> 2] |= c << (8 * (i & 3)); } } return 0; }
1threat
static int v9fs_do_chown(V9fsState *s, V9fsString *path, uid_t uid, gid_t gid) { return s->ops->chown(&s->ctx, path->data, uid, gid); }
1threat
static inline int ff_fast_malloc(void *ptr, unsigned int *size, size_t min_size, int zero_realloc) { void *val; if (min_size < *size) return 0; min_size = FFMAX(17 * min_size / 16 + 32, min_size); av_freep(ptr); val = zero_realloc ? av_mallocz(min_size) : av_malloc(min_size); memcpy(ptr, &val, sizeof(val)); if (!val) min_size = 0; *size = min_size; return 1; }
1threat
static void versatile_init(ram_addr_t ram_size, const char *boot_device, const char *kernel_filename, const char *kernel_cmdline, const char *initrd_filename, const char *cpu_model, int board_id) { CPUState *env; ram_addr_t ram_offset; qemu_irq *cpu_pic; qemu_irq pic[32]; qemu_irq sic[32]; DeviceState *dev; PCIBus *pci_bus; NICInfo *nd; int n; int done_smc = 0; if (!cpu_model) cpu_model = "arm926"; env = cpu_init(cpu_model); if (!env) { fprintf(stderr, "Unable to find CPU definition\n"); exit(1); } ram_offset = qemu_ram_alloc(ram_size); cpu_register_physical_memory(0, ram_size, ram_offset | IO_MEM_RAM); arm_sysctl_init(0x10000000, 0x41007004); cpu_pic = arm_pic_init_cpu(env); dev = sysbus_create_varargs("pl190", 0x10140000, cpu_pic[0], cpu_pic[1], NULL); for (n = 0; n < 32; n++) { pic[n] = qdev_get_gpio_in(dev, n); } dev = sysbus_create_simple("versatilepb_sic", 0x10003000, NULL); for (n = 0; n < 32; n++) { sysbus_connect_irq(sysbus_from_qdev(dev), n, pic[n]); sic[n] = qdev_get_gpio_in(dev, n); } sysbus_create_simple("pl050_keyboard", 0x10006000, sic[3]); sysbus_create_simple("pl050_mouse", 0x10007000, sic[4]); dev = sysbus_create_varargs("versatile_pci", 0x40000000, sic[27], sic[28], sic[29], sic[30], NULL); pci_bus = (PCIBus *)qdev_get_child_bus(dev, "pci"); for(n = 0; n < nb_nics; n++) { nd = &nd_table[n]; if ((!nd->model && !done_smc) || strcmp(nd->model, "smc91c111") == 0) { smc91c111_init(nd, 0x10010000, sic[25]); done_smc = 1; } else { pci_nic_init_nofail(nd, "rtl8139", NULL); } } if (usb_enabled) { usb_ohci_init_pci(pci_bus, -1); } n = drive_get_max_bus(IF_SCSI); while (n >= 0) { pci_create_simple(pci_bus, -1, "lsi53c895a"); n--; } sysbus_create_simple("pl011", 0x101f1000, pic[12]); sysbus_create_simple("pl011", 0x101f2000, pic[13]); sysbus_create_simple("pl011", 0x101f3000, pic[14]); sysbus_create_simple("pl011", 0x10009000, sic[6]); sysbus_create_simple("pl080", 0x10130000, pic[17]); sysbus_create_simple("sp804", 0x101e2000, pic[4]); sysbus_create_simple("sp804", 0x101e3000, pic[5]); sysbus_create_simple("pl110_versatile", 0x10120000, pic[16]); sysbus_create_varargs("pl181", 0x10005000, sic[22], sic[1], NULL); sysbus_create_varargs("pl181", 0x1000b000, sic[23], sic[2], NULL); sysbus_create_simple("pl031", 0x101e8000, pic[10]); versatile_binfo.ram_size = ram_size; versatile_binfo.kernel_filename = kernel_filename; versatile_binfo.kernel_cmdline = kernel_cmdline; versatile_binfo.initrd_filename = initrd_filename; versatile_binfo.board_id = board_id; arm_load_kernel(env, &versatile_binfo); }
1threat
How to find/watch the dimensions of a view in a NativeScript layout? : <p>When my layout loads any view inside of it has a width and height of <code>NaN</code>, it also has a <code>getMeasuredHeight()</code> and <code>getMeasuredWidth()</code> of <code>0</code>.</p> <p>At some point <code>getMeasuredHeight()</code> and <code>getMeasuredWidth()</code> (after the layout is laid out I guess) receive useful values.</p> <p>How can I get the dimensions of anything? How can I watch them change?? When will <code>.width</code> and <code>.height</code> ever not be <code>NaN</code>??? Why can't I make a view hover over the entire screen????</p> <p>So far I've been <strong>polling</strong> every 100ms and I feel pretty dumb. Please help.</p>
0debug
How can I separate classes into different files? : <p>I have a file with two classes and I was asked to separate the second class into a separate file. I have no idea how to do that and I'm wondering if the program will still work. Would I need to put them into the same project or how will I be able to still make the program work?</p>
0debug
Style Bootstrap 4 Custom Checkbox : <p>How do I style a custom checkbox in Bootstrap 4? I've tried everything but I can't even change its background color.</p> <p>This is my code outline:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous"&gt; &lt;label class="custom-control custom-checkbox"&gt; &lt;input type="checkbox" class="custom-control-input"&gt; &lt;span class="custom-control-indicator"&gt;&lt;/span&gt; &lt;span class="custom-control-description"&gt;Check this custom checkbox&lt;/span&gt; &lt;/label&gt;</code></pre> </div> </div> </p> <p>What do I target here? Could someone just show me how to change its background?</p> <p>Thank you.</p>
0debug
static av_cold int tta_decode_init(AVCodecContext * avctx) { TTAContext *s = avctx->priv_data; int i; s->avctx = avctx; if (avctx->extradata_size < 30) return -1; init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8); if (show_bits_long(&s->gb, 32) == AV_RL32("TTA1")) { skip_bits(&s->gb, 32); s->format = get_bits(&s->gb, 16); if (s->format > 2) { av_log(s->avctx, AV_LOG_ERROR, "Invalid format\n"); return -1; if (s->format == FORMAT_ENCRYPTED) { av_log_missing_feature(s->avctx, "Encrypted TTA", 0); return AVERROR(EINVAL); avctx->channels = s->channels = get_bits(&s->gb, 16); avctx->bits_per_coded_sample = get_bits(&s->gb, 16); s->bps = (avctx->bits_per_coded_sample + 7) / 8; avctx->sample_rate = get_bits_long(&s->gb, 32); s->data_length = get_bits_long(&s->gb, 32); skip_bits(&s->gb, 32); switch(s->bps) { case 2: avctx->sample_fmt = AV_SAMPLE_FMT_S16; avctx->bits_per_raw_sample = 16; break; case 3: avctx->sample_fmt = AV_SAMPLE_FMT_S32; avctx->bits_per_raw_sample = 24; break; default: av_log(avctx, AV_LOG_ERROR, "Invalid/unsupported sample format.\n"); if (avctx->sample_rate > 0x7FFFFF) { av_log(avctx, AV_LOG_ERROR, "sample_rate too large\n"); return AVERROR(EINVAL); s->frame_length = 256 * avctx->sample_rate / 245; s->last_frame_length = s->data_length % s->frame_length; s->total_frames = s->data_length / s->frame_length + (s->last_frame_length ? 1 : 0); av_log(s->avctx, AV_LOG_DEBUG, "format: %d chans: %d bps: %d rate: %d block: %d\n", s->format, avctx->channels, avctx->bits_per_coded_sample, avctx->sample_rate, avctx->block_align); av_log(s->avctx, AV_LOG_DEBUG, "data_length: %d frame_length: %d last: %d total: %d\n", s->data_length, s->frame_length, s->last_frame_length, s->total_frames); for (i = 0; i < s->total_frames; i++) skip_bits(&s->gb, 32); skip_bits(&s->gb, 32); if(s->frame_length >= UINT_MAX / (s->channels * sizeof(int32_t))){ av_log(avctx, AV_LOG_ERROR, "frame_length too large\n"); return -1; if (s->bps == 2) { s->decode_buffer = av_mallocz(sizeof(int32_t)*s->frame_length*s->channels); if (!s->decode_buffer) return AVERROR(ENOMEM); s->ch_ctx = av_malloc(avctx->channels * sizeof(*s->ch_ctx)); if (!s->ch_ctx) { av_freep(&s->decode_buffer); return AVERROR(ENOMEM); } else { av_log(avctx, AV_LOG_ERROR, "Wrong extradata present\n"); return -1; avcodec_get_frame_defaults(&s->frame); avctx->coded_frame = &s->frame; return 0;
1threat
static void virtio_net_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass); dc->exit = virtio_net_device_exit; dc->props = virtio_net_properties; set_bit(DEVICE_CATEGORY_NETWORK, dc->categories); vdc->init = virtio_net_device_init; vdc->get_config = virtio_net_get_config; vdc->set_config = virtio_net_set_config; vdc->get_features = virtio_net_get_features; vdc->set_features = virtio_net_set_features; vdc->bad_features = virtio_net_bad_features; vdc->reset = virtio_net_reset; vdc->set_status = virtio_net_set_status; vdc->guest_notifier_mask = virtio_net_guest_notifier_mask; vdc->guest_notifier_pending = virtio_net_guest_notifier_pending; }
1threat
Convert array to object keys : <p>What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.</p> <pre><code>['a','b','c'] </code></pre> <p>to:</p> <pre><code>{ a: '', b: '', c: '' } </code></pre>
0debug
Angular 2 - test for change in route params : <p>I have a component in angular 2 which responds to changes in the route parameters (the component doesn't reload from scratch because we're not moving out of the main route. Here's the component code:</p> <pre><code>export class MyComponent{ ngOnInit() { this._routeInfo.params.forEach((params: Params) =&gt; { if (params['area']){ this._pageToShow =params['area']; } }); } } </code></pre> <p>This works a treat and <code>_pageToShow</code> is set appropriate on navigation.</p> <p>I'm trying to test the behaviour on a change to the route (so a second trigger of the observable but it's refusing to work for me.) Here's my attempt: </p> <pre><code>it('sets PageToShow to new area if params.area is changed', fakeAsync(() =&gt; { let routes : Params[] = [{ 'area': "Terry" }]; TestBed.overrideComponent(MyComponent, { set: { providers: [{ provide: ActivatedRoute, useValue: { 'params': Observable.from(routes)}}] } }); let fixture = TestBed.createComponent(MyComponent); let comp = fixture.componentInstance; let route: ActivatedRoute = fixture.debugElement.injector.get(ActivatedRoute); comp.ngOnInit(); expect(comp.PageToShow).toBe("Terry"); routes.splice(2,0,{ 'area': "Billy" }); fixture.detectChanges(); expect(comp.PageToShow).toBe("Billy"); })); </code></pre> <p>But this throws a <code>TypeError: Cannot read property 'subscribe' of undefined</code> exception when I run it. If I run it without the <code>fixture.detectChanges();</code> line it fails as the second expectation fails.</p>
0debug
Are there any major differences or restrictions when using assets or res/raw folders? : <h2>Background</h2> <p>Some files of the app can only be stored in res/raw or assets folders.</p> <p>Each of those folders work in a very similar way to the other. res/raw folder allows to access files easier, with all the other benefits of resource files, while assets folder allows to access them no matter the file name and structure (including folders and sub folders).</p> <p>The main idea of loading files is about the same for both of them. You just have a choice of ease-of-use, depends on your needs.</p> <h2>The problem</h2> <p>I remember that a very long time ago, I've found some special behavior of both of those folders:</p> <ol> <li><p>Each folder within the assets folder had a max number of files. I think it was about 500, but not sure. I've noticed this behavior a very long time ago, </p></li> <li><p>Some said that files in the assets folder have a max size for files (example <a href="http://www.programering.com/a/MTM0QzMwATg.html" rel="noreferrer"><strong>here</strong></a>). I never saw such a restriction. Not even on Android 2.3 at the time.</p></li> <li><p>Some said (example <a href="http://blog.danlew.net/2013/08/20/joda_time_s_memory_issue_in_android/" rel="noreferrer"><strong>here</strong></a>), and it's still believed even today (example <a href="https://github.com/JakeWharton/ThreeTenABP" rel="noreferrer"><strong>here</strong></a>), that if you load a file from res/raw, it could take much more memory than if you took it from assets folder. </p></li> </ol> <h2>What I've tried</h2> <p>For #1, I never had to use more files anyway after the project I worked on, and at the time I worked on it, we simply split the files into more folders.</p> <p>For #2 , as I wrote, I never noticed it anyway. I used much larger files sizes.</p> <p>For #3, I tried to make a sample project that compares the memory usage between the 2 methods. I didn't notice any difference (memory usage or time to load) between the 2 methods. Especially not a major one. Sadly I have only one device (Nexus 5x), and it has quite a new Android version (8.1). It might be that starting from specific Android version there is no difference between the 2 methods. Another reason for this is that it's harder to measure memory usage on Java, because of the GC, and I've already noticed that on Android 8.x, memory works a bit differently than before (written about it <a href="https://stackoverflow.com/q/48091403/878126"><strong>here</strong></a>).</p> <p>I tried to read about the differences and restrictions of the above, but all I've found are very old articles, so I think things might have changed ever since.</p> <h2>The questions</h2> <p>Actually it's just one question, but I'd like to split it in case the answer is complex:</p> <ol> <li><p>Are there any major or unique limitations or differences between using res/raw and assets folders?</p></li> <li><p>Does reading a file from the assets folder (by creating an input stream from it) really take less memory than using the res/raw? So much that even one of the most appreciated developers (<a href="https://github.com/JakeWharton/ThreeTenABP" rel="noreferrer"><strong>here</strong></a>) decides to choose it, even nowadays? </p></li> <li><p>Have the above restrictions existed up to specific Android versions, and then they became identical in terms of no restrictions whatsoever (except of course files naming for res/raw, but that's just how it works) ? </p></li> <li><p>If so, from which Android version do they work about the same?</p></li> </ol>
0debug
how to upload same name file to amazon s3 and overwrite exist file : <pre><code> s3.putObject({ Bucket: bucketName, Key: fileName, Body: file, ACL: 'bucket-owner-full-control' }, function(err, data) { if (err) { console.log(err); } console.log(data) }); </code></pre> <p>I use this code to upload image to server amazon s3 . But I can't upload a same name file (this name exist on server s3 already ) . How can I upload same name file , and overwrite which exist on server s3 . Thanks for any help :) </p>
0debug
uint32_t HELPER(lcxbr)(CPUS390XState *env, uint32_t f1, uint32_t f2) { CPU_QuadU x1, x2; x2.ll.upper = env->fregs[f2].ll; x2.ll.lower = env->fregs[f2 + 2].ll; x1.q = float128_chs(x2.q); env->fregs[f1].ll = x1.ll.upper; env->fregs[f1 + 2].ll = x1.ll.lower; return set_cc_nz_f128(x1.q); }
1threat
C - why cant i read a linked list in a module and return the header in main? : <p>Today I was pretty confident I would get 100% on my exam, but I wasted all my time trying to fix this error, needless to say I never finished and I'm pretty fed up with it. The idea is:</p> <pre><code>typedef struct Poly{ int x; int y struct Poly *next; }Poly; Poly *add_poly(); int main(){ Poly *a = (Poly*)malloc(sizeof(Poly)); a = add_poly(); //so this should be ret, the first 2 ints i typed should be here printf("%dx^%d",a-&gt;x,a-&gt;y); //this works a=a-&gt;next; printf("%dx^%d",a-&gt;x,a-&gt;y); //this crashes. } Poly *add_poly(){ Poly *temp = (Poly*)malloc(sizeof(Poly)); Poly *ret = (Poly*)malloc(sizeof(Poly)); temp = ret; //make sure i get to keep the header of the list? while(1){ scanf("%d %d",&amp;x,&amp;y); temp-&gt;x=x; temp-&gt;y=y printf("%dx^%d",temp-&gt;x,temp-&gt;y);//authentication temp=temp-&gt;next; temp=(Poly*)malloc(sizeof(Poly)); if(y==0){ temp-&gt;x=0; temp-&gt;y=0; break; } } return ret; } </code></pre> <p>I don't get it! I've worked with linked lists before in much more complex coding but I never had this problem, I must be missing something but I wasted 1:30 hour trying to find the mistake in the exam, and another 2 hours after I went home, same error, even if I actualy deleted and retyped every command from scratch...</p>
0debug
what is the of drawing contours and creating a bounding rectangle on this image, as a newbee to android and openCV. so far : What i have so far, Mat imageMat = new Mat(); Utils.bitmapToMat(photo, imageMat); Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_BGR2GRAY); Imgproc.adaptiveThreshold(imageMat, imageMat, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV, 7, 7); List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Mat hierarchy = new Mat(); Imgproc.findContours(imageMat, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); Bitmap resultBitmap = Bitmap.createBitmap(imageMat.cols(), imageMat.rows(), Bitmap.Config.ARGB_8888); Utils.matToBitmap(imageMat, resultBitmap); ((ImageView) findViewById(R.id.imageView)).setImageBitmap(resultBitmap); [Binary image][1] [1]: https://i.stack.imgur.com/vNqYV.jpg
0debug
New Category not showing in News options tab in typo3 : I have created new category but when I want to create news and assign to a particular category that new category does not come in the options categories list.[list of categories][1] [created new category name][2] [1]: http://i.stack.imgur.com/6Htis.png [2]: http://i.stack.imgur.com/zKwub.png
0debug
convert private matrix form int to double c++ : <p>i wanna convert the private member matrix[] from int to double , i tried to convert it by using the function transform() ? when i input the values ex. matrix[i]= 90.9 it doesn't ceiling the value and doesn't convert it , where is the wrong? </p> <p>Thanks.</p> <pre><code> class A { private : int matrix[10]; public: A(); void inputMatrix(); void transformMatrix(); }; void A::inputMatrix() { for(int i=0; i&lt;10 ; i++) cin&gt;&gt;matrix[i]; } void A::transform() { ceil(matrix[i]); double matrix = static_cast&lt;double&gt;(matrix[i]); cout &lt;&lt; matrix[i] ; } </code></pre>
0debug
void HELPER(yield)(CPUARMState *env) { ARMCPU *cpu = arm_env_get_cpu(env); CPUState *cs = CPU(cpu); g_assert(!parallel_cpus); cs->exception_index = EXCP_YIELD; cpu_loop_exit(cs); }
1threat
how to use bar code reader in c# windows application? : <p>I want to create windows application in c# that can work with bar code reader.</p> <p>I want following feature to be add in my windows application:</p> <p>-> Details of Product should be fill up automatically in form when bar code reader scanned correct bar code of product.</p>
0debug
Project build error: 'dependencies.dependency.version' for org.springframework.cloud:spring-cloud-starter-eureka-server:jar is missing : <p>I am developing a code from <a href="https://www.dineshonjava.com/microservices-with-spring-boot/" rel="noreferrer">https://www.dineshonjava.com/microservices-with-spring-boot/</a>. When I update the spring-boot-starter-parent from <code>1.5.4.RELEASE</code> to <code>2.0.4.RELEASE</code>, build got failed.</p> <p>Could anyone please guide me what is the issue ?</p> <blockquote> <p>Project build error: 'dependencies.dependency.version' for org.springframework.cloud:spring-cloud-starter-eureka-server:jar is missing.</p> </blockquote> <p>Another error:</p> <pre><code>Multiple annotations found at this line: - For artifact {org.springframework.cloud:spring-cloud-starter-eureka-server:null:jar}: The version cannot be empty. (org.apache.maven.plugins:maven-resources-plugin:3.0.2:resources:default-resources:process- resources) org.apache.maven.artifact.InvalidArtifactRTException: For artifact {org.springframework.cloud:spring-cloud-starter-eureka-server:null:jar}: The version cannot be empty. at org.apache.maven.artifact.DefaultArtifact.validateIdentity(DefaultArtifact.java:148) at org.apache.maven.artifact.DefaultArtifact.&lt;init&gt;(DefaultArtifact.java:123) at org.apache.maven.artifact.factory.DefaultArtifactFactory.createArtifact(DefaultArtifactFactory.java:157) at org.apache.maven.artifact.factory.DefaultArtifactFactory.createDependencyArtifact(DefaultArtifactFactory.java: 57) at org.apache.maven.project.artifact.MavenMetadataSource.createDependencyArtifact(MavenMetadataSource.java:328) at org.apache.maven.project.artifact.MavenMetadataSource.createArtifacts(MavenMetadataSource.java:503) at </code></pre> <p><strong>pom.xml</strong></p> <pre><code>&lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.0.4.RELEASE&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-starter&lt;/artifactId&gt; &lt;/dependency&gt; &lt;!-- Eureka registration server --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-starter-eureka-server&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt; &lt;!-- &lt;version&gt;Camden.SR5&lt;/version&gt; --&gt; &lt;version&gt;Finchley.RELEASE&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/dependencyManagement&gt; </code></pre>
0debug
C++ sort() function for sorting strings : <p><br> Some days ago I wanted to use c++ <code>sort()</code> function to sort an array of strings which the total size, but I had a problem!<br> Does this function use the same algorithm for sorting numbers array and strings array? And if we use it to sort an array of strings which the total size of them is less than 100,000 characters, would it work in less than 1 second(in the worst case)?</p>
0debug
How to enable android vitals in google developer console? : <p>I am not able to see any data in my vitals overview section (ANR rate , Crash rate ... ) always the same message :</p> <p>Sorry, this data is not available.</p> <p>Are there any steps that i should go into to enable this feature ?</p> <p>Thank you</p>
0debug
int url_open(URLContext **puc, const char *filename, int flags) { URLProtocol *up; const char *p; char proto_str[128], *q; p = filename; q = proto_str; while (*p != '\0' && *p != ':') { if (!isalpha(*p)) goto file_proto; if ((q - proto_str) < sizeof(proto_str) - 1) *q++ = *p; p++; } if (*p == '\0' || (q - proto_str) <= 1) { file_proto: strcpy(proto_str, "file"); } else { *q = '\0'; } up = first_protocol; while (up != NULL) { if (!strcmp(proto_str, up->name)) return url_open_protocol (puc, up, filename, flags); up = up->next; } *puc = NULL; return AVERROR(ENOENT); }
1threat
Numpy argmax - random tie breaking : <p>In <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html" rel="noreferrer">numpy.argmax</a> function, tie breaking between multiple max elements is so that the first element is returned. Is there a functionality for randomizing tie breaking so that all maximum numbers have equal chance of being selected? </p> <p>Below is an example directly from numpy.argmax documentation. </p> <pre><code>&gt;&gt;&gt; b = np.arange(6) &gt;&gt;&gt; b[1] = 5 &gt;&gt;&gt; b array([0, 5, 2, 3, 4, 5]) &gt;&gt;&gt; np.argmax(b) # Only the first occurrence is returned. 1 </code></pre> <p>I am looking for ways so that 1st and 5th elements in the list are returned with equal probability.</p> <p>Thank you! </p>
0debug
How do I interpret a message payload without violating type aliasing rules? : <p>My program receives messages over the network. These messages are deserialized by some middleware (i.e. someone else's code which I cannot change). My program receives objects that look something like this:</p> <pre><code>struct Message { int msg_type; std::vector&lt;uint8_t&gt; payload; }; </code></pre> <p>By examining <code>msg_type</code> I can determine that the message payload is actually, for example, an array of <code>uint16_t</code> values. I would like to read that array without an unnecessary copy.</p> <p>My first thought was to do this:</p> <pre><code>const uint16_t* a = reinterpret_cast&lt;uint16_t*&gt;(msg.payload.data()); </code></pre> <p>But then reading from <code>a</code> would appear to violate the standard. Here is clause 3.10.10:</p> <blockquote> <p>If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:</p> <ul> <li>the dynamic type of the object,</li> <li>a cv-qualified version of the dynamic type of the object,</li> <li>a type similar (as defined in 4.4) to the dynamic type of the object,</li> <li>a type that is the signed or unsigned type corresponding to the dynamic type of the object,</li> <li>a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,</li> <li>an aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members (including, recursively, an element or non-static data member of a subaggregate or contained union),</li> <li>a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,</li> <li>a <code>char</code> or <code>unsigned char</code> type.</li> </ul> </blockquote> <p>In this case, <code>a</code> would be the glvalue and <code>uint16_t*</code> does not appear to meet any of the listed criteria.</p> <p>So how do I treat the payload as an array of <code>uint16_t</code> values without invoking undefined behavior or performing an unnecessary copy?</p>
0debug
leader clustering algorithm vs overlapping clustering algorithm : <p>I am trying to understand leader clustering algorithm and overlapping clustering algorithm , but not able to get proper documents and explanations. Can someone please help me understand these clustering algorithms that what are the key differences between both (leader clustering and overlapping clustering) algorithms, and if applicable, which algorithm provides the best result with large datasets.</p>
0debug
static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size, int64_t pos, uint64_t cluster_time, uint64_t block_duration, int is_keyframe, uint8_t *additional, uint64_t additional_id, int additional_size, int64_t cluster_pos, int64_t discard_padding) { uint64_t timecode = AV_NOPTS_VALUE; MatroskaTrack *track; int res = 0; AVStream *st; int16_t block_time; uint32_t *lace_size = NULL; int n, flags, laces = 0; uint64_t num; int trust_default_duration = 1; if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) { av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n"); return n; } data += n; size -= n; track = matroska_find_track_by_num(matroska, num); if (!track || !track->stream) { av_log(matroska->ctx, AV_LOG_INFO, "Invalid stream %"PRIu64" or size %u\n", num, size); return AVERROR_INVALIDDATA; } else if (size <= 3) return 0; st = track->stream; if (st->discard >= AVDISCARD_ALL) return res; av_assert1(block_duration != AV_NOPTS_VALUE); block_time = sign_extend(AV_RB16(data), 16); data += 2; flags = *data++; size -= 3; if (is_keyframe == -1) is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0; if (cluster_time != (uint64_t) -1 && (block_time >= 0 || cluster_time >= -block_time)) { timecode = cluster_time + block_time - track->codec_delay_in_track_tb; if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE && timecode < track->end_timecode) is_keyframe = 0; if (is_keyframe) av_add_index_entry(st, cluster_pos, timecode, 0, 0, AVINDEX_KEYFRAME); } if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) { if (timecode < matroska->skip_to_timecode) return res; if (is_keyframe) matroska->skip_to_keyframe = 0; else if (!st->skip_to_keyframe) { av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n"); matroska->skip_to_keyframe = 0; } } res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1, &lace_size, &laces); if (res) goto end; if (track->audio.samplerate == 8000) { if (st->codecpar->codec_id == AV_CODEC_ID_AC3) { if (track->audio.samplerate != st->codecpar->sample_rate || !st->codecpar->frame_size) trust_default_duration = 0; } } if (!block_duration && trust_default_duration) block_duration = track->default_duration * laces / matroska->time_scale; if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time)) track->end_timecode = FFMAX(track->end_timecode, timecode + block_duration); for (n = 0; n < laces; n++) { int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces; if (lace_size[n] > size) { av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n"); break; } if ((st->codecpar->codec_id == AV_CODEC_ID_RA_288 || st->codecpar->codec_id == AV_CODEC_ID_COOK || st->codecpar->codec_id == AV_CODEC_ID_SIPR || st->codecpar->codec_id == AV_CODEC_ID_ATRAC3) && st->codecpar->block_align && track->audio.sub_packet_size) { res = matroska_parse_rm_audio(matroska, track, st, data, lace_size[n], timecode, pos); if (res) goto end; } else if (st->codecpar->codec_id == AV_CODEC_ID_WEBVTT) { res = matroska_parse_webvtt(matroska, track, st, data, lace_size[n], timecode, lace_duration, pos); if (res) goto end; } else { res = matroska_parse_frame(matroska, track, st, data, lace_size[n], timecode, lace_duration, pos, !n ? is_keyframe : 0, additional, additional_id, additional_size, discard_padding); if (res) goto end; } if (timecode != AV_NOPTS_VALUE) timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE; data += lace_size[n]; size -= lace_size[n]; } end: av_free(lace_size); return res; }
1threat
How To Use toLowerCase in Selector Condion In Jquery : var path = window.location.pathname; // Returns path only var element = jq_menu("#topMenu a[href='" + path + "']"); element.parent().closest('li').addClass('active'); i use this codes for select active menu i want convert href value to lowerCase at Line 2 Code How Can I Do That
0debug
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.HashMap : <p>I have looked through numerous questions that are very similar to mine and have tried all the fixes that the other questions recommended to no avail. So I decided I'd post my own question in hopes that someone can help. </p> <p>NewsActivity:</p> <pre><code>import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.media.Image; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; public class NewsActivity extends Activity { private String xmlData; private ListView listView; private ArrayList&lt;News&gt; allNews; private Image newsImage; public final static String ITEM_TITLE = "newsTitle"; public final static String ITEM_DATE = "newsDate"; public final static String ITEM_DESCRIPTION = "newsDescription"; public final static String ITEM_IMGURL = "newsImageURL"; public Map&lt;String, ?&gt; createItem(String title, String date, String url) { Map&lt;String,String&gt; item = new HashMap&lt;&gt;(); item.put(ITEM_TITLE, title); item.put(ITEM_DATE, date); item.put(ITEM_IMGURL, url); return item; } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar bar = getActionBar(); bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#f8f8f8"))); bar.setDisplayShowHomeEnabled(false); bar.setDisplayShowTitleEnabled(true); bar.setDisplayUseLogoEnabled(false); bar.setTitle("News"); setContentView(R.layout.news_layout); Bundle newsBundle = getIntent().getExtras(); xmlData = newsBundle.getString("xmlData"); final ArrayList&lt;News&gt; newsData = getNewsData(xmlData); allNews = new ArrayList&lt;News&gt;(); List&lt;Map&lt;String, ?&gt;&gt; data = new LinkedList&lt;Map&lt;String, ?&gt;&gt;(); for(int i = 0; i &lt; newsData.size(); i++) { News currentNews = newsData.get(i); String newsTitle = currentNews.getNewsTitle(); String newsDate = currentNews.getNewsDate(); String newsDescription = currentNews.getNewsDescription(); String newsImageURL = currentNews.getNewsImageUrl(); data.add(createItem(newsTitle, newsDate, newsImageURL)); allNews.add(currentNews); } listView = (ListView) findViewById(R.id.news_list); LazyNewsAdapter adapter = new LazyNewsAdapter(this, newsData); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { Map&lt;String, String&gt; item = (HashMap&lt;String, String&gt;) parent.getItemAtPosition(position); //**ERROR IS HERE: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.HashMap** // String title = item.get(ITEM_TITLE); String url = item.get(ITEM_IMGURL); String date = item.get(ITEM_DATE); Iterator&lt;News&gt; itp = allNews.iterator(); News currentNews = null; while (itp.hasNext()) { currentNews = itp.next(); if (title == currentNews.getNewsTitle() &amp;&amp; url == currentNews.getNewsImageUrl() &amp;&amp; date == currentNews.getNewsDate()) break; } String newsTitle = currentNews.getNewsTitle(); String newsDescription = currentNews.getNewsDescription(); String newsUrl = currentNews.getNewsImageUrl(); String newsDate = currentNews.getNewsDate(); Intent detailnewsScreen = new Intent(getApplicationContext(), DetailNewsActivity.class); detailnewsScreen.putExtra("newsTitle", newsTitle); detailnewsScreen.putExtra("newsDescription", newsDescription); detailnewsScreen.putExtra("url", newsUrl); detailnewsScreen.putExtra("newsDate", newsDate); startActivity(detailnewsScreen); } }); } private ArrayList&lt;News&gt; getNewsData(String src) { ArrayList&lt;News&gt; newsList = new ArrayList&lt;&gt;(); News currentNews = new News(); String newsTitle = new String(); String newsDate = new String(); String newsUrl = new String(); String newsDescription = new String(); try { StringReader sr = new StringReader(src); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(sr); int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { String name = null; switch (eventType) { case XmlPullParser.START_TAG: name = xpp.getName(); if (name.equals("news")) { currentNews = new News(); } else if (name.equals("ntitle")) { newsTitle = xpp.nextText(); newsTitle = newsTitle.trim(); } else if (name.equals("ndate")) { newsDate = xpp.nextText(); newsDate = newsDate.trim(); } else if (name.equals("nimage")) { newsUrl = xpp.nextText(); newsUrl = newsUrl.trim(); } else if (name.equals("ndescription")) { newsDescription = xpp.nextText(); newsDescription = newsDescription.trim(); } break; case XmlPullParser.END_TAG: name = xpp.getName(); if (name.equals("news")) { currentNews.setNewsTitle(newsTitle); currentNews.setNewsDate(newsDate); currentNews.setNewsImageUrl("http://www.branko-cirovic.appspot.com/iWeek/news/images/" + newsUrl); currentNews.setNewsDescription(newsDescription); newsList.add(currentNews); } break; } eventType = xpp.next(); } } catch (Exception e){ e.printStackTrace(); } return newsList; } } </code></pre> <p>LazyNewsAdapter:</p> <pre><code>import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; public class LazyNewsAdapter extends BaseAdapter { private Activity activity; private ArrayList&lt;News&gt; listData; private LayoutInflater inflater = null; public LazyNewsAdapter(Activity activity, ArrayList&lt;News&gt; listData) { this.activity = activity; this.listData = listData; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return listData.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { News newsItem = listData.get(position); View view = convertView; if(convertView == null) view = inflater.inflate(R.layout.news_cell, null); TextView newsTitle = (TextView) view.findViewById(R.id.newsTitle); TextView newsDate = (TextView) view.findViewById(R.id.newsDate); ImageView image = (ImageView) view.findViewById(R.id.newsImage); newsTitle.setText(newsItem.getNewsTitle()); newsDate.setText(newsItem.getNewsDate()); String url = newsItem.getNewsImageUrl(); ImageLoader imageLoader = new ImageLoader(activity, 600, R.mipmap.placeholder); imageLoader.displayImage(url, image); return view; } } </code></pre> <p>The error that I am getting has a comment next to it in the NewsActivity. It seems to be trying to cast an integer to a HashMap for some reason. I have multiple other classes that use this exact method and have no issue, but for this NewsActivity I am getting this error.</p> <p>Any suggestions?</p> <p>Thanks so much!</p>
0debug
int inet_listen(const char *str, char *ostr, int olen, int socktype, int port_offset, Error **errp) { QemuOpts *opts; char *optstr; int sock = -1; opts = qemu_opts_create(&dummy_opts, NULL, 0); if (inet_parse(opts, str) == 0) { sock = inet_listen_opts(opts, port_offset, errp); if (sock != -1 && ostr) { optstr = strchr(str, ','); if (qemu_opt_get_bool(opts, "ipv6", 0)) { snprintf(ostr, olen, "[%s]:%s%s", qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"), optstr ? optstr : ""); } else { snprintf(ostr, olen, "%s:%s%s", qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"), optstr ? optstr : ""); } } } else { error_set(errp, QERR_SOCKET_CREATE_FAILED); } qemu_opts_del(opts); return sock; }
1threat
Transpiling SASS on the fly with SystemJS : <p>I read a lot of blogs that say SystemJS and SASS transpiling works, but every example I see online appears to handle the SASS processing up front (via a gulp-like task runner), and the JavaScript code then imports the generated CSS.</p> <p>What I'm hoping to be able to do is to have my JavaScript files import the SASS files directly (and have my SystemJS loader transpile into CSS on-the-fly). This is just for development purposes, for production, I plan to build a single static file with everything in it. Is this possible? If so, how is this typically done?</p> <p>Additional info: I am using Angular2 and Typescript as well.</p> <p>Thanks.</p>
0debug
static void sdhci_end_transfer(SDHCIState *s) { if ((s->trnmod & SDHC_TRNS_ACMD12) != 0) { SDRequest request; uint8_t response[16]; request.cmd = 0x0C; request.arg = 0; DPRINT_L1("Automatically issue CMD%d %08x\n", request.cmd, request.arg); sdbus_do_command(&s->sdbus, &request, response); s->rspreg[3] = (response[0] << 24) | (response[1] << 16) | (response[2] << 8) | response[3]; } s->prnsts &= ~(SDHC_DOING_READ | SDHC_DOING_WRITE | SDHC_DAT_LINE_ACTIVE | SDHC_DATA_INHIBIT | SDHC_SPACE_AVAILABLE | SDHC_DATA_AVAILABLE); if (s->norintstsen & SDHC_NISEN_TRSCMP) { s->norintsts |= SDHC_NIS_TRSCMP; } sdhci_update_irq(s); }
1threat
static void bcm2835_property_mbox_push(BCM2835PropertyState *s, uint32_t value) { uint32_t tag; uint32_t bufsize; uint32_t tot_len; size_t resplen; uint32_t tmp; value &= ~0xf; s->addr = value; tot_len = ldl_phys(&s->dma_as, value); value = s->addr + 8; while (value + 8 <= s->addr + tot_len) { tag = ldl_phys(&s->dma_as, value); bufsize = ldl_phys(&s->dma_as, value + 4); resplen = 0; switch (tag) { case 0x00000000: break; case 0x00000001: stl_phys(&s->dma_as, value + 12, 346337); resplen = 4; break; case 0x00010001: qemu_log_mask(LOG_UNIMP, "bcm2835_property: %x get board model NYI\n", tag); resplen = 4; break; case 0x00010002: qemu_log_mask(LOG_UNIMP, "bcm2835_property: %x get board revision NYI\n", tag); resplen = 4; break; case 0x00010003: resplen = sizeof(s->macaddr.a); dma_memory_write(&s->dma_as, value + 12, s->macaddr.a, resplen); break; case 0x00010004: qemu_log_mask(LOG_UNIMP, "bcm2835_property: %x get board serial NYI\n", tag); resplen = 8; break; case 0x00010005: stl_phys(&s->dma_as, value + 12, 0); stl_phys(&s->dma_as, value + 16, s->ram_size); resplen = 8; break; case 0x00028001: tmp = ldl_phys(&s->dma_as, value + 16); stl_phys(&s->dma_as, value + 16, (tmp & 1)); resplen = 8; break; case 0x00030001: stl_phys(&s->dma_as, value + 16, 0x1); resplen = 8; break; case 0x00038001: qemu_log_mask(LOG_UNIMP, "bcm2835_property: %x set clock state NYI\n", tag); resplen = 8; break; case 0x00030002: case 0x00030004: case 0x00030007: switch (ldl_phys(&s->dma_as, value + 12)) { case 1: stl_phys(&s->dma_as, value + 16, 50000000); break; case 2: stl_phys(&s->dma_as, value + 16, 3000000); break; default: stl_phys(&s->dma_as, value + 16, 700000000); break; } resplen = 8; break; case 0x00038002: case 0x00038004: case 0x00038007: qemu_log_mask(LOG_UNIMP, "bcm2835_property: %x set clock rates NYI\n", tag); resplen = 8; break; case 0x00030006: stl_phys(&s->dma_as, value + 16, 25000); resplen = 8; break; case 0x0003000A: stl_phys(&s->dma_as, value + 16, 99000); resplen = 8; break; case 0x00060001: stl_phys(&s->dma_as, value + 12, 0x003C); resplen = 4; break; case 0x00050001: resplen = 0; break; default: qemu_log_mask(LOG_GUEST_ERROR, "bcm2835_property: unhandled tag %08x\n", tag); break; } if (tag == 0) { break; } stl_phys(&s->dma_as, value + 8, (1 << 31) | resplen); value += bufsize + 12; } stl_phys(&s->dma_as, s->addr + 4, (1 << 31)); }
1threat
static int pcm_decode_frame(AVCodecContext *avctx, void *data, int *data_size, uint8_t *buf, int buf_size) { PCMDecode *s = avctx->priv_data; int c, n; short *samples; uint8_t *src, *src2[MAX_CHANNELS]; samples = data; src = buf; n= av_get_bits_per_sample(avctx->codec_id)/8; if((n && buf_size % n) || avctx->channels > MAX_CHANNELS){ av_log(avctx, AV_LOG_ERROR, "invalid PCM packet\n"); return -1; } buf_size= FFMIN(buf_size, *data_size/2); *data_size=0; n = buf_size/avctx->channels; for(c=0;c<avctx->channels;c++) src2[c] = &src[c*n]; switch(avctx->codec->id) { case CODEC_ID_PCM_S32LE: decode_to16(4, 1, 0, &src, &samples, buf_size); break; case CODEC_ID_PCM_S32BE: decode_to16(4, 0, 0, &src, &samples, buf_size); break; case CODEC_ID_PCM_U32LE: decode_to16(4, 1, 1, &src, &samples, buf_size); break; case CODEC_ID_PCM_U32BE: decode_to16(4, 0, 1, &src, &samples, buf_size); break; case CODEC_ID_PCM_S24LE: decode_to16(3, 1, 0, &src, &samples, buf_size); break; case CODEC_ID_PCM_S24BE: decode_to16(3, 0, 0, &src, &samples, buf_size); break; case CODEC_ID_PCM_U24LE: decode_to16(3, 1, 1, &src, &samples, buf_size); break; case CODEC_ID_PCM_U24BE: decode_to16(3, 0, 1, &src, &samples, buf_size); break; case CODEC_ID_PCM_S24DAUD: n = buf_size / 3; for(;n>0;n--) { uint32_t v = bytestream_get_be24(&src); v >>= 4; *samples++ = ff_reverse[(v >> 8) & 0xff] + (ff_reverse[v & 0xff] << 8); } break; case CODEC_ID_PCM_S16LE: n = buf_size >> 1; for(;n>0;n--) { *samples++ = bytestream_get_le16(&src); } break; case CODEC_ID_PCM_S16LE_PLANAR: for(n>>=1;n>0;n--) for(c=0;c<avctx->channels;c++) *samples++ = bytestream_get_le16(&src2[c]); src = src2[avctx->channels-1]; break; case CODEC_ID_PCM_S16BE: n = buf_size >> 1; for(;n>0;n--) { *samples++ = bytestream_get_be16(&src); } break; case CODEC_ID_PCM_U16LE: n = buf_size >> 1; for(;n>0;n--) { *samples++ = bytestream_get_le16(&src) - 0x8000; } break; case CODEC_ID_PCM_U16BE: n = buf_size >> 1; for(;n>0;n--) { *samples++ = bytestream_get_be16(&src) - 0x8000; } break; case CODEC_ID_PCM_S8: n = buf_size; for(;n>0;n--) { *samples++ = *src++ << 8; } break; case CODEC_ID_PCM_U8: n = buf_size; for(;n>0;n--) { *samples++ = ((int)*src++ - 128) << 8; } break; case CODEC_ID_PCM_ZORK: n = buf_size; for(;n>0;n--) { int x= *src++; if(x&128) x-= 128; else x = -x; *samples++ = x << 8; } break; case CODEC_ID_PCM_ALAW: case CODEC_ID_PCM_MULAW: n = buf_size; for(;n>0;n--) { *samples++ = s->table[*src++]; } break; default: return -1; } *data_size = (uint8_t *)samples - (uint8_t *)data; return src - buf; }
1threat
static int standard_decode_i_mbs(VC9Context *v) { int x, y, ac_pred, cbpcy; if (v->pq < 5) v->ttmb_vlc = &vc9_ttmb_vlc[0]; else if (v->pq < 13) v->ttmb_vlc = &vc9_ttmb_vlc[1]; else v->ttmb_vlc = &vc9_ttmb_vlc[2]; for (y=0; y<v->height_mb; y++) { for (x=0; x<v->width_mb; x++) { cbpcy = get_vlc2(&v->gb, vc9_cbpcy_i_vlc.table, VC9_CBPCY_I_VLC_BITS, 2); ac_pred = get_bits(&v->gb, 1); } } return 0; }
1threat
static QObject *parse_object(JSONParserContext *ctxt, va_list *ap) { QDict *dict = NULL; QObject *token, *peek; JSONParserContext saved_ctxt = parser_context_save(ctxt); token = parser_context_pop_token(ctxt); if (token == NULL) { goto out; } if (!token_is_operator(token, '{')) { goto out; } dict = qdict_new(); peek = parser_context_peek_token(ctxt); if (peek == NULL) { parse_error(ctxt, NULL, "premature EOI"); goto out; } if (!token_is_operator(peek, '}')) { if (parse_pair(ctxt, dict, ap) == -1) { goto out; } token = parser_context_pop_token(ctxt); if (token == NULL) { parse_error(ctxt, NULL, "premature EOI"); goto out; } while (!token_is_operator(token, '}')) { if (!token_is_operator(token, ',')) { parse_error(ctxt, token, "expected separator in dict"); goto out; } if (parse_pair(ctxt, dict, ap) == -1) { goto out; } token = parser_context_pop_token(ctxt); if (token == NULL) { parse_error(ctxt, NULL, "premature EOI"); goto out; } } } else { (void)parser_context_pop_token(ctxt); } return QOBJECT(dict); out: parser_context_restore(ctxt, saved_ctxt); QDECREF(dict); return NULL; }
1threat
Get first letter of a string from column : <p>I'm fighting with pandas and for now I'm loosing. I have source table similar to this:</p> <pre><code>import pandas as pd a=pd.Series([123,22,32,453,45,453,56]) b=pd.Series([234,4353,355,453,345,453,56]) df=pd.concat([a, b], axis=1) df.columns=['First', 'Second'] </code></pre> <p>I would like to add new column to this data frame with first digit from values in column 'First': a) change number to string from column 'First' b) extracting first character from newly created string c) Results from b save as new column in data frame</p> <p>I don't know how to apply this to the pandas data frame object. I would be grateful for helping me with that.</p>
0debug
I get an error in visual studio 2017 using the header stdafx.h in the code (Newbie) : I'm a newbie on an adventure in the world of C++. Here is the code. What am I doing wrong thanks for your help. I'm using visual studio 2017. 1>------ Build started: Project: Print1, Configuration: Debug Win32 ------ 1>Print1.cpp 1>c:\users\kiwiblazer\source\repos\print1\print1\print1.cpp(4): fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "pch.h"' to your source? 1>Done building project "Print1.vcxproj" -- FAILED. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== #include "stdafx.h" #include <iostream> using namespace std; int main() { cout << "Never fear, C++ is here! "; return 0;
0debug
How to create an array with its first list being ['0','1','2',...] etc up to 8? (as strings, not integers) : <p>Making a treasure hunt game and for the board, I would like numbers along the top and side for coordinates of a grid, the top line will be the numbers 0-8 in a list. Here's my code:</p> <pre><code>board=[] board.append([]) for i in range(9): i2=str(i) board[i].append(i2) </code></pre> <p>Although when i run it I get the error:</p> <pre><code>board[i].append(i2) </code></pre> <p>IndexError: list index out of range</p>
0debug
PowerShell guidelines for -Confirm, -Force, and -WhatIf : <p>Are there any official guidelines from Microsoft about when to add <code>-Confirm</code>, <code>-Force</code>, and <code>-WhatIf</code> parameters to custom PowerShell cmdlets? There doesn't seem to be a clear consensus about when/how to use these parameters. For example <a href="https://github.com/Azure/azure-powershell/issues/475" rel="noreferrer">this issue</a>.</p> <p>In the absence of formal guidelines, is there a best practice or rule of thumb to use? Here is some more background, with my current (possibly flawed) understanding:</p> <h2>-WhatIf</h2> <p>The <code>-WhatIf</code> flag displays what the cmdlet <em>would do</em> without actually performing any action. This is useful for a dry run of a potentially destabilizing operation, to see what the actual results would be. The parameter is automatically added if the cmdlet's <code>Cmdlet</code> attribute has the <a href="https://msdn.microsoft.com/en-us/library/system.management.automation.cmdletcommonmetadataattribute.supportsshouldprocess(v=vs.85).aspx" rel="noreferrer"><code>SupportsShouldProcess</code></a> property set to true.</p> <p>It seems like (but I'd love to see more official guidance here) that you should add <code>-WhatIf</code> if you are ever adding or removing resources. (e.g. deleing files.) Operations that update existing resources probably wouldn't benefit from it. Right?</p> <h2>-Force</h2> <p>The <code>-Force</code> switch is used to declare "I know what I'm doing, and I'm sure I want to do this". For example, when copying a file (<a href="https://technet.microsoft.com/en-us/library/hh849793.aspx" rel="noreferrer"><code>Copy-File</code></a>) the <code>-Force</code> parameter means:</p> <blockquote> <p>Allows the cmdlet to copy items that cannot otherwise be changed, such as copying over a read-only file or alias.</p> </blockquote> <p>So to me it seems like (again, I'd love some official guidance here) that you should add an optional <code>-Force</code> parameter when you have a situation where the cmdlet would otherwise fail, but can be convinced to complete the action.</p> <p>For example, if you are creating a new resource that will clobber an existing one with the same name. The default behavior of the cmdlet would report an error and fail. But if you add <code>-Force</code> it will continue (and overwrite the existing resource). Right?</p> <h2>-Confirm</h2> <p>The <code>-Confirm</code> flag gets automatically added like <code>-WhatIf</code> if the cmdlet has <code>SupportsShouldProcess</code> set to true. In a cmdlet if you call <a href="https://msdn.microsoft.com/en-us/library/system.management.automation.cmdlet.shouldprocess(v=vs.85).aspx" rel="noreferrer"><code>ShouldProcess</code></a> then the user will be prompted to perform the action. And if the <code>-Confirm</code> flag is added, there will be no prompt. (i.e. the confirmation is added via the cmdlet invocation.)</p> <p>So <code>-Confirm</code> should be available whenever a cmdlet has a big impact on the system. Just like <code>-WhatIf</code> this should be added whenever a resource is added or removed.</p> <p>With my potentially incorrect understanding in mind, here are some of the questions I'd like a concrete answer to:</p> <ul> <li>When should it be necessary to add <code>-WhatIf</code>/<code>-Confirm</code>?</li> <li>When should it be necessary to add <code>-Force</code>?</li> <li>Does it ever make sense to support both <code>-Confirm</code> and <code>-Force</code>?</li> </ul>
0debug
What is the interpretation of this code : <p>Could someone explain in the simplest terms, as if you are talking to an idiot (because you are), what this code is actually saying/doing/meaning?</p> <pre><code>var i = 5; while(--i &gt; 0){ console.log(i); } </code></pre>
0debug
static void *nbd_client_thread(void *arg) { char *device = arg; off_t size; size_t blocksize; uint32_t nbdflags; int fd, sock; int ret; pthread_t show_parts_thread; sock = unix_socket_outgoing(sockpath); if (sock < 0) { goto out; } ret = nbd_receive_negotiate(sock, NULL, &nbdflags, &size, &blocksize); if (ret < 0) { goto out; } fd = open(device, O_RDWR); if (fd < 0) { fprintf(stderr, "Failed to open %s: %m", device); goto out; } ret = nbd_init(fd, sock, nbdflags, size, blocksize); if (ret < 0) { goto out; } pthread_create(&show_parts_thread, NULL, show_parts, device); if (verbose) { fprintf(stderr, "NBD device %s is now connected to %s\n", device, srcpath); } else { dup2(STDOUT_FILENO, STDERR_FILENO); } ret = nbd_client(fd); if (ret) { goto out; } close(fd); kill(getpid(), SIGTERM); return (void *) EXIT_SUCCESS; out: kill(getpid(), SIGTERM); return (void *) EXIT_FAILURE; }
1threat
How to make a .bat file that can have a look what is the answear? : Hello I don't know how to make a .bat file that can use vbyes or vbno. I tried this: @echo off color 0a cls echo Hi %USERNAME% pause >nul echo a = msgbox("Hello",4+16,"Hi bruh")>hi.vbs start hi.vbs if a = vbYes then goto hello2 else goto hello1 pause >nul :hello echo Hello1 pause >nul exit :hello2 echo Hello2 pause >nul exit But it didn't work. Please help me if you know. #HAVE A NICE DAY :-)
0debug