_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d4601
train
This is most likely caused by using PHP 8 and PHPMyAdmin < v5 either upgrade you PHPMyAdmin to 5.0 or higher or downgrade your PHP to 7 A: You can also disable notifications and warnings adding this line to config.inc.php: $cfg['SendErrorReports'] = 'never'; Source: PMA Docs A: I had the same error. phpMyAdmin 5.1.3 uses PHP 7.1 and phpMyAdmin 4.9.10 uses PHP 5.5 to 7.4 You can see that info here: https://www.phpmyadmin.net/downloads/ I have installed 4.9.5 with apache, so what I did was install PHP7.4 and php7.4-fpm, then I modified the phpMyAdmin apache config file to indicate that it should work with PHP7.4 Install php7.4-fpm: sudo apt install libapache2-mod-fcgid sudo apt install software-properties-common sudo add-apt-repository ppa:ondrej/php && sudo apt update sudo apt install php7.4-fpm sudo a2enmod actions alias proxy_fcgi fcgid sudo systemctl restart apache2 Modify phpMyAdmin apache config file: sudo nano /etc/phpmyadmin/apache.conf After Alias /phpmyadmin /usr/share/phpmyadmin paste: <FilesMatch \.php> # Apache 2.4.10+ can proxy to unix socket SetHandler "proxy:unix:/var/run/php/php7.4-fpm.sock|fcgi://localhost/" </FilesMatch> You can restart apache again and that's it. Good luck! A: Because 5.0 series is ended and 5.1 will be out next this will not be fixed. 5.1 has a new DI system and the classes mentioned in the output do not exist anymore. But you can download the latest version in development (phpMyAdmin 5.1+snapshot) and the DI errors should be gone :) https://github.com/phpmyadmin/phpmyadmin/issues/16268 A: I've got a WAMPSERVER installed and what cleared those notices for me was updating phpmyadmin to 5.1.3 that supported PHP 8
unknown
d4602
train
Your issue is order of operations -- in R, : has higher precedence than + and -. ## Demonstration: 1:5 - 1 # [1] 0 1 2 3 4 1:(5 - 1) # [1] 1 2 3 4 ## In your case ## change this: for (i in 2: length(msci)-1) ## to this: for (i in 1:(length(msci) - 1)) ## I don't see `j` defined in your code, but I assume you have the same issue and need for (j in (i + 1):n))
unknown
d4603
train
I have been able to solve this problem. what I did was to hide all divs that may be visible then toggle the dropdown I clicked to show its content. $(document).on("click", ".dropdown-toggle", function (e) { e.stopPropagation(); // hide all dropdown that may be visible var i; var dropdowns = $('.dropdown-content'); for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if ($(openDropdown).hasClass("show")) { $(openDropdown).removeClass("show"); } } // toggle the dropdown $(this).siblings().toggleClass('show'); });
unknown
d4604
train
Because you didn't do anything to stop the outermost shell from picking up the special keywords and characters ( do, for, $, etc ) that you mean to be run by xargs. xargs isn't a shell built-in; it gets the command line you want it to run for each element on stdin, from its arguments. just like any other program, if you want ; or any other sequence special to be bash in an argument, you need to somehow escape it. It seems like what you really want here, in my mind, is to invoke in a subshell a command ( your nested for loops ) for each input element. I've come up with this; it seems to to the job: echo -n "1-3,7-9" \ | sed 's/-/../g' \ | xargs -I @ \ bash -c "for i in {@}; do for j in {\$i}; do echo -n \"\$j,\"; done; done;" which gives: {1..3},{7..9}, A: Could use below shell to achieve this # Mac newline need special treatment echo "1-3,7-9" | sed -e 's/-/../g' -e $'s/,/\\\n/g' | xargs -I@ echo 'for i in {@}; do echo -n "$i,"; done' | bash 1,2,3,7,8,9,% #Linux echo "1-3,7-9" | sed -e 's/-/../g' -e 's/,/\n/g' | xargs -I@ echo 'for i in {@}; do echo -n "$i,"; done' | bash 1,2,3,7,8,9, but use this way is a little complicated maybe awk is more intuitive # awk echo "1-3,7-9,11,13-17" | awk '{n=split($0,a,","); for(i=1;i<=n;i++){m=split(a[i],a2,"-");for(j=a2[1];j<=a2[m];j++){print j}}}' | tr '\n' ',' 1,2,3,7,8,9,11,13,14,15,16,17,% A: echo -n "1-3,7-9" | perl -ne 's/-/../g;$,=",";print eval $_'
unknown
d4605
train
margin:0 auto; in your css will centre the content div horizontally, to center it vertically, youd need top:50%; margin-top:-[insert half of the content div's height here];
unknown
d4606
train
There are several ways to go about making a fly-out menu, which is what I believe you are after. The very basic approach, is to add something similar to the following to your AXML: <?xml version="1.0" encoding="utf-8"?> <flyoutmenu.FlyOutContainer xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <include layout="@layout/MenuLayout" /> <include layout="@layout/ContentLayout" /> </flyoutmenu.FlyOutContainer> Source: http://blog.neteril.org/blog/2013/04/19/fly-out-menu-xamarin-android/ Another Source: http://www.appliedcodelog.com/2016/01/navigation-drawer-using-material-design.html I hope this helps!
unknown
d4607
train
No need for lookaheads or complex patterns. Consider this: >>> re.findall('id_([a-z]+)|num([0-9]+)', s) [('john', ''), ('', '847')] When the first pattern matches, the first group will contain the match, and the second group will be empty. When the second pattern matches, the first group is empty, and the second group contains the match. Since one of the two groups will always be empty, joining them couldn't hurt. >>> [a+b for a,b in re.findall('id_([a-z]+)|num([0-9]+)', s)] ['john', '847'] A: You may use this code in Python with lookaheads: >>> s = "id_john, num847, id_000, num___" >>> print re.findall(r'(?:id_(?=[a-z]+\b)|num(?=\d+\b))([a-z\d]+)', s) ['john', '847'] RegEx Details: * *(?:: Start non-capture group * *id_(?=[a-z]+\b): Match id_ with a lookahead assertion to make sure we have [a-z]+ characters ahead followed by word boundary *|: OR *num(?=\d+\b))([a-z\d]+: Matchnum` with a lookahead assertion to make sure we have digits ahead followed by word boundary *): End non-capture group *([a-z\d]+): Match 1+ characters with lowercase letters or digits
unknown
d4608
train
It depends if you really want to make sure IsEnable gets set or not. If you can imagine scenarios in which the user doesn't want to set it, then I suppose you leave it up to them to call the base method. Otherwise, do it for them. A: The second, template-based approach is better in my opinion. It allows you to ensure that some base functionality is always called, and gives you room to add some if none is present at first without the risk of breaking any subclass. A: As soon as you make a method virtual, you are giving a derived class a chance to break your class. A responsible deriver will always ask himself "should I call the base implementation?" Guidance for this should always come from documentation. MSDN uses standard verbiage: Notes to Inheritors: When overriding Xxxxx in a derived class, be sure to call the base class's Xxxx method so that blablah happens. The C# language makes that easy with the "base" keyword. Working from the assumption that this documentation is not available or unclear, your second example would strongly discourage a deriver to call the other base class method. After all, s/he wouldn't use the standard pattern. Use this pattern only if you want to discourage the inheritor from calling a base class method. A: In the first one, where the overring class could prevent Enable from being set, I reckon Enable and Disable could potentially be misleading method names. Something like TryEnable and TryDisable would probably be more accurate implying that there are situations where you cannot enable. A third possible situation could be catered for if you took example 2 and changed it so the base class calls OnEnable before setting the flag: public void Enable() { OnEnable(); // Exceptions raised from here prevent the flag being set. IsEnable = true; } Then overriding classes could prevent the setting of the flag by raising an exception if an error were to occur. Thus error situations would prevent the flag from being changed. Just food for thought.
unknown
d4609
train
It should work. Because Glide trying to fetch image which type you specified. I just tried it and its work. it loads too late. If you wait a bit, you will see that it can be loaded. You can test it more easily if you upload a lower resolution gif file to Drive.
unknown
d4610
train
Thanks for the feedback guys. As it turns out, the toggle feature wasn't what I wanted anyway. I removed the extra $(document).ready(function(){ like @hsalama suggested, and binned the .toggle event like @François Wahl suggested. Here's how it ended up: $(document).ready(function(){ $("#picone").click(function() { $("#divone").animate( {height:300, opacity:1}, 500 ); $("#divtwo, #divthree").animate( {height:0, opacity:0}, 500 ); }); $("#pictwo").click(function() { $("#divtwo").animate( {height:300, opacity:1}, 500 ); $("#divone, #divthree").animate( {height:0, opacity:0}, 500 ); }); $("#picthree").click(function() { $("#divthree").animate( {height:300, opacity:1}, 500 ); $("#divone, #divtwo").animate( {height:0, opacity:0}, 500 ); }); }); Thanks guys :)
unknown
d4611
train
In fact, it seems my problem was caused by a misunderstanding of DocuSign's API. The note field is designed to provide a note that only appears during the signing experience, while the "emailNotification":{"emailSubject":"TEST","emailBody":"TEST"} field is designed to do what I was trying to achieve.
unknown
d4612
train
Well, think about this. list1 {1, 2, 3, 5} list2 {1, 5}. As shmosel said, what happen if your loop runs twice? It exit the loop, and the function. Ideally, you want to go through all elements on both array. BTW, I don't think your solution is working as well (you can of cause, but your code will look super ugly, probably takes O(list1.length * list2.length)). Since both lists are sorted, you can compare both element, and loop the smaller element list first. For example, using list1 and list2, compare 1 and 1, both equal, then move to 2 and 5. Then compare 2 and 5, add 2 to the list, and move 2 to 3 ONLY. Which takes O(list1.length + list2.length). A: It’s a classic pitfall. When one list runs dry, your loop stops (as it should). At this point you will still want to exhaust the other list. So after your while loop insert the logic to copy the remaining elements from the other list. Since you know one list is done and only one has elements remaining, but you don’t know which, the easy solution is just to take the remaining elements from both lists. Since both lists were sorted, you know that the remainder of the list that still has elements in it cannot contain any elements from the run-dry list, so you simply add them all to your result. All in all you will probably add two while loops after the loop you have, one for iterL1 and one for iterL2. Since each of these run in linear time, your time complexity will not get hurt.
unknown
d4613
train
This sounds like a bug. Please file an issue in the issue tracker including the smallest possible bit of SQL that triggers this. A: If you want to drop tables that have foreign key constraints on SAP HANA you either have to drop those constraints before or you have to specify the CASCADE command option. This is documented in the SAP HANA SQL reference guide. Note, that CASCADE will drop all dependent objects, not just constraints.
unknown
d4614
train
The problem was that you defined name and breed separately in each subclass of Animal. You need to make name and breed instance variables in Animal. That way, Java knows that every single Animal has a name and breed. public abstract class Animal { private String name; private String breed; public Animal(String name, String breed) { this.name = name; this.breed = breed; } public getName() { return name; } public getBreed() { return breed; } public abstract void moving(); } public class Dog extends Animal { public Dog(String name, String breed) { super(name, breed); } @Override public void moving(){ System.out.print("Walks\n"); } } public class Fish extends Animal { public Fish(String name, String breed) { super(name, breed); } @Override public void moving(){ System.out.print("Swims\n"); } } Now you can print the name and breed for any Animal, whether it's a Dog or Fish. Animal[] arr = new Animal[6]; arr[0] = new Fish("Riby", "Sea Fish"); arr[1] = new Dog("Any", "Great Dane"); arr[2] = new Fish("Ribytsa", "River fish"); arr[3] = new Dog("Jackie", "Pug"); arr[4] = new Fish("Bobi", "Mix"); arr[5] = new Dog("Ruby", "Labrador"); for (Animal a : arr) { System.out.println(a.getName() + " " + a.getBreed()); a.moving(); }
unknown
d4615
train
I fixed this problem by preloading the image manually, however I do not know if this is the CKEditor way to achieve this Code: var imageElement = editor.document.createElement('img'); imageElement.setAttribute('src', imageSource); function setWidthAndHeight() { if (this.width > 0) { imageElement.setAttribute('width', this.width); } if (this.height > 0) { imageElement.setAttribute('height', this.height); } return true; } var tempImage = new Image(); tempImage.src = imageSource; tempImage.onload = setWidthAndHeight; editor.insertElement(imageElement);
unknown
d4616
train
Essentially the same question that was posed here. The essence is that multiprocessing will convert any iterable without a __len__ method into a list. There is an open issue to add support for generators but for now, you're SOL. If your array is too big to fit into memory, consider reading it in in chunks, processing it, and dumping the results to disk in chunks. Without more context, I can't really provide a more concrete solution. UPDATE: Thanks for posting your code. My first question, is it absolutely necessary to use multiprocessing? Depending on what my_function does, you may see no benefit to using a ThreadPool as python is famously limited by the GIL so any CPU bound worker function wouldn't speed up. In this case, maybe a ProcessPool would be better. Otherwise, you are probably better off just running results = map(my_function, generator). Of course, if you don't have the memory to load the input data, it is unlikely you will have the memory to store the results. Secondly, you can improve your generator by using itertools Try: import itertools import string letters = string.ascii_lowercase cod = itertools.permutations(letters, 6) def my_function(x): return x def dump_results_to_disk(results, outfile): with open(outfile, 'w') as fp: for result in results: fp.write(str(result) + '\n') def process_in_chunks(generator, chunk_size=50): accumulator = [] chunk_number = 1 for item in generator: if len(accumulator) < chunk_size: accumulator.append(item) else: results = list(map(my_function, accumulator)) dump_results_to_disk(results, "results" + str(chunk_number) + '.txt') chunk_number += 1 accumulator = [] dump_results_to_disk(results, "results" + str(chunk_number)) process_in_chunks(cod) Obviously, change my_function() to whatever your worker function is and maybe you want to do something instead of dumping to disk. You can scale chunk_size to however many entries can fit in memory. If you don't have the disk space or the memory for the results, then there's really no way for you process the data in aggregate
unknown
d4617
train
Try below. Added varResult variable to get the filename. You may change it as you want. Used Application.GetSaveAsFilename to get the file name. Sub test() Dim pic_rng As Range Dim ShTemp As Worksheet Dim ChTemp As Chart Dim PicTemp As Picture Dim FName As String Dim varResult As Variant On Error Resume Next FName = "C:\Users\Desktop\Nutrifacts and Analysis-Save\1.png" 'displays the save file dialog varResult = Application.GetSaveAsFilename(FileFilter:="PNG (*.png), *.png") If varResult = False Then Exit Sub ' do what you want Else FName = varResult End If Application.ScreenUpdating = False ThisWorkbook.Windows(1).DisplayGridlines = False Set pic_rng = Worksheets(1).Range("A1:R31") Set ShTemp = Worksheets.Add Charts.Add ActiveChart.Location Where:=xlLocationAsObject, Name:=ShTemp.Name Set ChTemp = ActiveChart pic_rng.CopyPicture Appearance:=xlScreen, Format:=xlPicture With ThisWorkbook.Sheets(1) ActiveSheet.Shapes.Item(1).Line.Visible = msoFalse ActiveSheet.Shapes.Item(1).Width = .Range("A1:R31").Width ActiveSheet.Shapes.Item(1).Height = .Range("A1:R31").Height End With ChTemp.Paste ChTemp.Export Filename:=FName, Filtername:="png" Application.DisplayAlerts = False ShTemp.Delete Application.DisplayAlerts = True ThisWorkbook.Windows(1).DisplayGridlines = True Application.ScreenUpdating = True Set ShTemp = Nothing Set ChTemp = Nothing Set PicTemp = Nothing MsgBox ("Done.") End Sub
unknown
d4618
train
function onDrop(e) { // Get the id of the elements involved in the drag and drop event var source = $(e.draggable.element).attr('id'); var target = e.dropTarget.attr('id'); }
unknown
d4619
train
You can use std::enable_if instead of static_assert: template <std::size_t N, typename ...Args> auto function(Args&&... args) -> typename std::enable_if<N == sizeof...(Args), void>::type { ... } Update: It's also possible to use it in constructors, where N is a template argument of the class. template <std::size_t N> struct foobar { template <typename ...Args, typename = typename std::enable_if<N == sizeof...(Args), void>::type> foobar(Args&&... args) { ... } };
unknown
d4620
train
Use setCustomKey to add values to reports. FirebaseCrashlytics.instance.setCustomKey('str_key', 'hello'); See Customize your Firebase Crashlytics crash reports for details.
unknown
d4621
train
That's the difference between: virsh create and: virsh define and virsh start. The first one will create a non-persistent VM.
unknown
d4622
train
I found solution to explicit use &block as following def sidebar_link(text,link, color = nil, &block) recognized = Rails.application.routes.recognize_path(link) output = "" content_tag(:li, :class => ( "sticker sticker-color-#{color}" if color) ) do output << link_to( text, link, :class => ( 'lead' if recognized[:controller] == params[:controller] && recognized[:action] == params[:action]) ) output << capture(&block) if block_given? raw output end end
unknown
d4623
train
The error you're getting says that the meteor command is not found. This happens if your application doesn't have meteor listed as a dependency in your project's package.json file. If you add meteor as a dependency to your project, then push this change up to Heroku, that will cause meteor to get installed, and it should now have access to the meteor command. A: the problem was resolved when using this build https://github.com/AdmitHub/meteor-buildpack-horse.git and changing the package.json to { "name": "microscope", "engines": { "node": "6.9.2", "npm": "3.10.9" }, "scripts": { "start": "meteor run" }, "dependencies": { "babel-runtime": "^6.20.0", "meteor-node-stubs": "~0.2.0" } }
unknown
d4624
train
Why not just load in a script conditionally? (function() { if( window.innerWidth > 600 ) { var theScript = document.createElement('script'); theScript.type = 'text/javascript'; theScript.src = 'js/menu-collapser.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(theScript, s); } })(); Or better yet, only execute the code if the window.innerWidth > 600 ? Anyway, there are a lot of solutions you can use. A: media is not a valid attribute for <script>, check it here. So you should detect media types by manually than load the script dynamically. There is a plug-in for css media detection in javascript, you can use it. <script type="text/javascript" src="js/mediatypechecker.js"></script> $(function() { if(IsMediaType('screen') > 0 && parseInt(screen.width) < 599) { $.getSscript("js/menu-collapser.js"); } }); A: You can't do that directly using Javascript <script> tags. Media queries are used in linked CSS files or inline CSS styles. A basic example: <link rel="stylesheet" media="screen and (min-width: 900px)" href="desktop.css"/> <link rel="stylesheet" media="screen and (min-width: 571px)" href="tablet.css"/> <link rel="stylesheet" media="screen and (max-width: 570px)" href="mobile.css"/> Or directly in your stylesheets: @media screen and (max-width: 599px) { #mobile { display: block; } } However, you can use an external asset loader/media query library to do this (require.js, modernizr.js, enquire.js and others), In this case, I'm setting an example using enquire.js, as I think it's very effective and doesn't require jQuery by default: Full example 1) Include enquire.js (available here): <script type="text/javascript" src="/js/enquire.js"></script> 2) Create a load function - to load JS files: <script type="text/javascript"> // This loads JS files in the head element function loadJS(url) { // adding the script tag to the head var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; // fire the loading head.appendChild(script); } </script> 3) Fire enquire.js and listen for media query changes (both on-load and on-resize): <script type="text/javascript"> enquire.register("screen and (max-width: 599px)", { match : function() { // Load a mobile JS file loadJS('mobile.js'); } }).listen(); enquire.register("screen and (min-width: 600px) and (max-width: 899px)", { match : function() { // Load a tablet JS file loadJS('tablet.js'); //console.log('tablet loaded'); } }).listen(); enquire.register("screen and (min-width: 900px)", { match : function() { // Load a desktop JS file loadJS('desktop.js'); //console.log('desktop loaded'); } }).listen(); </script> Putting it all together Using a simple HTML page with enquire.js loaded from an external file: <html> <head> <script type="text/javascript" src="/enquire.js"></script> <script type="text/javascript"> // This loads JS files in the head element function loadJS(url) { // adding the script tag to the head var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; // fire the loading head.appendChild(script); } </script> <style> body { font-family: arial; } h1 { font-size: 50pt; } #mobile { display: none; } #tablet { display: none; } #desktop { display: none; } @media screen and (max-width: 599px) { #mobile { display: block; } } @media screen and (min-width: 600px) and (max-width: 899px) { #tablet { display: block; } } @media screen and (min-width: 900px) { #desktop { display: block; } } </style> </head> <body> <div id="desktop"> <h1>Desktop</h1> </div> <div id="tablet"> <h1>Tablet</h1> </div> <div id="mobile"> <h1>Mobile</h1> </div> <script type="text/javascript"> enquire.register("screen and (max-width: 599px)", { match : function() { // Load a JS file loadJS('mobile.js'); } }).listen(); enquire.register("screen and (min-width: 600px) and (max-width: 899px)", { match : function() { loadJS('tablet.js'); //console.log('tablet loaded'); } }).listen(); enquire.register("screen and (min-width: 900px)", { match : function() { loadJS('desktop.js'); //console.log('desktop loaded'); } }).listen(); </script> </body> </html> In addition to loading JS files, you could create a CSS loader too, which would work in the same way (conditionally), but that defeats the object of using @media in CSS. It's worth reading the usage explanations for enquire.js, as it can do a lot more than I've illustrated here. Caveat: Nothing above uses jQuery, but you could take advantage of some of the functions it offers; loading scripts for example - or executing other functions that you need to. A: If you want it to react to later resizing events (e.g. on desktop) as well, you can do it like this: <script> moby = window.matchMedia("(max-width: 500px)"); moby.addListener( moby=>{ if(moby.matches){ document.head.innerHTML+="<script src='wonderfulScreenAffectedScript.js'></script>"; } } ); </script>
unknown
d4625
train
You can't select expressions directly, you have to select them as variables. I.e., you need to do: SELECT ?z (SUM(xsd:int(?myInt)) as ?sum) This is a common mistake because some endpoints (e.g., the public DBpedia endpoint, which is running Virtuoso) do allow your original form, even though it's not legal SPARQL. As mentioned in a comment, you should group by ?zero, not by distinct(?z).
unknown
d4626
train
An output parameter can contain only a single value. You are trying to return result sets via the output variable. This is not how output parameters work. You read the result sets coming from the procedure; no need to use output variables. CREATE PROCEDURE get_initial_data() BEGIN SELECT * FROM users; SELECT * FROM employees; END Output parameters are useful in a situation where you have a procedure calling another procedure and use the output of the called procedure. Even then, you can only use single values with output parameters.
unknown
d4627
train
As hinted in a comment by @Mosha, it seems that big query supports User Defined Functions (UDF). You can input it in the UDF Editor tab on the web UI. In this case, I used something like: function flattenTogether(row, emit) { if (row.bar && row.bar.property1) { for (var i=0; i < row.bar.property1.length; i++) { emit({property1: row.bar.property1[i], name: row.bar.property2[i]}); } } }; bigquery.defineFunction( 'flattenBar', ['bar.property1', 'bar.property2'], [{'name': 'property1', 'type': 'string'}, {'name': 'property2', 'type': 'string'}], flattenTogether); And then the query looked like: SELECT property1, property2, FROM flattenBar( SELECT bar.property1, bar.property2, FROM [dataset.foo] WHERE baz = 'baz') A: Since baz is not repeated, you can simply filter on it in WHERE clause without any flattening: SELECT bar.property1, bar.property2 FROM t WHERE baz = 'baz'
unknown
d4628
train
Progress bar's progress value is between 0.0 and 1.0, your code sets it in the increments of 15.0, which is out of range. Your increment should be 0.15, not 15.0. A: Progress is a value between 0.0 and 1.0. Edit: Did you try to call [myView setNeedsDisplay];? 2nd Edit: Maybe there is one confusion: viewDidLoad is called right before you are presenting the view. Therefore in the code you have shown here incrementaProgres: is called before viewDidLoad.
unknown
d4629
train
Three things. First, you need begin and end for your always block. Second, why are you doing count <= ~count when the count hits the max? Shouldn't you just set it back to 0? Third, you can't give the internal count register the same name as the count output. You will need to call one of them something else. Actually, why do you want to output count? If this is a clock divider, you want to output another clock, right? The following should work. module clk_div( clk, rst, outclk); parameter count_width=27; parameter count_max=25000000; reg [count_width-1:0] count; input clk,rst; output outclk; reg intern_clk; assign outclk = intern_clk; initial begin count=0; intern_clk=1'b0; end always @(posedge clk) begin if (rst) count <= 0; else if (count == count_max) begin count <= 0; intern_clk <= !intern_clk; end else count <= count + 1'b1; end endmodule But it seems like you are trying to divide the clock down to 1 Hz. That's quite a lot. I recommend you use a PLL instead of making your own clock divider. Since you mention a 50 MHz clock, I'm guessing you are using an Altera FPGA? If so, open up the MegaWizard plugin manager and create a PLL.
unknown
d4630
train
The problem is that you want to make your subscription = to the getProducts() call. ngOnInit() { this.subscription = this._productListService.getProducts() // subscription created here .subscribe( products => this.products = products, // value applied to products here error => this.errorMessage = <any>error); } A: The value of this.products is assigned in subscribe(). You can ignore the returned subscription object as in code snippet below. ngOnInit() { this._productListService.getProducts() .subscribe( products => this.products = products, error => this.errorMessage = <any>error); }
unknown
d4631
train
Just use if condition, inside for loop to check if it has question or not. it will work for you. <script> question_block(); function question_block() { $.ajax({ url: '@Url.Action("QuestionBlocks", "Home")', contentType: 'application/json; charset=utf-8', type: 'GET', dataType: 'json', processData: false, success: function (result) { var email = result; for (var i = 0; i <= email.length - 1; i++) { var question = ""; for (var j = 1; j <= 10; j++) { var getQ = email[i]["Question" + j]; if (getQ) { question += '<div class="activeQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + getQ + '</div>'; } } if (question != "") { $("#questions").append(question); } } } }); } </script> A: You can try like this !!! <script> $(document).ready(function() { question_block(); }); function question_block() { $.ajax({ url: '@Url.Action("QuestionBlocks", "Interwier")', contentType: 'application/json; charset=utf-8', type: 'GET', dataType: 'json', processData: false, success: function(result) { var email = result; for (var i = 0; i <= email.length - 1; i++) { var question=''; var Question1=''; var Question2=''; var Question3=''; var Question4=''; var Question5=''; var Question6=''; var Question7=''; var Question8=''; var Question9=''; email[i].Question1==''?Question1='':Question1='<div class="activeQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' +email[i].Question1 + '</div>' question=question+Question1 //Do this for all question $("#questions").append(question); //$('.hiddenQue:empty').hide();
unknown
d4632
train
The first problem is your while: while(buffer[++i] == '+') So you've found your +, but in the while you first increase the position and then test whether the value is still +. That fails if you only have one + (and if you have several, the first is not overwritten). Instead, replace it with: for ( ; (buffer[i] == '+') && (i < lSize) ; i++) The next problem is that after fread, the file position is at the end. Your call to fwrite will thus append the modified buffer. To actually overwrite the file you first need to call rewind(pFile); again. A final note on fread/fwrite: you read and write lSize items, each 1 byte in size. That's pretty slow (try it with a one megabyte file). Instead you likely want the opposite: result = fread(buffer, lSize, 1, pFile); Note that result will then merely have 1 on success. The same applies for fwrite. A: Note that you would be trying to write the modified contents at the end of the file. Besides, switching between read and write operations need certain function calls in between to switch the operation mode. Try adding fseek( pFile, 0, SEEK_SET ); right before doing fwrite. Note that there may still be something wrong A: You open the file in rb (for reading), then write to it... I am not sure it will do what you want.
unknown
d4633
train
.dropdown-menu has min-width: 160px; and min-width overrides width so you can not change width you can use min-width instead of width. .dropdown-menu { min-width: 60px !important; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" /> <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li><a href="#">Action</a> </li> <li><a href="#">Another</a> </li> <li><a href="#">Something</a> </li> <li><a href="#">Separated</a> </li> </ul> </div> It works. You should call bootstrap lib and jquery. Please, read bootstrap documentation. Jsfiddle A: Give a ID for the div and specify the min-width in the css as follows: .dropdown #mydiv{ min-width:60px; } Note: Do NOT use '!important'. For more information check out this great post by Chris Coyier : Specifics on CSS Specificity
unknown
d4634
train
You have a number of issues. Don't #include .cpp files. Your << operator should be declared as a free function not a member function, declare it as a friend instead: class Board{ ... friend std::ostream& operator<<(std::ostream& os, const Board& bd); ... } Your operator uses some member variables from this rather than bd, the correct implementation is: std::ostream& operator<<(std::ostream& os, const Board& bd){ for(int V = bd.amt_rows-1; V>=0; --V){ for(int I = 0; I<bd.amt_cols-1;++I){ os << bd.ptr_columns[I][V] << " "; } os << "\n"; } return os; }
unknown
d4635
train
You can create a function for this and get exactly what you want implementing conditions: create or replace function some_func(input_author_id integer, input_date date) returns setof posts as $$ declare selected_posts posts%rowtype; begin select * from posts p into selected_posts where p.author_id = input_author_id and p.publish_date > input_date; if not found then return query select * from posts p where p.author_id = input_author_id order by publish_date desc limit 1; else return query select * from posts p where p.author_id = input_author_id and p.publish_date > input_date; end if; end $$ language plpgsql; After that, just pass the values of the parameters you want: select * from some_func(2,'2021-07-01'); And this will give you the below result: author_id post_id publish_date 2 432 2021-06-22 A: Possible with a single query: WITH cte AS ( SELECT * FROM posts WHERE author_id = 1 AND publish_date > '2021-07-01' ORDER BY publish_date ) TABLE cte UNION ALL ( -- parentheses required SELECT * FROM posts WHERE NOT EXISTS (SELECT FROM cte) AND author_id = 1 AND publish_date <= '2021-07-01' ORDER BY publish_date DESC NULLS LAST LIMIT 1 ); Related: * *Combining 3 SELECT statements to output 1 table Or with a PL/pgSQL function: CREATE OR REPLACE FUNCTION my_func(_author_id int, _publish_date date) RETURNS SETOF posts LANGUAGE plpgsql aS $$ BEGIN RETURN QUERY SELECT * FROM posts WHERE author_id = _author_id AND publish_date > _publish_date ORDER BY publish_date; IF NOT FOUND THEN RETURN QUERY SELECT * FROM posts WHERE author_id = _author_id AND publish_date <= _publish_date ORDER BY publish_date DESC NULLS LAST LIMIT 1; END IF; END $func$; Call: SELECT * FROM my_func(2,'2021-07-01'); Related: * *PLpgSQL function not returning matching titles *How to return result of a SELECT inside a function in PostgreSQL?
unknown
d4636
train
can you change query into this? sql = "INSERT INTO Customer (FNAME, LNAME, AGE, LICNUM, STATE, CAR_TYPE, RENTDATE, RETURNDATE, TOTAL, PAYTYPE, RETURNED) VALUES('"+f_name.getText()+"','"+l_name.getText()+"','"+Age+"','"+liscense_num.getText()+"','"+issuing.getText()+"','"+car_select.getToolkit()+"','"+rental.getText()+"','"+return_d.getText()+"','"+total.getText()+"','"+button_val.getText()+"','true') "; A: --Not an answer: java.sql.SQLSyntaxErrorException: Syntax error: Encountered "[" at line 1, column 160. at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source) at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source) at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source) at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source) at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source) at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source) at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source) at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source) at Auto.actionPerformed(Auto.java:381) at java.awt.Button.processActionEvent(Unknown Source) at java.awt.Button.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$500(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) Caused by: ERROR 42X01: Syntax error: Encountered "[" at line 1, column 160. at org.apache.derby.iapi.error.StandardException.newException(Unknown Source) at org.apache.derby.iapi.error.StandardException.newException(Unknown Source) at org.apache.derby.impl.sql.compile.ParserImpl.parseStatementOrSearchCondition(Unknown Source) at org.apache.derby.impl.sql.compile.ParserImpl.parseStatement(Unknown Source) at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source) at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source) at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source) ... 25 more
unknown
d4637
train
Because the thread switching infrastructure is unusable at that point. When servicing an interrupt, only stuff of higher priority can execute - See the Intel Software Developer's Manual on interrupt, task and processor priority. If you did allow another thread to execute (which you imply in your question that it would be easy to do), you wouldn't be able to let it do anything - if it caused a page fault, you'd have to use services in the kernel that are unusable while the interrupt is being serviced (see below for why). Typically, your only goal in an interrupt routine is to get the device to stop interrupting and queue something at a lower interrupt level (in unix this is typically a non-interrupt level, but for Windows, it's dispatch, apc or passive level) to do the heavy lifting where you have access to more features of the kernel/os. See - Implementing a handler. It's a property of how O/S's have to work, not something inherent in Linux. An interrupt routine can execute at any point so the state of what you interrupted is inconsistent. If you interrupted the thread scheduling code, its state is inconsistent so you can't be sure you can "sleep" and switch threads. Even if you protect the thread switching code from being interrupted, thread switching is a very high level feature of the O/S and if you protected everything it relies on, an interrupt becomes more of a suggestion than the imperative implied by its name. A: So what stops the scehduler from putting interrupt context to sleep and taking next schedulable process and passing it the control? The problem is that the interrupt context is not a process, and therefore cannot be put to sleep. When an interrupt occurs, the processor saves the registers onto the stack and jumps to the start of the interrupt service routine. This means that when the interrupt handler is running, it is running in the context of the process that was executing when the interrupt occurred. The interrupt is executing on that process's stack, and when the interrupt handler completes, that process will resume executing. If you tried to sleep or block inside an interrupt handler, you would wind up not only stopping the interrupt handler, but also the process it interrupted. This could be dangerous, as the interrupt handler has no way of knowing what the interrupted process was doing, or even if it is safe for that process to be suspended. A simple scenario where things could go wrong would be a deadlock between the interrupt handler and the process it interrupts. * *Process1 enters kernel mode. *Process1 acquires LockA. *Interrupt occurs. *ISR starts executing using Process1's stack. *ISR tries to acquire LockA. *ISR calls sleep to wait for LockA to be released. At this point, you have a deadlock. Process1 can't resume execution until the ISR is done with its stack. But the ISR is blocked waiting for Process1 to release LockA. A: I think it's a design idea. Sure, you can design a system that you can sleep in interrupt, but except to make to the system hard to comprehend and complicated(many many situation you have to take into account), that's does not help anything. So from a design view, declare interrupt handler as can not sleep is very clear and easy to implement. From Robert Love (a kernel hacker): http://permalink.gmane.org/gmane.linux.kernel.kernelnewbies/1791 You cannot sleep in an interrupt handler because interrupts do not have a backing process context, and thus there is nothing to reschedule back into. In other words, interrupt handlers are not associated with a task, so there is nothing to "put to sleep" and (more importantly) "nothing to wake up". They must run atomically. This is not unlike other operating systems. In most operating systems, interrupts are not threaded. Bottom halves often are, however. The reason the page fault handler can sleep is that it is invoked only by code that is running in process context. Because the kernel's own memory is not pagable, only user-space memory accesses can result in a page fault. Thus, only a few certain places (such as calls to copy_{to,from}_user()) can cause a page fault within the kernel. Those places must all be made by code that can sleep (i.e., process context, no locks, et cetera). A: So what stops the scehduler from putting interrupt context to sleep and taking next schedulable process and passing it the control? Scheduling happens on timer interrupts. The basic rule is that only one interrupt can be open at a time, so if you go to sleep in the "got data from device X" interrupt, the timer interrupt cannot run to schedule it out. Interrupts also happen many times and overlap. If you put the "got data" interrupt to sleep, and then get more data, what happens? It's confusing (and fragile) enough that the catch-all rule is: no sleeping in interrupts. You will do it wrong. A: Disallowing an interrupt handler to block is a design choice. When some data is on the device, the interrupt handler intercepts the current process, prepares the transfer of the data and enables the interrupt; before the handler enables the current interrupt, the device has to hang. We want keep our I/O busy and our system responsive, then we had better not block the interrupt handler. I don't think the "unstable states" are an essential reason. Processes, no matter they are in user-mode or kernel-mode, should be aware that they may be interrupted by interrupts. If some kernel-mode data structure will be accessed by both interrupt handler and the current process, and race condition exists, then the current process should disable local interrupts, and moreover for multi-processor architectures, spinlocks should be used to during the critical sections. I also don't think if the interrupt handler were blocked, it cannot be waken up. When we say "block", basically it means that the blocked process is waiting for some event/resource, so it links itself into some wait-queue for that event/resource. Whenever the resource is released, the releasing process is responsible for waking up the waiting process(es). However, the really annoying thing is that the blocked process can do nothing during the blocking time; it did nothing wrong for this punishment, which is unfair. And nobody could surely predict the blocking time, so the innocent process has to wait for unclear reason and for unlimited time. A: Even if you could put an ISR to sleep, you wouldn't want to do it. You want your ISRs to be as fast as possible to reduce the risk of missing subsequent interrupts. A: The linux kernel has two ways to allocate interrupt stack. One is on the kernel stack of the interrupted process, the other is a dedicated interrupt stack per CPU. If the interrupt context is saved on the dedicated interrupt stack per CPU, then indeed the interrupt context is completely not associated with any process. The "current" macro will produce an invalid pointer to current running process, since the "current" macro with some architecture are computed with the stack pointer. The stack pointer in the interrupt context may point to the dedicated interrupt stack, not the kernel stack of some process. A: By nature, the question is whether in interrupt handler you can get a valid "current" (address to the current process task_structure), if yes, it's possible to modify the content there accordingly to make it into "sleep" state, which can be back by scheduler later if the state get changed somehow. The answer may be hardware-dependent. But in ARM, it's impossible since 'current' is irrelevant to process under interrupt mode. See the code below: #linux/arch/arm/include/asm/thread_info.h 94 static inline struct thread_info *current_thread_info(void) 95 { 96 register unsigned long sp asm ("sp"); 97 return (struct thread_info *)(sp & ~(THREAD_SIZE - 1)); 98 } sp in USER mode and SVC mode are the "same" ("same" here not mean they're equal, instead, user mode's sp point to user space stack, while svc mode's sp r13_svc point to the kernel stack, where the user process's task_structure was updated at previous task switch, When a system call occurs, the process enter kernel space again, when the sp (sp_svc) is still not changed, these 2 sp are associated with each other, in this sense, they're 'same'), So under SVC mode, kernel code can get the valid 'current'. But under other privileged modes, say interrupt mode, sp is 'different', point to dedicated address defined in cpu_init(). The 'current' calculated under these mode will be irrelevant to the interrupted process, accessing it will result in unexpected behaviors. That's why it's always said that system call can sleep but interrupt handler can't, system call works on process context but interrupt not. A: High-level interrupt handlers mask the operations of all lower-priority interrupts, including those of the system timer interrupt. Consequently, the interrupt handler must avoid involving itself in an activity that might cause it to sleep. If the handler sleeps, then the system may hang because the timer is masked and incapable of scheduling the sleeping thread. Does this make sense? A: If a higher-level interrupt routine gets to the point where the next thing it must do has to happen after a period of time, then it needs to put a request into the timer queue, asking that another interrupt routine be run (at lower priority level) some time later. When that interrupt routine runs, it would then raise priority level back to the level of the original interrupt routine, and continue execution. This has the same effect as a sleep. A: It is just a design/implementation choices in Linux OS. The advantage of this design is simple, but it may not be good for real time OS requirements. Other OSes have other designs/implementations. For example, in Solaris, the interrupts could have different priorities, that allows most of devices interrupts are invoked in interrupt threads. The interrupt threads allows sleep because each of interrupt threads has separate stack in the context of the thread. The interrupt threads design is good for real time threads which should have higher priorities than interrupts.
unknown
d4638
train
You cannot have non-unique values with a unique index. But you can have non-unique values with a unique constraint that is enforced by a non-unique index. Even if you initially created a non-unique index, the drop index and enable syntax will try to recreate a unique index unless you provide more details in the using index section. For example: SQL> create table my_table(my_column number, 2 constraint my_constraint unique (my_column)); Table created. SQL> alter table my_table disable constraint my_constraint drop index; Table altered. SQL> insert into my_table select 1 from dual union all select 1 from dual; 2 rows created. SQL> alter table my_table enable novalidate constraint my_constraint; alter table my_table enable novalidate constraint my_constraint * ERROR at line 1: ORA-02299: cannot validate (USER.MY_CONSTRAINT) - duplicate keys found SQL> alter table my_table enable novalidate constraint my_constraint 2 using index (create index my_index on my_table(my_column)); Table altered. SQL> --The constraint is enforced, even though other rows violate it. SQL> insert into my_table values(1); insert into my_table values(1) * ERROR at line 1: ORA-00001: unique constraint (USER.MY_CONSTRAINT) violated A: When you inserted the rows into your table you violated the constraint, looks like it is a unique constraint based on the error message "duplicate keys found" check what columns the constraint is based on, and then do a quick query like the following to see if you have any rows with duplicates (columna and columnb are the columns in your unique constraint) SELECT columna, columnb COUNT() FROM mytable HAVING COUNT() > 1 You won't be able to enable the unique constraint until all the rows in the table meet the rules of the constraint.
unknown
d4639
train
You should read the documentation on the Requests Dialog. When you use the Facebook Javascript SDK to call the dialog, you will recieve a callback as soon as the dialog has closed. This callback will contain details about the users actions within the dialog. Taken from the documentation : FB.ui({method: 'apprequests', message: 'My Great Request' }, function requestCallback(response) { // Handle callback here }); In the callback's response argument there is details about the request_id and who the request was sent to : Object request: "REQUEST_ID" to: Array[2] 0: "FB_ID1" 1: "FB_ID2" 2: "FB_ID3" ... Unless there is a specific and valid reason not to use facebook's dialogs, I recommend staying with the features facebook has given us. As soon as you start using 3rd party plugins to "mimic" facebook behavior, you are dependent on those developers to update their code when facebook makes changes.
unknown
d4640
train
try out using linq way like this var matched = from table1 in dt1.AsEnumerable() join table2 in dt2.AsEnumerable() on table1.Field<int>("ID") equals table2.Field<int>("ID") where table1.Field<string>("Data") == table2.Field<string>("Data") select table1; A: If you want to find duplicates, you can try this var result = table1.AsEnumerable().Intersect(table2.AsEnumerable()).Select(x => x); If you want to eliminate duplicates from union, you can try this var result = table1.AsEnumerable().Union(table2.AsEnumerable()).Select(x => x);
unknown
d4641
train
The simplest approach is just to read the string as a JSON string. unescaped_str = JSON.load("\"#{str}\"") A: That string is escaped twice. There are a few ways to unescape it. The easiest is eval, though it is not safe if you don't trust the input. However if you're sure this is a string encoded by ruby: print eval(str) Safer: print YAML.load(%Q(---\n"#{str}"\n)) If it was a string escaped by javascript: print JSON.load(%Q("#{str}")) See also Best way to escape and unescape strings in Ruby?
unknown
d4642
train
datetime.now() returns a local datetime, while datetime.utcfromtimestamp() returns a UTC datetime. So of course you will have the difference of your timezone accounted for in your calculation. In order to avoid that, either always use local time, or always use universal time. >>> (datetime.datetime.utcnow() - datetime.datetime.utcfromtimestamp(0)).total_seconds() - time.time() 0.0 A: Epoch is in GMT, so the number of seconds that have passed since Epoch is the same no matter what timezone you are in. Hence, the correct answer to your question: is there any way to get number of seconds passed (w.r.t localtime) since epoch from time module? is >>> import time >>> time.time() 1442482454.94842
unknown
d4643
train
Simple loop through the objects to convert string to bool: yourArray.forEach(x => x.isSingle = x.isSingle === 'true'); A: Just Iterate over the array and replace the value as per your requirement like this - var obj = [ { "noFolder": "AW343", "type": "T7", "creationDate": "22/05/2017", "isSingle": "true" }, { "noFolder": "AW35", "type": "T34", "creationDate": "09/05/2017", "isSingle": "false" }, { "noFolder": "ASW3", "type": "T3", "creationDate": "05/07/2017", "isSingle": "true" }, { "noFolder": "BG5", "type": "T1", "creationDate": "22/12/2018", "isSingle": "false" } ] obj.map((e) => { e.isSingle == "true" ? e.isSingle = true : e.isSingle = false }); A: Using reduce method. let updated_array = array.reduce(function(acc, elem) { acc.push(Object.assign({}, elem, { isSingle: (elem['isSingle'] == true ? true : false) })); return acc; }, []);
unknown
d4644
train
img { border: solid 10px transparent; } img:hover { border-color: green; } A: img:hover { border: solid 2px red; margin: -2px; } Seems to work for me (Safari 6.0.5). No added space since the border is drawn on the 'inside' of the img. A: The problem is that you're adding a border to the element that takes up space - the other elements on the page have to move to make room for it. The solution is to add a border that matches the background, and then just change the color or styling on hover. Another possibility is to make the box larger than you originally intended, and then resize it to fit the border you're adding.
unknown
d4645
train
It seems piecewise does not support vector-valued functions. Possible workaround: define each coordinate as a piecewise function. sage: gamma(t) = (t, ....: piecewise([(t <= 0, 0), (t > 0, exp(-t^-2))]), ....: piecewise([(t < 0, exp(-t^-2)), (t > 0, 0)])) ....: sage: gamma t |--> (t, piecewise(t|-->0 on (-oo, 0], t|-->e^(-1/t^2) on (0, +oo); t), piecewise(t|-->e^(-1/t^2) on (-oo, 0), t|-->0 on (0, +oo); t)) sage: parametric_plot(gamma, (t, -1, 1)) Launched html viewer for Graphics3d Object
unknown
d4646
train
Try to use the following code for getting the image in all APIs - public void takePicture() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); file = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", getOutputMediaFile()); intent.putExtra(MediaStore.EXTRA_OUTPUT, file); startActivityForResult(intent, TAKE_IMAGE_REQUEST); } private File getOutputMediaFile() { File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), getString(R.string.app_folder_name)); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { return null; } } return new File(mediaStorageDir.getPath() + File.separator + PROFILE_PIC + getString(R.string.pic_type)); } And on your onActivityResult - @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case TAKE_IMAGE_REQUEST: if (resultCode == RESULT_OK) { imageView.setImageURI(file); } break; default: break; } } Also, you need to define the Provider in your Manifest.xml file - <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"/> </provider> And finally the provider_paths.xml will be as follows - <?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="external_files" path="."/> </paths> Let me know in case you need any clarification.
unknown
d4647
train
In the 'old' way of NuGet (which you seem to use, check this for info on new vs old) this was possible by using the command in the .nuget\NuGet.targets file you mention. If you change the line with PackageOutputDir to below it will work. <PackageOutputDir Condition="$(PackageOutputDir) == ''">C:\LocalPackageRepository</PackageOutputDir> Even better would be to set a property on the PropertyGroup in the .csproj like this: <PackageOutputDir>C:\LocalPackageRepository</PackageOutputDir> In the new way of NuGet you would add this key to the NuGet.config file: <add key="repositoryPath" value="C:\LocalPackageRepository" /> A: Not sure why the global config settings didn't work for me, but adding below solution solved my problem: * *Create an environment variable under user variables: Variable name: MyNugetsOutput Variable value: D:\myteam\teampackages * *Then add below settings to .csproj file: <Target Name="CopyPackage" AfterTargets="Pack"> <Copy SourceFiles="$(OutputPath)\$(PackageId).$(PackageVersion).nupkg" DestinationFolder="$(MyNugetsOutput)\$(PackageId).$(PackageVersion).nupkg" /> </Target> reference: Target build order Update Currently I'm using below code, it is simpler but it copies all .nupkg files to the "Local" path <Target Name="AfterPack" AfterTargets="Pack"> <Exec Command="dotnet nuget push $(PackageOutputPath)*.nupkg --source Local" /> </Target> A: You cannot do this from the .nuspec file. You can create a NuGet.Config file and define a global packages directory for all solutions: <configuration> <config> <add key="repositoryPath" value="C:\myteam\teampackages" /> </config> ... </configuration> This is done outside the .nupkg file and stored either under your profile or in a subdirectory which is a parent to all the directories containing your solutions. See the NuGet documentation for more details on this feature.
unknown
d4648
train
I wrote a wrapper for ios5, disabled ARC, and rewrote a few vars definitions. It is all working now. :D I might write a bit more about this problem if I find the time.
unknown
d4649
train
See a working demo of the following code here. I've modified your initMenu function to add the open_menu class to the appropriate accordion (and added a CSS class to indicate that it was added by changing the background to green): function initMenu() { // SNIP ... $('#menu li a').click(function() { // SNIP ... if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) { $('#menu ul:visible').slideUp('normal') .siblings('a').removeClass('open_menu'); checkElement.slideDown('normal') .siblings('a').addClass('open_menu'); return false; } }); } I then created a function to be called after initMenu that will trigger a click on the accordion with the same rel as the id of the currently selected item: function showCurrentTab() { var curId = $('.tabcontent:visible')[0].id, $curLink = $('a[rel="'+curId+'"]'); $curLink.closest('ul') .parent('li') .children('a').click(); } To figure out what's going on here, see the API docs for closest, parent and children and relate that to your HTML structure.
unknown
d4650
train
If it doesn't return a valid body then take a look at the HTTP response header. I guess you are violating Nominatim's usage policy. Do you provide a valid HTTP user agent?
unknown
d4651
train
That's because there's no data-detail property on HTML element. Here is a quick explanation for .data(), .prop() and .attr() : DOM element is an object which has methods, and properties (from the DOM) and attributes(from the rendered HTML). Some of those properties get their initial value by the attributes id->id, class->className, title->title, style->style etc. Consider this element: <input type="checkbox" checked data-detail="somedata" > The result of the following would be: $('input').prop('id'); // => " "-empty string, property id exist on the element (defined by DOM) , but is not set. $('input').attr('id');// => undefined - doesn't exist. If you do the following: $('input').attr('id',"someID"); $('input').prop('id'); // => "someID" $('input').attr('id'); // => "someID" And also: $('input').prop('id',"someOtherID"); $('input').prop('id');// => "someOtherID" $('input').attr('id');// => "someOtherID" So, some attributes and properties have 1:1 mapping. (change of the attr result change of the prop and vice versa). Consider the following: <input type="text" data-detail="somedata" value="someValue"> $('input').prop('value'); // => "someValue" $('input').val(); // => "someValue" $('input').attr('value'); // => "someValue" And if you do: $('input').prop('value','newVal'); // or $('input').val('newVal'); $('input').prop('value'); // => "newVal" -value of the property $('input').val(); // => "newVal" -value of the property $('input').attr('value'); // => "someValue" -value of the attr didn't change, since in this case it is not 1:1 mapping (change of the prop value doesn't reflect to the attribute value). Case with the .data() 1) How to get: - Have in mind that attribute name is data-* and property name is dataset, so: <input type="checkbox" data-detail="somedata" >   $('input')[0].dataset; //=> [object DOMStringMap] { detail: "somedata"} $('input')[0].dataset.detail; // => "somedata" $('input').prop('dataset'); //=>[object DOMStringMap] { detail: "somedata"} $('input').prop('dataset').detail; // => "somedata" $('input').data('detail'); // => "somedata" $('input').attr('data-detail'); // => "somedata" 2) How to set: I) $('input').prop('dataset').detail='newData'; $('input').prop('dataset'); //=> [object DOMStringMap] { detail: "newData"} $('input').prop('dataset').detail; // => "newData" $('input').attr('data-detail'); // => "newData" $('input').data('detail'); // => "newData" II) $('input').attr('data-detail','newData'); $('input').prop('dataset'); //=> [object DOMStringMap] { detail: "newData"} $('input').prop('dataset').detail; // => "newData" $('input').attr('data-detail'); // => "newData" $('input').data('detail'); // => "newData" So you can see that here is 1:1 mapping, attr change reflects prop and vice versa. But check the third way: III) $('input').data('detail','newData'); $('input').prop('dataset'); // => [object DOMStringMap] { detail: "somedata"} $('input').prop('dataset').detail; // => "somedata" $('input').attr('data-detail'); // => "somedata" $('input').data('detail'); // => "newData" <-----****** So, what is happening up here? $(elem).data(key, value) does not change the HTML5 data-* attributes of the element. It stores its values in $.cache internally. So for getting data-* you would never go wrong with .data() : $(".saveBtn").on("click", function() { var saveBtn = $(this); var detail = saveBtn.data("detail"); var relevantInput = saveBtn.parent().next(); var value = relevantInput.prop("value"); });
unknown
d4652
train
Why do you need special property? You can create ListView with ComboBox quite easily: ObservableList<WindowsItem> windowsItems = FXCollections.observableArrayList(); ObservableList<WindowsItem> data = FXCollections.observableArrayList(); final ListView<WindowsItem> listView = new ListView<>(data); listView.setEditable(true); listView.setItems(data); listView.setCellFactory(ComboBoxListCell.forListView(windowsItems));
unknown
d4653
train
I copyed you example and for me it works: <?php $array = array( 'php' => array( 36, 51, 116, 171, 215, 219, 229, 247, 316, ), 'java' => array( 14, 16, 19, 24, 25, 26, 29, 31, 33, 34, 35, 36, 37, 40, 45, 49, 51, ), 'ajax' => array( 91, 110, 113, 172, ), ); $intersected_array = call_user_func_array('array_intersect',$array); print_r($intersected_array); // RESULT: "Array ( ) " Please copy exactly this code and tell me your output.
unknown
d4654
train
If you want to use file system as a backend, simply try this settings: spring.profiles.active=native spring.cloud.config.server.native.searchLocations: file:///full/path/to/resources See also this documentation A: I'm embarrassed to write this but intellij wouldn't clean the build. I ran the gradle task and it all worked out.
unknown
d4655
train
You can handle it from C# or SQL like this : C# if(EndDate < DateTime.Now.Date) // Assuming EndDate is already defined in your class { using(SqlConnection sqlCon = new SqlConnection(sqlCon.ConnectionString) ) using(SqlCommand sqlCmd = new SqlCommand("DeleteByDate", sqlCon)) { sqlCon.Open(); sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Parameters.Add("@AdvID", SqlDbType.Int); sqlCmd.Parameters["@AdvID"].Value = AdvID //Assuming it's already defined; sqlCmd.ExecuteNonQuery(); } } SQL : ALTER PROC [dbo].[DeleteByDate] @AdvID int AS BEGIN DECLARE @CurrentDate DATE = GETDATE() -- to get current date -- Assuming that Advertisement table has the column EndDate IF EXISTS (SELECT * FROM Advertisement a WHERE a.EndDate < @CurrentDate ) BEGIN UPDATE a SET a.Status = 0 FROM Advertisement a WHERE a.AdvID = @AdvID END END If you go with C#, it won't fire the sp until the condition is met, but in SQL, it'll make your C# fires the sp, and the sp will check the condition every time your code runs it. So, it depends in your application structure, is it application first, or database first, which comes first would be your way to go.
unknown
d4656
train
Use the following measure: YoY = [AVG_SALE]/CALCULATE([AVG_SALE];SAMEPERIODLASTYEAR('yourTable'[Year]))-1 If you want to treat the possible errors (maybe you miss some years in your data, or you've got no sales on specific year): YoY = IFERROR([AVG_SALE]/CALCULATE([AVG_SALE];SAMEPERIODLASTYEAR('tableName'[Year]))-1;BLANK()) Remember to replace tableName with the name of your table!
unknown
d4657
train
The problem with singletons is that they make it harder to mock and unit test your application. You should decouple your dependencies; and if you do somehow need a singleton (which should be very, very rare) then consider having the singleton implement an interface that you can mock for testing purposes. A: Whenever I'm tempted to use a singleton, I re-read Global Variables are Bad and consider whether the convenience is really worth putting up with this (slightly) paraphrased list of problems: * *Non-locality of methods and variables *No access control or constraint checking *Implicit coupling *Concurrency issues *Namespace pollution *Memory allocation issues *Unduly Complicated Testing A: Singletons are basically global variables, and it's a bad idea to create a global variable just to avoid passing things around. Then again, often the right thing to do is simply to pass objects around from one class to another. The trick is figuring out the minimum amount of data you can pass to minimize the coupling. This is where well-designed classes are important. For example, you rarely need to pass an NSManagedObjectContext because you can get it from any NSManagedObject. Now, let me address the specific case of your expensive-to-create objects. You might try pooling those objects instead of creating them every time one is needed. Database access is a good example of this. Rather than allocating a database connection every time you ask for one, you grab one out of a cache. Of course, when the cache is empty, you need to allocate one. And, for memory reasons, you should be willing and able to empty out the cache when the system asks you to. That the object is expensive to create shouldn't matter to the user. That's an implementation detail, but it's one that you can design around. You do have to be careful because only objects that don't have mutable state can be handled this way, so you may have to rethink the design of your classes if you want to go this route. A: Why don't you just make your app delegate a factory for the expensive-to-create instances? Each time a view controller needs an instance of the helper class it ask the appDelegate for it. A: Personally, I usually using singleton. In my opinion, it make the code cleaner... And I am sure that class instance is unique. I use it to have single point access to resource Edit : Seems I'm wrong ! what about the flexible implementation ? static Singleton *sharedSingleton = nil; + (Singleton*)sharedManager { if (sharedSingleton == nil) { sharedSingleton = [[super alloc] init]; } return sharedSingleton; }
unknown
d4658
train
build-sql will just create the SQL files; insert-sql would overwrite the database. When I do table adding like this, I have just looked in the generated SQL in data/sql and added the tables by hand. s2 has migrations built in, IIRC. For s1.4 check out http://www.symfony-project.org/plugins/sfPropelMigrationsLightPlugin - just found via google, I've never used it.
unknown
d4659
train
You can use HAL_FLASH_Program with TYPEPROGRAM_BYTE to write a single 1-byte char. If your data is a bit long (a struct, a string...), you can also write the bulk with TYPEPROGRAM_WORD, or even TYPEPROGRAM_DOUBLEWORD (8 bytes at a time), and then either complete with single bytes as needed or pad the excess with zeros. That would certainly be a bit faster, but maybe it's not significant for you.
unknown
d4660
train
When you are generating a database first DbContext, you get two collections to add against (if you have two relationships setup - one for each key). For example, you should then see: * *us.User_Profile.Add() *us.User_Profile2.Add() You would then add the profile to both collections to have both foreign keys updated properly when persisting. Entity Framework keeps track of the fact you have added the same object reference to two collections, and will save it properly. Note: The other option is to save the user, and then put the ID you get back on both foreign key properties, but this may be less efficient.
unknown
d4661
train
If threaded development and service development are both totally new then I think you will struggle to implement this in a useful way. Even so... Scheduler-type applications are best run as services, because otherwise you need the user to be logged in to be running the application. Services run independently of the user being logged in. Because of this, however, services don't have a user interface so your GUI needs to package up the details of schedule into a configuration file somewhere, then signal the service to re-load that configuration file so that the service will then know what to do and when to do it. The service will normally spawn a worker thread to do pretty much everything, and that worker thread needs to be able to respond to the service being shut down (read up on AutoResetEvent to see how this might be done across threads). The thread will then wait until either an event or for the appropriate time to arrive and then do whatever it has to do. None of this is actually complicated, but I suggest you do some digging into multithreaded programming first. A: I agree with ColinM, Services are best for the Scheduler Type of application. You have to combine the Services with application to run your code at scheduled intervals. See the article for more details - http://msdn.microsoft.com/en-us/magazine/cc163821.aspx
unknown
d4662
train
Theres a few steps you'll need to follow in order to update your application on google play store, at first Version your application : http://developer.android.com/tools/publishing/versioning.html 2nd step is to sign the application for the first time : http://developer.android.com/tools/publishing/app-signing.html and the 3rd step is to update the version of your application on play store : https://support.google.com/googleplay/android-developer/answer/113476?hl=en in the last link you will guidance on how to check the application signature and if they match the previous version signature. A: I solved it! My mistake, I was trying to check the update without signing the application (I copied it directly from the bin!) Thanks,
unknown
d4663
train
You need to learn more about layouts and how they work. I strongly suggest you read the entire layout manager tutorial, since understanding layouts are the solution here, and just using BorderLayout isn't the way to solve it. You'll likely want to nest layouts, perhaps using BorderLayout for the overall GUI, and having a central JPanel use BoxLayout to allow you to stack components on top of each other inside of it. Then perhaps add this JPanel to the main JPanel that uses BorderLayout in the BorderLayout.CENTER position. A: Just a hunch, but maybe you need to call repaint() in addition to revalidate() Java Swing revalidate() vs repaint()
unknown
d4664
train
On any links to the register page put <a href="Signup.aspx?ReturnUrl=<%=Request.Url.AbsolutePath%>">Register Here</a> then on your register form when they have registered add: if (!String.IsNullOrEmpty(Request["ReturnUrl"])) Response.Redirect(Request["ReturnUrl"]); else Response.Redirect("~/Default.aspx"); A: if(Request.QueryString["foo"] == "bar"){ Response.Redirect("page.php", true); } This would get the information from http://www.example.com/registered.aspx?foo=bar So Request.QueryString["QueryString"] is the value of anything after the ? and each variable after the &. so if you had http://www.example.com/registered.aspx?foo=bar&abc=def Then you would have 2 querystrings, foo and abc.
unknown
d4665
train
We can use the dcast from data.table. It should be more efficient than the cast from reshape. We convert the 'data.frame' to 'data.table' (setDT(df1)) and then use dcast. library(data.table) dcast(setDT(df1), date+item_id~ paste0("store", store_id), value.var="sale_num") # date item_id store1 store2 store3 #1: 1/1/15 33 10 12 15 #2: 1/1/15 44 54 NA 66 #3: 1/2/15 33 14 NA NA
unknown
d4666
train
No, you do not have to manually call it. The destructor of CBrush calls DeleteObject() for you...actually the destructor for CGdiObject from which CBrush is derived. To make sure bad things don't happen, you should also make sure that the brush is not selected into a device context when the destruction occurs. A: no, you can find in the msdn an exemple of code. http://msdn.microsoft.com/fr-fr/library/btwwha51.aspx
unknown
d4667
train
You should be adding, not attaching, the new objects. Update If you get the same error when you AddObject, then you need to make sure the StoreGeneratedPattern in SSDL is set to Identity. The designer should do this for you if your DB is set up correctly and your provider supports it. A: If the item does not exist in the database you do not need to call context.Attach, only context.AddObject or context.<collection>.Add.
unknown
d4668
train
I'm going to take a few guesses here about what you are trying to do, because I'm not 100% sure I understood... Here's what I think you are trying to do: * *There are two ListViews. *When you click on the first one, it sets up text in the second one to load. *It does so via an AsyncTask called LoadProduct. *selected is used in the LoadProduct to determine what to load. *You aren't getting quite the results you expect. Okay, so if I'm right here, I would suggest a few changes. * *Pass in the selected value to the AsyncTask. *Clear the previous adapter from it's values. *Add the new values. The AsyncTask should be able to take the input, no problem. A: You just need to clear array list using clear method before adding new data to array,this would defiantly help you
unknown
d4669
train
The most efficient way would be to realize that it is a bad idea. 1000 records is too much for any user to deal with. 1-2 Orders of Magnitude to much. There is no human on this planet, that could work with that much data at once. This data needs to be filtered, grouped or paginated way more before it comes in front of a user. And those are all operations you should not be doing past the query. Those should be done in the query itself. Retrieving data you do not want to do filtering later just adds a tone of network load, adds race conditions, Database locks and is propably slower anyway (DBMS are really good at their job!). Worse, with ASP.Net and it's shared memory it can quickly lead to memory issues. A: Profile your code. Understand where most of the time is spent. It could be SQL Server, it could be transmission over network, it could be binding the data to the control[s]. If it is SQL Server, we would need to see your schema to tell you how performance could be improved. Like, do you have an index on mykey? BTW, don't call it a key, key is something that uniquely identifies the record, which is obviously not the case here. A: Use reporting (e.g. Reporting Services) and create a link to export the data into an excel spreadsheet.
unknown
d4670
train
You can signal history that you are done passing arguments, so it does not try to evaluate -t, like so: history -s -- "-t tag_name"
unknown
d4671
train
You will have to execute multiple cypress runners in order for Cypress to actually run in parallel. If you only have one npx cypress run command, then only one runner is being used. I've found the easiest way to run multiple cypress runners is to use npm-run-all. Assuming my script in my package.json is cypress-tests, my npm-run-all script to run the tests with three runners would be: npm-run-all cypress-tests cypress-tests cypress-tests --parallel Note: the --parallel flag here tells npm-run-all to run your commands in parallel. If the corresponding cypress flag is removed, your tests will not run in parallel (instead, npm-run-all will run two cypress runners in parallel, but each running your entire suite.)
unknown
d4672
train
I'll try and address these one at a time to better match the question: 1) You can re-bind when you .load() (or whatever jQuery ajax method you're using) or use a plugin like livequery(), for example here's re-binding (do this in your success handler): $("#myDynamicDiv .myForm").ajaxForm({ ...options... }); Or using livequery(): $(".myForm").livequery(function() { $(this).ajaxForm({ ...options... }); }); 2) Use a class instead of IDs here, like this: class="myForm", whenever you want to handle batches of elements like this class is a pretty safe route. The examples above work with class and not IDs per form (they can have IDs, they're just not used). Your form tags would look like this: <form class="myForm"> 3) The same solutions in answer #1 account for this :) A: ID values are unique to a single DOM element. So you'd need to give each form a new ID, so if you had three forms, you could name them like so: <form name="formone" id="formone"... <form name="formtwo" id="formtwo"... <form name="formthree" id="formthree"... Now you'd create instances of your ajax request like so: $('#formone, #formtwo, #formthree').ajaxForm({ beforeSubmit: showLoader, success: hideLoader });
unknown
d4673
train
do like: yourAdapter.getItem(info.position); or ((YourAdapter)lv.getAdapter()).getItem(position); or even simpler, listOfItem.get(info.position);
unknown
d4674
train
This is answered in the comments on the original post. It was fixed by just removing var canvas = this;.
unknown
d4675
train
I fixed the problem. Go to --> windows setting --> Network& Internet --> Proxy --> Switch Turn on (Use a Proxy server) to Turn Off A: Are you using proxy software, like V2ray, SSR...? If so, close the software, and try again. A: On Linux, the problem can be resolved by replacing https with http in the proxy settings environment variable export https_proxy=http://123.123.123.123:8888. Note, it is proxy settings for https, but an http address is used. A: So far no one has suggested that the pip version is one of the culprits as well. If your virtual environment is having a recent version of pip (e.g. 21.3.1), try to download the older version same as the one installed in the main python directory (e.g. pip version 19.0.3). For Windows, copy it to the venv\Lib\site-packages folder and unzip the contents, then cd into that folder then enter the commands python setup.py install to downgrade the pip version. A: SSL Trust Issues: pip install numpy -i http://pypi.douban.com/simple --trusted-host pypi.douban.com https://jhooq.com/pip-install-connection-error/ A: On windows,the problem can be resolved by add 'pypi.org' to the proxy whitelist in the proxy settings A: maybe you can try to replace ip to proxy server hostname if commands run in unix and you know server hostname
unknown
d4676
train
You can bind your Combo box items from your view model using item source. See the example below: First, you want to set the DataContext of your Window. /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = new ViewModel(); } } Next, public class ViewModel { public ObservableCollection<string> CmbContent { get; private set; } public ViewModel() { CmbContent = new ObservableCollection<string> { "Item 1", "Item 2", "Item 2" }; } } Finally, <Grid> <ComboBox Width="200" VerticalAlignment="Center" HorizontalAlignment="Center" x:Name="MyCombo" ItemsSource="{Binding CmbContent}" /> </Grid>
unknown
d4677
train
Here is option to build everything in Angular without Nginx * *Create a App/Home component, which renders your landing page including Login & Register buttons. *Build a normal app/routing for Login & Register. *During compile time (ng build), pre-render the App component using AppShell technique. Here is blog for your reference https://medium.com/technext/boost-your-angular-app-using-appshell-217651af6698
unknown
d4678
train
Just need to add the below code at the new test case result newTestCaseResult.addProperty("TestSet", testsetref);
unknown
d4679
train
li tags align themselves vertically but not their content, so in order to align the content vertically either you need to use display: table-cell; or line-height property li{ list-style:none; height:33%; vertical-align: middle; line-height: 100px; } Demo Also I don't think you are resetting the stylesheet in your codepen demo, search for CSS reset and you will get loads of reset stylesheets which will reset the browser applied default styles. A: Check this out: http://codepen.io/anon/pen/xHncd #navigationWheeler { height: 300px; width:30px; text-align: center; vertical-align: middle; border: black solid 1px; background-color: lightgray; } li{ list-style:none; height:33%; vertical-align: middle; } li:before { content: ''; display: inline-block; height: 100%; vertical-align: middle; } It's a bit hacky, but you can keep percentage as the height for your li-tags. A: It appears some padding is being applied to the ul. This is most likely the default styling of the browser and a CSS reset would remove this. Remove this padding and place a width on the ul to horizontally center the elements. navigationWheeler { height: 300px; width:30px; text-align: center; vertical-align: middle; border: black solid 1px; background-color: lightgray; padding: 0px; width: 100px; } Adding padding to the li elements can vertically center the text within them. li{ list-style:none; height:33%; vertical-align: middle; padding-top: 50%; } Working Example http://codepen.io/anon/pen/Djzhy A: All solutions I have seen so far work partly. This is the full working pen: * *No padding/margin on ul-tag *li-tags increase with the height of their parent by %. http://codepen.io/helloworld/pen/IfymB <ul id="navigationWheeler" > <li> <div>1</div> </li> <li style="background-color: #0094ff;"> <div>2</div> </li> <li> <div>3</div> </li> </ul> #navigationWheeler { height: 300px; width:30px; text-align: center; vertical-align: middle; border: black solid 1px; background-color: lightgray; padding:0; margin:0; } li{ list-style:none; height:33%; vertical-align: middle; display:table; } div{ width:30px; display:table-cell; vertical-align: middle; }
unknown
d4680
train
Straight from the horses mouth: public static void CreateMessageWithAttachment(string server) { // Specify the file to be attached and sent. // This example assumes that a file named Data.xls exists in the // current working directory. string file = "data.xls"; // Create a message and set up the recipients. MailMessage message = new MailMessage( "[email protected]", "[email protected]", "Quarterly data report.", "See the attached spreadsheet."); // Create the file attachment for this e-mail message. Attachment data = new Attachment(file, MediaTypeNames.Application.Octet); // Add time stamp information for the file. ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(file); disposition.ModificationDate = System.IO.File.GetLastWriteTime(file); disposition.ReadDate = System.IO.File.GetLastAccessTime(file); // Add the file attachment to this e-mail message. message.Attachments.Add(data); //Send the message. SmtpClient client = new SmtpClient(server); // Add credentials if the SMTP server requires them. client.Credentials = CredentialCache.DefaultNetworkCredentials; try { client.Send(message); } catch (Exception ex) { Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", ex.ToString() ); } // Display the values in the ContentDisposition for the attachment. ContentDisposition cd = data.ContentDisposition; Console.WriteLine("Content disposition"); Console.WriteLine(cd.ToString()); Console.WriteLine("File {0}", cd.FileName); Console.WriteLine("Size {0}", cd.Size); Console.WriteLine("Creation {0}", cd.CreationDate); Console.WriteLine("Modification {0}", cd.ModificationDate); Console.WriteLine("Read {0}", cd.ReadDate); Console.WriteLine("Inline {0}", cd.Inline); Console.WriteLine("Parameters: {0}", cd.Parameters.Count); foreach (DictionaryEntry d in cd.Parameters) { Console.WriteLine("{0} = {1}", d.Key, d.Value); } data.Dispose(); }
unknown
d4681
train
I had a same problem. Solution for me was: * *In jupyter print %pip install lasio *Reset the kernel and start again That's all. By the way, via conda it didn't work. Good lick!
unknown
d4682
train
I'm assuming that you mean that the numbers now have commas as a thousands-separator, like this: 1234567 = "1,234,567" You can remove all of those commas before you call parseInt, like this: tot += parseInt($(this).html().replace(',',''));
unknown
d4683
train
You can perform math operations using filters you can use {{quantityCols | multiply("pageSize")}} documentation here https://github.com/rangav/thunder-client-support/blob/master/docs/filters.md#multiply
unknown
d4684
train
Same problem. Tons of link errors when compiling for simulator; device works fine. Checked frameworks as suggested by Sim but looked fine. Edit: All of the problems seem to be with pre-compiled 3rd party libraries (in my case that means the Facebook Three20.a library and Occipital's libRedLaserSDK.a). Anybody know if I need to use versions of those libraries recompiled for 4.0, or if there is there another fix? Edit2: And one more clue, which suggests some of the other posters are on the right track: in my project "Groups & Files" list, all of my frameworks appear in red text. Yet if I check any one of them, the target checkbox is checked. A: I don't know why this suddenly started happening when you upgraded, but these link errors mean that your link line is missing some frameworks. It would be very helpful to see the full compiler output (expand the transcript in Build Results to get this). Looks like QuartzCore, Foundation, MediaPlayer, UIKit and others are missing, based on the symbols which are undefined. I figured this out by searching for the missing symbols (e.g. "NSOperation") in the iPhone developer site. The documentation for each function lists the framework that defines the function. A: Check Frameforks is checked for the new build target. Select UIkit.framework -> Get Info and check general and targets tabs A: I would try reinstalling XCode. Backup your /Developer folder first then give these steps a go. From the terminal use: sudo /Developer/Library/uninstall-devtools --mode=all to uninstall XCode and the iPhone SDKs, then delete the /Developer folder after you've done this to ensure that XCode and the iPhone SDK have been cleanly removed from your system. Reinstall Xcode afterwards. A: I had this same problem a couple of days ago, but for me just restarting Xcode fixed it, I could build my app without any problems. I have no idea what caused this to happen in the first place, though.
unknown
d4685
train
You can't delete an element from an array, but you can delete a vector element like this: #include <iostream> #include <vector> using namespace std; int main() { vector<int> nums = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75 }; char ans; int pos = 0; cout << "Press y to generate number: "; cin >> ans; while (ans == 'y' || ans == 'Y') { cout << "\n\nEnter position to Delete number: "; cin >> pos; --pos; nums.erase(nums.begin() + pos); cout << "\nNew Array is:\n\n"; for (const auto& element : nums) { std::cout << element << '\n'; } cout << "Press y to generate number" << "\n"; cin >> ans; } }
unknown
d4686
train
merging the columns and force pandas to compare the values in each column and always favour the non-NaN value. Is this what you mean? In [45]: data = pd.merge(df1, df2, how='outer', on=['Item ID', 'Equipment']) In [46]: data['Location'] = data['Location_y'].fillna(data['Location_x']) In [47]: data['Owner'] = data['Owner_y'].fillna(data['Owner_x']) In [48]: data = data.drop(['Location_x', 'Location_y', 'Owner_x', 'Owner_y'], axis=1) In [49]: data Out[49]: Item ID Equipment Status Date Location Owner 0 1 Jackhammer Active 08/09/2020 London James 1 1 Jackhammer Active 08/10/2020 London James 2 2 Cement Mixer Active 29/02/2020 New York Tim 3 3 Drill Active 11/02/2020 Paris Sarah 4 3 Drill Active 30/11/2020 Paris Sarah 5 3 Drill Active 21/12/2020 Paris Sarah 6 4 Ladder Inactive NaN Hong Kong Luke 7 5 Winch Inactive NaN Sydney Kojo 8 6 Circular Saw Active 19/06/2020 Moscow Alex 9 7 Hammer NaN 21/12/2020 Toronto Ken 10 8 Sander NaN 19/06/2020 Frankfurt Ezra (To my knowledge) you cannot really merge on null column. However you can use fillna to take the value and replace it by something else if it is NaN. Not a very elegant solution, but it seems to solve your example at least. Also see pandas combine two columns with null values A: Generically you can do that as follows: # merge the two dataframes using a suffix that ideally does # not appear in your data suffix_string='_DF2' data = pd.merge(df1, df2, how='outer', on=['Item_ID'], suffixes=('', suffix_string)) # now remove the duplicate columns by mergeing the content # use the value of column + suffix_string if column is empty columns_to_remove= list() for col in df1.columns: second_col= f'{col}{suffix_string}' if second_col in data.columns: data[col]= data[second_col].where(data[col].isna(), data[col]) columns_to_remove.append(second_col) if columns_to_remove: data.drop(columns=columns_to_remove, inplace=True) data The result is: Item_ID Equipment Owner Status Location Date 0 1 Jackhammer James Active London 08/09/2020 1 1 Jackhammer James Active London 08/10/2020 2 2 Cement_Mixer Tim Active New_York 29/02/2020 3 3 Drill Sarah Active Paris 11/02/2020 4 3 Drill Sarah Active Paris 30/11/2020 5 3 Drill Sarah Active Paris 21/12/2020 6 4 Ladder Luke Inactive Hong_Kong NaN 7 5 Winch Kojo Inactive Sydney NaN 8 6 Circular_Saw Alex Active Moscow 19/06/2020 9 7 Hammer Ken NaN Toronto 21/12/2020 10 8 Sander Ezra NaN Frankfurt 19/06/2020 On the following test data: df1= pd.read_csv(io.StringIO("""Item_ID Equipment Owner Status Location 1 Jackhammer James Active London 2 Cement_Mixer Tim Active New_York 3 Drill Sarah Active Paris 4 Ladder Luke Inactive Hong_Kong 5 Winch Kojo Inactive Sydney 6 Circular_Saw Alex Active Moscow"""), sep='\s+') df2= pd.read_csv(io.StringIO("""Item_ID Equipment Owner Date Location 1 Jackhammer James 08/09/2020 London 1 Jackhammer James 08/10/2020 London 2 Cement_Mixer NaN 29/02/2020 New_York 3 Drill Sarah 11/02/2020 NaN 3 Drill Sarah 30/11/2020 NaN 3 Drill Sarah 21/12/2020 NaN 6 Circular_Saw Alex 19/06/2020 Moscow 7 Hammer Ken 21/12/2020 Toronto 8 Sander Ezra 19/06/2020 Frankfurt"""), sep='\s+')
unknown
d4687
train
I think this might be what you're looking for x.split(/\^|\$|\*/) A: This works for me: x = "a random string to be formatted" ['^', '$', '*'].each { |token| x = x.split(token)[0] if x.include?(token) } A: Based on the code you provided x = 'a random string to be formated' %w(^ $ *).each do |symbol| x = x.split(symbol)[0] if x.include?(symbol) end A: You're looking for this regex: string.match(/^([^^$*]+)[$^*]?/).captures[0] It returns all characters up the the first occasion of $, ^, or *, or the end of the string.
unknown
d4688
train
Make JsonGenerator as mock object, then verify its method call. @ExtendWith(MockitoExtension.class) class TestDateTimeSerializerTest { @Mock JsonGenerator generator; // JsonGenerator is mock @Mock SerializerProvider provider; @Test void test() throws IOException { TestDateTimeSerializer serializer = new TestDateTimeSerializer(); LocalDateTime now = LocalDateTime.now(); // run your method serializer.serialize(now, generator, provider); // assert mocked generator's method call verify(generator).writeString(ArgumentMatchers.anyString()); } } Mockito API doc : https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#1 you can find more example and usage. A: Please try this: import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import org.junit.Before; import org.junit.Test; import java.time.LocalDateTime; import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME; import static org.junit.Assert.*; public class TestDateTimeSerializerSerializerTest { private ObjectMapper mapper; protected TestDateTimeSerializer serializer; @Before public void setup() { mapper = new ObjectMapper(); serializer = new TestDateTimeSerializer(); SimpleModule module = new SimpleModule(); module.addSerializer(LocalDateTime.class, serializer); mapper.registerModule(module); } @Test public void testSerializeNonNull() throws JsonProcessingException { LocalDateTime ldt = LocalDateTime.parse("2016-10-06T10:40:21.124", ISO_LOCAL_DATE_TIME); String serialized = mapper.writeValueAsString(ldt); assertEquals("equal strings", "\"2016-10-06T10:40:21.124Z\"", serialized); } @Test public void testSerializeNull() throws JsonProcessingException { LocalDateTime ldt = null; String serialized = mapper.writeValueAsString(ldt); assertEquals("equal strings", "null", serialized); } }
unknown
d4689
train
Your algorithm's runtime is O(N^2) that is approximately 10^5 * 10^5 = 10^10. With some basic observation it can be reduced to O(NlgN) which is approximately 10^5*16 = 1.6*10^6 only. Algorithm: * *Sort the array ary_nums. *for every i'th integer of the array, make a binary search to find if ary_nums[i]-K, is present in the array or not. If present increase result, skip i'th integer otherwise. sort($ary_nums); for ($i = $total_nums - 1; $i > 0; $i--) { $hi = $i-1; $low = 0; while($hi>=$low){ $mid = ($hi+$low)/2; if($ary_nums[$mid]==$ary_nums[$i]-$diff){ $count++; break; } if($ary_nums[$mid]<$ary_nums[$i]-$diff){ $low = $mid+1; } else{ $hi = $mid-1; } } } } A: I got the same question for my technical interview. I wonder if we are interviewing for the same company. :) Anyway, here is my answer I came up with (after the interview): // Insert code to get the input here $count = 0; sort ($arr); for ($i = 0, $max = $N - 1; $i < $max; $i++) { $lower_limit = $i + 1; $upper_limit = $max; while ($lower_limit <= $upper_limit) { $midpoint = ceil (($lower_limit + $upper_limit) / 2); $diff = $arr[$midpoint] - $arr[$i]; if ($diff == $K) { // Found it. Increment the count and break the inner loop. $count++; $lower_limit = $upper_limit + 1; } elseif ($diff < $K) { // Search to the right of midpoint $lower_limit = $midpoint + 1; } else { // Search to the left of midpoint $upper_limit = $midpoint - 1; } } } @Fallen: Your code failed for the following inputs: Enter the numbers N and K: 10 3 Enter numbers for the set: 1 2 3 4 5 6 7 8 9 10 Result: 6 I think it has to do with your calculation of $mid (not accounting for odd number)
unknown
d4690
train
One of the new features in C++20 is Down with typename. In C++17, you had to provide the typename keyword in nearly all† dependent contexts to disambiguate a type from a value. But in C++20, this rule is relaxed a lot. In all contexts where you need to have a type, the typename keyword is no longer mandatory. One such context is the return type of a function in class scope, as in your example. Others include the type in a member declaration, the type on the right-hand side of a using declaration, the parameter declaration of a lambda, the type you're passing to static_cast, etc. See the paper for the full list. † Nearly all because base-specifiers and mem-initializer-ids were always excluded, as in: template <typename T> struct X : T::type { }; // always ok This is okay because, well, that needs to be a type. The paper simply extends this logic (well, it has to be a type, so let's just assume it's a type) to a lot more places that have to be types. A: From the reference, from c++20, in contexts where the dependent name is unambiguously a typename, the typename keyword is no longer needed. In particular: A qualified name that is used as a declaration specifier in the (top-level) decl-specifier-seq of: a simple declaration or function definition at namespace scope
unknown
d4691
train
I have no idea what resolved this. maybe a reboot? maybe some odd update. I came in one monday and it started working. A: I can not find an answer anywhere. uninstalled and reinstalled...again. No luck. I finally had the ODBC idea. I created an ODBC datasource, then used that using the ADOXSchemaProvider. This works. Not great, but this beats coding by hand, and for now, it beats converting all my templates to something else. here is a sample ODBC connection string if you need to go this route. DSN=myDsn;Uid=myUsername;Pwd=mypwd;
unknown
d4692
train
You have all <div>s with the same ID. You should not duplicate the IDs. They should be unique. And also, a <label> cannot have a <div> inside it. Since you are using $("#select"), it selects only the first <div>. Make sure your IDs are unique and try it. This code works for you: $(document).ready( function(){ $('select').focus( function(){ $(this).closest("div").addClass('selected'); }); $('select').focusout( function(){ $(this).closest("div").removeClass('selected'); }); }); Fiddle: http://jsfiddle.net/praveenscience/TeNaf/2/
unknown
d4693
train
Editing databases with data grids is ridiculously easy if you make life easy. Try doing this: * *Make a brand new project, so you don't disturb existing code *Add a new file of type DataSet *Open it by double clicking *Right click anywhere on the surface, choose Add.. TableAdapter *Fill in the connection details of the db *Choose "SELECT that produces rows" *Put a query of SELECT * FROM tbl_tahunan *Finish the wizard *Switch to the form *Open the Data Sources tool panel (View menu, Other Windows submenu) *Expand the nodes in the name of your dataset *Drag the tbl_tahunan one onto the form *Run the program Yes, that's it, not a single line of code written by you; VS has done it all (and made a better job of it too) and this simple app will download, display, edit and save rows. And I bet it won't have any decimal problems either.. You can look at how it works by reading the code in .Designer.cs files: the datagridview is connected to a datatable (tbl_tahunandatatable) through a bindingSource. When you fill the table with data, you will see the grid show the data automatically. You do not need to interact with the datagridview cells collection. All programmatic editing of data should be done to the datatable. This is a concept called MVC (model- the datatable, view - the datagridview, controller - sometimes the datagridview in editing mode, other times something else) - keeping M separate from VC usually helps build a sensible program structure You can build on this simple app you've created by e.g.: * *opening dataset, *right clicking on the TableAdapter, *adding another query, *add a query with some relevant where clause (llike SELECT * FROM tbl_tahunan WHERE adhb BETWEEN @from AND @to) *call it a good name, like FillByAdhbBetween *putting some text boxes in the UI *putting a button on the ui that calls it: tbl_tahunanTableAdapter.FillByAdhbBetween(somedatasetname.tbl_tahunan, Convert.ToDecimal(adhbfromTextbox.Text), Convert.ToDecimal(adhbtoTextbox.Text)) Now the grid will only fill with some rows instead of all Personally I always make the first query in a table adapter have a WHERE clause, that selects by primary key. It is handy for loading related data. We almost never want to select all rows from a db into our program
unknown
d4694
train
You should approach this the other way around. Send the user to the thanks page, and on that thanks page do $pdf->Output(). That should do what you want. A: Webpages/HTTP is a request-response system. The browser sends one request, to which there's exactly one response. You simply cannot respond with a PDF and a redirect, or a PDF and some Javascript. The typical thing to do is to display the Thank You page first, then inside this page redirect to the file download using Javascript. That way the page stays up and the file downloads. A: You can make thank-you.php send the PDF file. After submitting the form, send the user to the thank-you page then the thank you page will send the user the PDF file. In that way, the thank you page is visible and the page will still be visible after downloading the PDF file.
unknown
d4695
train
While the {x..y} syntax originated in zsh decades ago, ksh93 was the one adding the {x..y..step} one and zsh only added it in version 4.3.10-test-3 in 2010. You probably have an older version of zsh there.
unknown
d4696
train
This is possible, but with these alterations: Variables should start with a $ sign and concatenation is done with the . sign: $variable = "someContentNotHardCoded"; xmlhttp.send("name=".$variable);
unknown
d4697
train
If I understood what this is about, I see two alternatives: The first one is to modify struct account, so there's one extra field, a semaphore. Any process should P() on the semaphore before it accesses the other account's fields, and V() when it's done with it. The second would be to modify struct list, adding an extra array of semaphores, same size as the array of accounts, assigning each semaphore in the array with the same-indexed account, and using P() and V() on it again, before and after accessing the corresponding account.
unknown
d4698
train
This should do it: [layout] { display: flex; } #left { flex: 0 0 180px; background-color:#f00; margin-right: 20px; } #right { flex: 1 0 300px; background-color:#0ff; } <div layout> <div id="left"> left </div> <div id="right"> right </div> </div> See flex for details. It's flex-shrink and flex-grow that do the heavy lifting in this case. And the default value of flex-wrap, which is nowrap. Don't forget to prefix. Also note the 300px value of flex-basis (third value in flex shorthand of #right element. In this case, it's the minimum width of that element. When it gets under that size, the scrollbar appears. And here it is with 3 columns: [layout] { display: flex; } [layout] > * { padding: 1rem; } #left, #right { flex: 0 0 180px; } #left { background-color:#f00; } #right { background-color:#0ff; } #middle { flex: 1 0 300px; margin: 0 10px; border: 1px solid #eee; } <div layout> <div id="left"> left </div> <div id="middle"> middle </div> <div id="right"> right </div> </div> Side note: nobody seems to have told you the horizontal bar you're trying to achieve was what the rest of the world was trying to avoid when they invented responsive layouts. It's considered really bad user experience and Google lowers the rank of websites that do not feature responsive layouts. Long story short, it will be losing you (or the client) serious money. The more important the website, the more important the loss. A better user experience would be to transform left and right sidebars into swipe-able drawers on small devices.
unknown
d4699
train
The compiler attempts to interpret c-style casts as c++-style casts, in the following order (see cppreference for full details): * *const_cast *static_cast *static_cast followed by const_cast *reinterpret_cast *reinterpret_cast followed by const_cast Interpretation of (T1)t2 is pretty straightforward. const_cast fails, but static_cast works, so it's interpreted as static_cast<T1>(t2) (#2 above). For (T1&)t2, it's impossible to convert an int& to unsigned long& via static_cast. Both const_cast and static_cast fail, so reinterpret_cast is ultimately used, giving reinterpret_cast<T1&>(t2). To be precise, #5 above, since t2 is const: const_cast<T1&>(reinterpret_cast<const T1&>(t2)). EDIT: The static_cast for (T1&)t2 fails due to a key line in cppreference: "If the cast can be interpreted in more than one way as static_cast followed by a const_cast, it cannot be compiled.". Implicit conversions are involved, and all of the following are valid (I assume the following overloads exist, at a minimum): * *T1 c1 = t2; const_cast<T1&>(static_cast<const T1&>(c1)) *const T1& c1 = t2; const_cast<T1&>(static_cast<const T1&>(c1)) *T1&& c1 = t2; const_cast<T1&>(static_cast<const T1&>(std::move(c1))) Note that the actual expression, t1 == (T1&)t2, leads to undefined behavior, as Swift pointed out (assuming sizeof(int) != sizeof(unsigned long)). An address that holds an int is being treated (reinterpreted) as holding an unsigned long. Swap the order of definition of a and b in main(), and the result will change to be equal (on x86 systems with gcc). This is the only case that has undefined behavior, due to a bad reinterpret_cast. Other cases are well defined, with results that are platform specific. For (T1&&)t2, the conversion is from an int (lvalue) to an unsigned long (xvalue). An xvalue is essentially an lvalue that is "moveable;" it is not a reference. The conversion is static_cast<T1&&>(t2) (#2 above). The conversion is equivalent to std::move((T1)t2), or std:move(static_cast<T1>(t2)). When writing code, use std:move(static_cast<T1>(t2)) instead of static_cast<T1&&>(t2), as the intent is much more clear. This example shows why c++-style casts should be used instead of c-style casts. Code intent is clear with c++-style casts, as the correct cast is explicitly specified by the developer. With c-style casts, the actual cast is selected by the compiler, and may lead to surprising results. A: Let's look at (T1&&)t2 first. This is indeed a temporary materialization; what happens is that the compiler performs lvalue-to-rvalue conversion on t2 (i.e. accesses its value), casts that value to T1, constructs a temporary of type T1 (with value 1, since that is the value of b and is a valid value of type T1), and binds it to an rvalue reference. Then, in the comparison t1 == (T1&&)t2, both sides are again subject to lvalue-to-rvalue conversion, and since this is valid (both refer to an object of type T1 within its lifetime, the left hand side to a and the right hand side to the temporary) and both sides have value 1, they compare equal. Note that a materialized temporary of type T1 (say) can bind either to a reference T1&& or T1 const&, so you could try the latter as well in your program. Also note that while the T1 converted from t2 is a temporary, it would be lifetime extended if you bound it to a local variable (e.g. T1&& r2 = (T1&&)t2;). That would extend the lifetime of the temporary to that of the local reference variable, i.e. to the end of the scope. This is important when considering the "with its lifetime" rule, but here the temporary is destroyed at the end of the expression, which is still after it is accessed by the == comparison. Next, (T1&)t2 should be interpreted as a static_cast reference binding to a temporary T1 followed by a const_cast; that is, const_cast<T1&>(static_cast<T1 const&>(t2)). The first (inner) cast materializes a temporary T1 with value converted from t2 and binds it to a T1 const& reference, and the second (outer) cast casts away const. Then, the == comparison performs lvalue-to-rvalue conversion on t1 and on the T1& reference; both of these are valid since both refer to an object of type T1 within its lifetime, and since both have value 1 they should compare equal. (Interestingly, the materialized temporary is also a candidate for lifetime extension, but that doesn't matter here.) However, all major compilers currently fail to spot that they should do the above (Why is (int&)0 ill-formed? Why does this C-style cast not consider static_cast followed by const_cast?) and instead perform a reinterpret_cast (actually a reinterpret_cast to T1 const& followed by a const_cast to T1&). This has undefined behavior (since unsigned long and int are distinct types that are not related by signedness and are not types that can access raw memory), and on platforms where they are different sizes (e.g. Linux) will result in reading stack garbage after b and thus usually print that they are unequal. On Windows, where unsigned long and int are the same size, it will print that they are equal for the wrong reason, which will nevertheless be undefined behavior. A: Technically all four variants are platform dependent t1 == t2 t2 gets promoted to 'long', the casted to unsigned long. t1 == (T1)t2 signed int gets converted to its representation as unsigned long, in order being casted to long first. There were debates if this must be considered an UB or not, because result is depending on platform, I honestly not sure how it is defined now, aside from clause in C99 standard. Result of comparison would be same as t1 == t2. t1 == (T1&)t2 The cast result is a reference, you compare reference ( essentially a pointer) to T1, which operation yields unknown result. Why? Reference js pointing to a different type. t1 == (T1&&)t2 The cast expression yields an rvalue, so you do compare values, but its type is rvalue reference. Result of comparison would be same as t1 == t2. PS. Funny thing happen (depends on platform, essentially an UB) if if you use such values: const unsigned long a = 0xFFFFFFFFFFFFFFFF; const int b = -1; Output might be: t1 == t2 t1 == (T1)t2 t1 == (T1&)t2 t1 == (T1&&)t2 This is one of reasons why you should be careful in comparing unsigned to signed values, especially with < or >. You'll be surprised by -1 being greater than 1. if unsigned long is 64bit int and pointer is equal to 64-bit int. -1 if casted to unsigned, becomes its binary representation. Essentially b would become a pointer with address 0xFFFFFFFFFFFFFFFF.
unknown
d4700
train
So this is how I solved the issue i was facing. A simple 1 line code was enough. def execute_XXXX(): f = open('linux.pem','r') s = f.read() keyfile = StringIO.StringIO(s) mykey = paramiko.RSAKey.from_private_key(keyfile) sshcon = paramiko.SSHClient() sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) sshcon.connect('XXX.XXX.XXX.XXX', username='XXX', pkey=mykey) stdin, stderr, stdout= sshcon.exec_command('spark-submit XXX.py') if (stdout.channel.recv_exit_status())!= 0: logger.info("XXX ------>"+str(stdout.readlines())) logger.info("Error--------->"+str(stderr.readlines())) sys.exit(1) A: You need to implement a sparkListener. More information to which can be found on the below link. How to implement custom job listener/tracker in Spark?
unknown