_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d9001
train
The reason you are getting an "image not found" error is because there is no such image called plugins/trigger in the docker registry. Instead I think you probably want the plugins/downstream image [1][2]. [1] http://plugins.drone.io/drone-plugins/drone-downstream/ [2] https://hub.docker.com/r/plugins/downstream/
unknown
d9002
train
If using ngx-translate you can do the following: <ion-select formControlName="myControl" [okText]="'okText' | translate" [cancelText]="'cancelText' | translate"></ion-select> In translation file e.g. en.json { "okText": "OK", "cancelText": "Cancel" } A: <ion-select multiple="true" okText="Okay" cancelText="Dismiss"> I am not sure but you can try this too <ion-select multiple="true" okText="ٹھیک ہے" cancelText="خطرہ"> A: This work for me using ngx-translate doing the following: HTML FILE <ion-select cancelText="{{'SELECT.Cancel' | translate:params}}" okText="{{'SELECT.ok' | translate:params}}"> </ion-select> i18n en.josn FILE { "SELECT": { "ok":"OK", "Cancel":"Cancel" }, }
unknown
d9003
train
You are looking to add a header to your UICollection views. There are MANY tutorials that can help you. This one here can get you started: http://www.appcoda.com/supplementary-view-uicollectionview-flow-layout/
unknown
d9004
train
Looks like a problem with ab on OSX Lion: http://simon.heimlicher.com/articles/2012/07/08/fix-apache-bench-ab-on-os-x-lion That fixed my problem.
unknown
d9005
train
You should be using a prepared statement with a ? placeholder for the city value. Then, bind a JS variable to the ?. router.get('/filter/:city', (req, res) => { const location = req.params.city; connection.query( "SELECT * FROM weather_data WHERE city = ?", [location], (err, results, field) => { if (err) { console.log(err); } else { res.status(200).send(results); console.log(results); } } ); }); Note that when using a prepared statement there is no need to massage the location variable by doing things like wrapping in single quotes. Instead, let your MySQL driver worry about how to handle this, via the prepared statement. A: `select * from weather_data where city = \'${singleQuoteLocation}\' `
unknown
d9006
train
Without getting into the specifics of your code, one pattern is to carry a mutable container for your results in the arguments public static int makeChange(int amount, int currentCoin, List<Integer>results) { // .... if (valid_result) { results.add(result); makeChange(...); } // .... } And call the function like this List<Integer> results = new LinkedList<Integer>(); makeChange(amount, currentCoin, results); // after makeChange has executed your results are saved in the variable "results" A: I don't understand logic or purpose of above code but this is how you can have each combination stored and then printed. public class MakeChange { private static int[] availableCoins = { 1, 2, 5, 10, 20, 25, 50, 100 }; public static void main(String[] args) { Collection<CombinationResult> results = makeChange(5, 7); for (CombinationResult r : results) { System.out.println( "firstWay=" + r.getFirstWay() + " : secondWay=" + r.getSecondWay() + " --- Sum=" + r.getSum()); } } public static class CombinationResult { int firstWay; int secondWay; CombinationResult(int firstWay, int secondWay) { this.firstWay = firstWay; this.secondWay = secondWay; } public int getFirstWay() { return this.firstWay; } public int getSecondWay() { return this.secondWay; } public int getSum() { return this.firstWay + this.secondWay; } public boolean equals(Object o) { boolean flag = false; if (o instanceof CombinationResult) { CombinationResult r = (CombinationResult) o; flag = this.firstWay == r.firstWay && this.secondWay == r.secondWay; } return flag; } public int hashCode() { return this.firstWay + this.secondWay; } } public static Collection<CombinationResult> makeChange( int amount, int currentCoin) { Collection<CombinationResult> results = new ArrayList<CombinationResult>(); makeChange(amount, currentCoin, results); return results; } public static int makeChange(int amount, int currentCoin, Collection<CombinationResult> results) { // if amount = zero, we are at the bottom of a successful recursion if (amount == 0) { // return 1 to add this successful solution return 1; // check to see if we went too far } else if (amount < 0) { // don't count this try if we went too far return 0; // if we have exhausted our list of coin values } else if (currentCoin < 0) { return 0; } else { int firstWay = makeChange( amount, currentCoin - 1, results); int secondWay = makeChange( amount - availableCoins[currentCoin], currentCoin, results); CombinationResult resultEntry = new CombinationResult( firstWay, secondWay); results.add(resultEntry); return firstWay + secondWay; } } } A: I used the following: /** * This is a recursive method that calculates and displays the combinations of the coins included in * coinAmounts that sum to amountToBeChanged. * * @param coinsUsed is a list of each coin used so far in the total. If this branch is successful, we will add another coin on it. * @param largestCoinUsed is used in the recursion to indicate at which coin we should start trying to add additional ones. * @param amountSoFar is used in the recursion to indicate what sum we are currently at. * @param amountToChange is the original amount that we are making change for. * @return the number of successful attempts that this branch has calculated. */private static int change(List<Integer> coinsUsed, Integer currentCoin, Integer amountSoFar, Integer amountToChange) { //if last added coin took us to the correct sum, we have a winner! if (amountSoFar == amountToChange) { //output System.out.print("Change for "+amountToChange+" = "); //run through the list of coins that we have and display each. for(Integer count: coinsUsed){ System.out.print(count + " "); } System.out.println(); //pass this back to be tallied return 1; } /* * Check to see if we overshot the amountToBeChanged */ if (amountSoFar > amountToChange) { //this branch was unsuccessful return 0; } //this holds the sum of the branches that we send below it int successes=0; // Pass through each coin to be used for (Integer coin:coinAmounts) { //we only want to work on currentCoin and the coins after it if (coin >= currentCoin) { //copy the list so we can branch from it List<Integer> copyOfCoinsUsed = new ArrayList<Integer>(coinsUsed); //add on one of our current coins copyOfCoinsUsed.add(coin); //branch and then collect successful attempts successes += change(copyOfCoinsUsed, coin, amountSoFar + coin, amountToChange); } } //pass back the current return successes; }
unknown
d9007
train
You'll need to also implement a VisualizerObjectSource to perform custom serialization. Example: public class ControlVisualizerObjectSource : VisualizerObjectSource { public override void GetData(object target, Stream outgoingData) { var writer = new StreamWriter(outgoingData); writer.WriteLine(((Control)target).Text); writer.Flush(); } } public class ControlVisualizer : DialogDebuggerVisualizer { protected override void Show( IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider) { string text = new StreamReader(objectProvider.GetData()).ReadLine(); } public static void TestShowVisualizer(object objectToVisualize) { var visualizerHost = new VisualizerDevelopmentHost( objectToVisualize, typeof(ControlVisualizer), typeof(ControlVisualizerObjectSource)); visualizerHost.ShowVisualizer(); } } class Program { static void Main(string[] args) { ControlVisualizer.TestShowVisualizer(new Control("Hello World!")); } } You'll also need to register the visualizer with the appropriated VisualizarObjectSource, which for this example could be something like this: [assembly: DebuggerVisualizer( typeof(ControlVisualizer), typeof(ControlVisualizerObjectSource), Target = typeof(System.Windows.Forms.Control), Description = "Control Visualizer")]
unknown
d9008
train
A native query, by definition, is a SQL query. It must contain valid SQL for your specific database. The query will return a List<Object[]>, and it should be trivial to iterate through the list and create a new instance of FreeLocation for each Object[] array.
unknown
d9009
train
You can't determine how many lines the URL response will be over, so you need to join them all together yourself in one line using StringBuilder: static void updateIp() throws MalformedURLException, IOException { String urlParameters = "name=sub&a=rec_edit&id=9001"; URL url = new URL("http://httpbin.org/post"); URLConnection con = url.openConnection(); con.setDoOutput(true); BufferedReader reader; try (OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream())) { writer.write(urlParameters); writer.flush(); String line; StringBuilder urlResponse = new StringBuilder(); reader = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((line = reader.readLine()) != null) { urlResponse.append(line); } String response = urlResponse.toString(); System.out.println(response); } reader.close(); } The response string variable will now contain all the output in a single line.
unknown
d9010
train
Starting from C++17 there's no difference whatsoever. There's one niche use case where the std::vector = std::vector initialization syntax is quite useful (albeit not for default construction): when one wants to supply a "count, value" initializer for std::vector<int> member of a class directly in the class's definition: struct S { std::vector<int> v; // Want to supply `(5, 42)` initializer here. How? }; In-class initializers support only = or {} syntax, meaning that we cannot just say struct S { std::vector<int> v(5, 42); // Error }; If we use struct S { std::vector<int> v{ 5, 42 }; // or = { 5, 42 } }; the compiler will interpret it as a list of values instead of "count, value" pair, which is not what we want. So, one proper way to do it is struct S { std::vector<int> v = std::vector(5, 42); }; A: The 1st one is default initialization, the 2nd one is copy initialization; The effect is same here, i.e. initialize the object v via the default constructor of std::vector. For std::vector<int> v = std::vector<int>();, in concept it will construct a temporary std::vector then use it to move-construct the object v (note there's no assignment here). According to the copy elision (since C++17 it's guaranteed), it'll just call the default constructor to initialize v directly. Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible, as the language rules ensure that no copy/move operation takes place, even conceptually: * *In the initialization of a variable, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type: T x = T(T(f())); // only one call to default constructor of T, to initialize x (Before C++17, the copy elision is an optimization.) this is an optimization: even when it takes place and the copy/move (since C++11) constructor is not called, it still must be present and accessible (as if no optimization happened at all), BTW: For both cases, no std::vector objects (including potential temporary) will be constructed with dynamic storage duration via new expression. A: You had asked: What is the difference between std::vector<int> v; and std::vector<int> v = std::vector<int>(); ? As others have stated since C++17 there basically is no difference. Now as for preference of which one to use, I would suggest the following: * *If you are creating an empty vector to be filled out later then the first version is the more desirable candidate. *If you are constructing a vector with either a default value as one of its members and or a specified count, then the later version would be the one to use. *Note that the following two are different constructors though: * *std::vector<int> v = std::vector<int>(); *Is not the same constructor as: *std::vector<int> v = std::vector<int>( 3, 10 ); *The 2nd version of the constructor is an overloaded constructor. *Otherwise if you are constructing a vector from a set of numbers than you have the following options: * *std::vector<int> v = { 1,2,3,4,5 }; *operator=( std::initializer_list) *std::vector<int> v{ 1,2,3,4,5 }; *list_initialization Here is the list of std::vector constructors.
unknown
d9011
train
It seems like you are saying you're trying to assign a class as the current user's name. I'm wondering if going that far is necessary. Assigning the list element with a class named "current_user" might be enough, then have separate CSS to control anything with class named "current_user". Here's an example fiddle. CSS li { list-style:none; clear:both; float:right; text-align:right; background-color:#A7A2A0; border:1px solid #EEE; width:200px; margin:10px; padding:5px; } li.current_user { float:left; text-align:left; background-color:#24887F; } HTML <li class="current_user"> <b>Current User:</b> <div class="message"> <p>My message!</p> </div> </li> <li> <b>All Other Users:</b> <div class="message"> <p>Other person's smessage.</p> </div> </li> UPDATE: Looking at the firebase example I altered it to add a class "current_user" if the username matched the the name of the user that wrote the message. Below is the part of the code that I altered in the "displayChatMessage" function, I also added CSS to the head section for the "current_user" class. Here's a link to the working example, view it in to different web browsers using different usernames at the same time to see. function displayChatMessage(name, text) { if(name == $('#nameInput').val()){ $('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv')).addClass('current_user'); $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight; } else{ $('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv')); $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight; } }; This is the CSS I added to the head. <style type="text/css"> .current_user { background-color:#24887F; } </style> A: There are many users using the app concurrently. But for every user, there is only one current_user in session. Don't mix it up. Since the message is to be processed by server, you can easily add a new attribute of message.klass in server side by judging the message comes from current_user. If it is, the class may be current, else blank or others. Then, in JS $('li').addClass('<%= message.klass %>')
unknown
d9012
train
CodeIgniter, though unarguably one of the best PHP frameworks to be developed, had a problem of not properly storing sessions, i.e. it was noted for storing the SESSION data in the COOKIE, only in encrypted format. Thus with sufficient knowledge about your system and the hashing algorithm used, an attacker could've transformed all cookie data to session data. This problem was solved, however before CodeIgniter v3 was released. But I believe the best way to store sessions may be: 1. Do not autoload the session class, but rather load them whenever you need them. 2. Define a basepath or exit, i.e. defined('BASEPATH') or exit('No direct script access allowed') 3. Though an overstretch, I recommend setting an encryption key and encrypting every session value before you store it (remember to set a strong encryption key password)
unknown
d9013
train
The !! is simply two ! operators right next to each other. It's a simple way of converting any non-zero value to 1, and leaving 0 as-is.
unknown
d9014
train
Here is how to do it with "f-strings" and the range() class object in a for loop: for_loop_basic_demo.py: #!/usr/bin/python3 END_NUM = 7 for i in range(1, END_NUM + 1): print(f"line{i}") Run command: ./for_loop_basic_demo.py Output: line1 line2 line3 line4 line5 line6 line7 Going further: 3 ways to print The 3 ways I'm aware of to print formatted strings in Python are: * *formatted string literals; AKA: "f-strings" *the str.format() method, or *the C printf()-like % operator Here are demo prints with all 3 of those techniques to show each one for you: #!/usr/bin/python3 END_NUM = 7 for i in range(1, END_NUM + 1): # 3 techniques to print: # 1. newest technique: formatted string literals; AKA: "f-strings" print(f"line{i}") # 2. newer technique: `str.format()` method print("line{}".format(i)) # 3. oldest, C-like "printf"-style `%` operator print method # (sometimes is still the best method, however!) print("line%i" % i) print() # print just a newline char Run cmd and output: eRCaGuy_hello_world/python$ ./for_loop_basic_demo.py line1 line1 line1 line2 line2 line2 line3 line3 line3 line4 line4 line4 line5 line5 line5 line6 line6 line6 line7 line7 line7 References: * ****** This is an excellent read, and I highly recommend you read and study it!: Python String Formatting Best Practices *Official Python documentation for all "Built-in Functions". Get used to referencing this: https://docs.python.org/3/library/functions.html * *The range() class in particular, which creates a range object which allows the above for loop iteration: https://docs.python.org/3/library/functions.html#func-range A: You can use f strings.\ n = 7 for i in range(1, n + 1): print(f"line{i}")
unknown
d9015
train
Assuming we're talking about the Html widget provided by flutter_html. If you have access to the widget, you can call .data on it to get the String? value: final Html html = Html(data: '<p>Hello world!</p>'); final String stringToShare = html.data; By defining html (the first line) in your build function, you can access it in the share button as well.
unknown
d9016
train
I think what you're looking for is Raw <label>@Html.Raw(Model.Message)</label> This will write Model.Message's contents as html instead of text.
unknown
d9017
train
Properties are not callable. When you access self.get_unique_id, Python makes the call to the underlying method decorated by @property behind the scenes, which in this case returns a string. You don't need to call it again, drop the parens: def save(self, *args, **kwarg): self.unique_id = self.get_unique_id self.age = self.get_age super(Person, self).save(*args, **kwarg) OTOH, going by @DanielRoseman's comment, you don't need store the age in the database. Just calculate it when its needed. You could rename get_age as age and drop the age field, so age becomes a property.
unknown
d9018
train
Firestore queries always work based on one or more indexes. In the case where you have conditions on multiple fields, it often needs a so-called composite index on those fields. Firestore automatically adds indexes for the individual fields, but you will have to explicitly tell it to create composite indexes. When you try to execute a query for which the necessary index is missing, the SDK raises an error that contain both the fact that an index is missing and a direct link to the Firestore console to create exactly the index that the query needs. All fields are prepopulated, so you just need to click the button start creating the index. If you don't see the error message/link in your apps logging output yet, consider wrapping the query in a try/catch and logging it explicitly.
unknown
d9019
train
I already solved the problem. The following post was quite helpful: Spring Boot And Multi-Module Maven Projects I moved the file com.example.mcp.dataintegration.Application.java to com.example.mcp.Application.java. But furthermore unclear why my ComponentScan amd JPARepo definition were ignored... A: Did you try @EnableJpaRepositories with @Configuration in Application class that you run. I have tried something like this for one of my projects which is similar to yours and it worked for me; @Configuration @EnableJpaRepositories("com.example.mcp") @EntityScan("com.example.mcp") WorkingDay has @Entity annotation.
unknown
d9020
train
%@", [view.annotation class]); [mapView removeAnnotation:view.annotation]; //[mapView removeAnnotations:mapView.annotations]; [mapView setNeedsDisplay]; } A: This may not be the only thing, but the first thing that leaps out is that you autorelease the annotation on the line where you alloc it. Therefore you shouldn't also release it after you've added it to mapView. As this stands, the annotation will likely be prematurely deallocated when the autorelease pool drains -- and if not exactly then, then at some subsequent point that is still premature. The map view will be stuck with a stale pointer and boom. Not sure why that would manifest quite as soon as you describe, so there may be something else too...
unknown
d9021
train
If you are binding to a value type, such as a string or an int, you can simply use {Binding}, here's an example: <DataTemplate > <TextBlock Text="{Binding}" TextWrapping="Wrap"/> </DataTemplate> This kind of binding will bind to the object itself as opposed to a Property on said object. Note: What gets displayed in the Text will be whatever gets returned by the .ToString() method on that object. You could then override the .ToString() method in your classes to return something useful back, like this: public class MyClass { public string Name { get; set; } public override string ToString() { return Name; } } This will force MyClass to be displayed as whatever is inside the Name property in your ComboBox. Taking this a step further, your requirements are that you may need to put objects of different types in a single ComboBox. Not a problem, you can make use of the DataType property in a DataTemplate, see below: <DataTemplate DataType="{x:Type myNamespace:myClass}"> ... </DataTemplate> Note that these should be declared in a ResourceDictionary, and will affect all objects that are displayed of that type. This allows you to define what gets displayed for a given type. A: Indeed you cannot set both DisplayMemberPath property and a specific ItemTemplate at the same time. They are mutually exclusive. You can read it here This property [i.e. DisplayMemberPath] is a simple way to define a default template that describes how to display the data objects So if you need a specific item template, simply do not set the DisplayMemberPath property of your combobox (there is no need to do it).
unknown
d9022
train
These are one of the soultions how to display current date in textbox: 1. JAVASCRIPT SOLUTION <!DOCTYPE html> <html> <body onload="myFunction()"> Date: <input type="text" id="demo"/> <script> function myFunction() { document.getElementById('demo').value= Date(); } </script> </body> </html> EDIT Instead of value, in the same way by id, you could set the placeholder as you wish: document.getElementById('demo').placeholder= Date(); 2. JQUERY SOLUTION <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> </head> <body onload="myFunction()"> Date: <input type="text" id="demo"/> <script> function myFunction() { $(document).ready(function(){ $('#demo').attr("placeholder", Date()); }); } </script> </body> </html> I think this will help you.
unknown
d9023
train
You can add your variable into the :root selector (like Bootstrap do), and use it with the css function var(). :root { --bg-color: $background-color; --text-color: $text-color; } If you want to get the value using jQuery : jQuery(':root').css('--bg-color'); :root { --bg-color: #f00; --text-color: #0f0; } section { height: 100px; color: var(--text-color); background-color: var(--bg-color); } <section> Lorem ipsum ... </section> A: No, you cannot use sass Variables in Data Attribute directly but there is an indirect way of doing this. In this way also you can change Variable from dark to light, and it will change the color from red to green. But those both should be declared in your data-bg as i did. See this example. [data-bg='dark']{ --text-color: red; } [data-bg='light']{ --text-color: green; } div { color: var(--text-color); } <div data-bg="light"> testing green</div> <div data-bg="dark"> testing red</div> A: An instance of data-bg attribute you can use style attribute to store the variable. In html: <div class="section" style="--data-bg:#ccff00"> and in scss: .section{ $bg: var(--data-bg); width: 200px; height: 200px; background: $bg; }
unknown
d9024
train
Quick reference to another great answer for this question: How to sort NSMutableArray using sortedArrayUsingDescriptors? NSSortDescriptors can be your best friend in these situations :) A: What you have done here is create a list with two elements: [NSNumber numberWithInteger:myValue01] and @"valueLabel01". It seems to me that you wanted to keep records, each with a number and a string? You should first make a class that will contain the number and the string, and then think about sorting. A: Doesn't the sortedArrayUsingComparator: method work for you? Something like: - (NSArray *)sortedArray { return [results sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2) { NSNumber *number1 = [obj1 objectAtIndex:0]; NSNumber *number2 = [obj2 objectAtIndex:0]; return [number1 compare:number2]; }]; }
unknown
d9025
train
You missed ; in first line of data step.
unknown
d9026
train
If the unit takes it's input as PAnsiChar, you're toast. Unless the default code page on your system can encode the Å character, there's simply no way of putting that information into an ANSI CHAR. And if such encoding was available, all of your routines that now show question marks would have shown the proper char. Slightly longer info: Unicode is encoding a vast amount of characters, including all characters in all written languages, special symbols, musical notes, the space is so vast there's encoding for Klingon characters! Ansi chars are encoded using a table lookup that maps the values that can be encoded in one byte to a selection of Unicode chars. When using AnsiString you can only use less then 256 Unicode chars at a time. When you try to encode one Unicode char to one AnsiString you'll essentially doing a lookup in the code page table, looking for a code that points back to the original Unicode char. If no such encoding is available you get the famous question mark! Here's a routine that converts string to UTF8 string and returns it as AnsiString (all UTF8 is actually valid - but meaningless - AnsiString): function Utf8AsAnsiString(s:string):AnsiString; var utf8s:UTF8String; begin utf8s := UTF8String(s); SetLength(Result, Length(utf8s)); if Length(utf8s) > 0 then Move(utf8s[1], Result[1], Length(utf8s)); end; You can pass the result of this function and hope the unit can handle UTF8. Good luck. A: You need an intermediary step to load the char into a string, like so: const ANGSTROM = Chr(0197); procedure ShowAngstrom; var message: AnsiString; begin message := ANGSTROM; ShowMessage(PAnsiChar(message)); end; EDIT: Here's a guess as to what the problem might be if this doesn't work for AggPas. I'm not familiar with AggPas, but I have used the Asphyre graphics library, and its text-drawing system, back in the pre-Unicode days, required you to generate a specialized bitmap by giving it a font file and a range of characters it could print. (Not sure if it's improved since then; I haven't used it in a while.) Any character outside that range wouldn't print properly. If AggPas works in a similar way, it could be that the font image you have doesn't contain anything for character 197, so no matter how correct your Delphi code is, it's got nothing to map to and you're not going to get the right output. See if you can verify this. If not... then I'm out of ideas and I hope someone else here is more familiar with the problem.
unknown
d9027
train
I finally found the solution... it effectively was a problem with the headers, specifically the User-Agent one. I found after lots of searching a guy having the same problem as me with the same site. Although his code was different the important bit was that he set the UserAgent attribute of the request manually to that of a browser. I think I had done this before but I may had done it pretty bad... sorry. The final code if it is of interest to any one is this: public static string Http(string url) { if (url.Length > 0) { Uri myUri = new Uri(url); // Create a 'HttpWebRequest' object for the specified url. HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri); // Set the user agent as if we were a web browser myHttpWebRequest.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4"; HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); var stream = myHttpWebResponse.GetResponseStream(); var reader = new StreamReader(stream); var html = reader.ReadToEnd(); // Release resources of response object. myHttpWebResponse.Close(); return html; } else { return "NO URL"; } } Thank you very much for helping. A: There can be a dozen probable causes for your problem. One of them is that the redirect from the server is pointing to an FTP site, or something like that. It can also being that the server require some headers in the request that you're failing to provide. Check what a browser would send to the site and try to replicate.
unknown
d9028
train
Here's another way to do it, using the WinHttpRequest object: Dim httpRequest As Object Dim url As String Dim i As Long Dim jsonResponse As String Set httpRequest = CreateObject("MSXML2.ServerXMLHTTP") url = "https://gender-api.com/get?name=elizabeth" ' For example httpRequest.Open "POST", url, False httpRequest.send jsonResponse = httpRequest.ResponseText MsgBox jsonResponse
unknown
d9029
train
Try this code, read the comments to understand the code. I hope this code helps you. import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; class main { static String var; // The text input gets stored in this variable public static void main(String args[]) { JFrame frame = new JFrame("Chat Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); JPanel panel = new JPanel(); JLabel label = new JLabel("Enter Base:"); JTextField tf = new JTextField(2); panel.add(label); panel.add(tf); frame.getContentPane().add(BorderLayout.SOUTH, panel); frame.setVisible(true); tf.addActionListener(new ActionListener() { // Action to be performed when "Enter" key is pressed @Override public void actionPerformed(ActionEvent e) { var = tf.getText(); // Getting text input from JTextField(tf) } }); } }
unknown
d9030
train
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 50; } this delegate method for increase the height of your tableview cell. you may try this. A: Go to tableview properties in XIB, check if Separator has been set as 'None'. In that case, you need to set it as 'Single Line' from the drop down .. A: Set property of your tableView from coding yourTableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine; Using xib Or increase your tableView row height (more then your image height) -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 100; }
unknown
d9031
train
I have finally found a workaround for doing exactly what I wanted : * *I have all my different "pages" (they are Wordpress pages, but I use them as different sections on a one-page site) in different files. *Each file has it's own HTML and corresponding logic. *In my index.php file, I call my files this way : require_once(locate_template('tpl-name.php')); I'm pretty sure it's not exactly the best way of doing it, but it works for me. Wish Wordpress would allow API access to it's rendering though.
unknown
d9032
train
You can use the key argument to the sort. In your case, print(sorted(list_of_food, key=lambda k:k[1])) will do the trick. The key function should return an integer, usually. A: You can't sort after outputting to stdout. Well, you shouldn't, since it's heavily complicating a simple task. Instead, you sort the value and print the result: print sorted(my_list_of_food(blah), key=lambda x: x[1]) The part where you were having difficulties is sorting by the second field; that's why that key argument is there - to override the default ordering (which would be the first item of the tuple). To learn more about key functions, check this section on the python Sorting HOW TO If you're still wondering, technically, you could sort the stdout output if you replaced sys.stdout with a wrapper object that buffered the output then sorted and printed it (to the real stdout) periodically, but it's pointless and hard to get right, IMHO. A: If it prints out that way, than either my_list_of_food(blah) returns a string, or it returns a class instance that has a __repr__ method that returns that string... Your best bet is to get data in the actual list format before it becomes a string. If it returns a class instance, get the list and sort on it using key... Otherwise you need to parse the text, so I'll address that part only: # this is assuming the structure is consistent # function to parse a line of the form "('{text}', {int}, {int})" into tuple members using regex import re re_line = re.compile(r"\('(?P<name>\w*)',\s?(?P<int1>\d+)\s?,\s?(?P<int2>\d+)\)") def ParseLine(line): m = re_line.match(line) if m: return (m.group('name'), int(m.group('int1')), int(m.group('int2'))) # otherwise return a tuple of None objects else: return (None, None, None) # final sorted output (as tuples of (str, int, int) ) sorted( [ParseLine(line) for line in my_list_of_food(blah).splitlines()], key = lambda tup: tup[1] ) A: OK: If you really have to do it that way: capture the output of the function in a StringIO object and sort the lines read back from that object. import sys try: from StringIO import StringIO except: from io import StringIO a = [ ('Apples', 4, 4792320), ('Oranges', 2, 2777088), ('Pickles', 3, 4485120), ('Pumpkins', 1, 5074944), ('more stuff', 4545, 345345) ] [Step 1] out = StringIO() # create a StringIO object sys.stdout = out # and redirect stdout to it for item in a : print (item) # print output sys.stdout = sys.__stdout__ # redirect stdout back to normal stdout out.seek(0) # rewind StringIO object s = out.readlines() # and read the lines. [Step 2: define a key function to split the strings at comma, and compare the 2nd field numerically. ] def sortkey(a): return int(a.split(',')[1].strip()) [Step 3: sort and print] s.sort(key=sortkey) for line in s: print (line)
unknown
d9033
train
You can totally do this in NAnt 0.85. Let's say for example you have a property with the name "myvalue" that you want to be able to be passed in from the command line. You would first define the property in your NAnt script like this: <property name="myvalue" value="0" overwrite="false" /> When you call NAnt you just need to use the -D parameter to pass in your new value like this: nant.exe buildfile:myfile.build -logfile:mylog.log -D:myvalue=16 And your new value of "16" will be recognized in your build script which you can test by simply echoing the value like this: <echo message="myvalue: ${myvalue}" /> For further information you can read the documentation and look at example "iv": http://nant.sourceforge.net/release/0.85/help/tasks/property.html A: use unless attribute, it works. <property name="msbuild.path" value="CONFIGURABLE" unless="${property::exists('msbuild.path')}" /> then as usual nant -D:msbuild.path=... A: Need more details, especially if you "change the value of the property" from command line. One thing that I have seen that causes some confusion is that when the property is overridden from command line ( -D:prop=value ), and if the same property is defined in the file (<property name="prop" value="value"/> ) it will say read only property cannot be overridden because the property set from command line is read only and it cannot be overridden by the property defined in the file. It is not the other way around, which causes some confusion and people thinking that despite having no readonly set to true etc. still saying cannot be overridden. So try to see if the property you set is actually using the value you wanted, if you are overriding from command line.
unknown
d9034
train
I think you should reconsider this line: train.MSZoning = pd.get_dummies(train.MSZoning) You are assigning a DataFrame to a Series. Not sure what's going on there but my guess is that is not your intention.
unknown
d9035
train
You can use git filter-branch with the --subdirectory-filter option to filter a subdirectory of your repository and thus make the repository contain the subfolder as root directory. This is described in step 5 here, documentation here might also help. You would have to clone your repository three times and run filter-branch in each of those for a different part of your project. Since (with said --subdirectory-filter) only subdirectories can be treated this way, you may have to rearrange your repository before. The advantage over the naive deletion of other parts is, however, that by using filter-branch you will only preseve history that concerns the actual content of your repository, and do not have any history of the parts filtered out.
unknown
d9036
train
You can create a fetched results controller that fetches SubCategory entities and groups them into sections according to the Category: // Fetch "SubCategory" entities: NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SubCategory"]; // First sort descriptor for grouping the cells into sections, sorted by category name: NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"category.name" ascending:YES]; // Second sort descriptor for sorting the cells within each section: NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]; request.sortDescriptors = [NSArray arrayWithObjects:sort1, sort2, nil]; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:@"category.name" cacheName:nil]; [self.fetchedResultsController setDelegate:self]; NSError *error; BOOL success = [self.fetchedResultsController performFetch:&error]; Then you can use the usual table view data source methods as described in the NSFetchedResultsController Class Reference. This gives you a table view with one table view section for each category. A: so, you have the categories in the fetchedResultsController.fetchedObjects since each subCategory is essentially contained in the Category you can access each by calling [Category valueForKey:@"subCategory" this will give you an NSSet that you can then sort out (to an NSArray) and use as data for your tableView. It won't be contained in a fetchedResultsController though. A: If you have the option u can do it in other way also if u like. Take all The Category objects in arrayOfCategories -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection (NSInteger)section: { Category *cat = [ arrayOfCategories objectAtIndex:indexPath.row] if(arrayToHoldObjects.count > 0) { [arrayToHoldObjects removeAllObject]; } for(Subcategory *sub in Category.subcategory) { [arrayToHoldObjects addObject:sub]; } return arrayToHoldObjects.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { Category *cat = [ arrayOfCategories objectAtIndex:indexPath.row] if(arrayToHoldObjects.count > 0) { [arrayToHoldObjects removeAllObject]; } for(Subcategory *sub in Category.subcategory) { [arrayToHoldObjects addObject:sub]; } Subcategory *sub = [arrayToHoldObjects objectAtIndexPath.row] for(int k =0 ; k < arrayToHoldObjects .count; k++) { // do what ever u like with sub return cell; } }
unknown
d9037
train
If we are talking about calendar months there we have only 12 options (Jan => Dec). Just compile a static table or in the query itself as 12 selects that form a table, and use that to join. select * from (select 1 as m), (select 2 as m), .... (select 12 as m) you might also be interested in the Technics mentioned in other posts : * *How to extract unique days between two timestamps in BigQuery? *Hits per day in Google Big Query A: I'm not sure if this works in bigquery, but this is the structure of a query that does what you want: select org.name, org.code, m.month, sum(s.actual_cost) from org cross join (select month from public.spending group by month) m left join pubic.spending s on s.ord_ig = org.code and s.month = m.month where prescribing_setting = 4 group by org.name, org.code, m.month; A: I would suggested following steps for you to get through: STEP 1 - identify months range (start and finish) month is assumed to be presented in format YYYY-MM-01 if it is in different format - code should be slightly adjusted SELECT MIN(month) as start, MAX(month) as finish FROM public.spending Assume Result of Step 1 is '2014-10-01' as start, '2015-05-01' as finish Step 2 - produce all months in between Start and Finish SELECT DATE(DATE_ADD(TIMESTAMP('2000-01-01'), pos - 1, "MONTH")) AS month FROM ( SELECT ROW_NUMBER() OVER() AS pos, * FROM (FLATTEN(( SELECT SPLIT(RPAD('', 1000, '.'),'') AS h FROM (SELECT NULL)),h ))) nums CROSS JOIN ( SELECT '2014-10-01' AS start, '2015-05-01' AS finish // <<-- Replace with SELECT from Step 1 ) range WHERE pos BETWEEN 1 AND 1000 AND DATE(DATE_ADD(TIMESTAMP('2000-01-01'), pos - 1, "MONTH")) BETWEEN start AND finish So, now - Result of Step 2 is month 2014-10-01 2014-11-01 2014-12-01 2015-01-01 2015-02-01 2015-03-01 2015-04-01 2015-05-01 It has all months, even if some are missed in public.spending table in between start and finish I think the rest is trivial and you have already main code for it. Let me know if this is not accurate and you need help in completing above steps
unknown
d9038
train
It would probably be easier to parse the markup into a tree of Objects and then convert that into MXML. Something like this: var source_code = $("body").html(); var openStartTagRx = /^\s*<div/i; var closeStartTagRx = /^\s*>/i; var closeTagRx = /^\s*<\/div>/i; var attrsRx = new RegExp( '^\\s+' + '(?:(data-type)|([a-z-]+))' + // group 1 is "data-type" group 2 is any attribute '\\=' + '(?:\'|")' + '(.*?)' + // group 3 is the data-type or attribute value '(?:\'|")', 'mi'); function Thing() { this.type = undefined; this.attrs = undefined; this.children = undefined; } Thing.prototype.addAttr = function(key, value) { this.attrs = this.attrs || {}; this.attrs[key] = value; }; Thing.prototype.addChild = function(child) { this.children = this.children || []; this.children.push(child); }; function getErrMsg(expected, str) { return 'Malformed source, expected: ' + expected + '\n"' + str.slice(0,20) + '"'; } function parseElm(str) { var result, elm, childResult; if (!openStartTagRx.test(str)) { return; } elm = new Thing(); str = str.replace(openStartTagRx, ''); // parse attributes result = attrsRx.exec(str); while (result) { if (result[1]) { elm.type = result[3]; } else { elm.addAttr(result[2], result[3]); } str = str.replace(attrsRx, ''); result = attrsRx.exec(str); } // close off that tag if (!closeStartTagRx.test(str)) { throw new Error(getErrMsg('end of opening tag', str)); } str = str.replace(closeStartTagRx, ''); // if it has child tags childResult = parseElm(str); while (childResult) { str = childResult.str; elm.addChild(childResult.elm); childResult = parseElm(str); } // the tag should have a closing tag if (!closeTagRx.test(str)) { throw new Error(getErrMsg('closing tag for the element', str)); } str = str.replace(closeTagRx, ''); return { str: str, elm: elm }; } console.log(parseElm(source_code).elm); jsFiddle This parses the markup you provided into the following: { "type" : "Application" "attrs" : { "id" : "app" }, "children" : [ { "type" : "Label" }, { "type" : "Button" }, { "type" : "VBox" }, { "type" : "Group" } ], } It's recursive, so embedded groups are parsed, too.
unknown
d9039
train
You're running into two issues here: 1) when you create your check-out datepicker is created your dataField is not defined yet (it gets set once you select a data in your check-in datepicker) 2) you are not creating a valid Date - you can access the Date of a datepicker by using $('#check-in').datepicker("getDate") take a look at this fiddle: http://jsfiddle.net/nerL43s5/ to see it in action. $('#check-in').datepicker({ onSelect: function(date) { console.log(date ); // now you have a date you can set as the minDate: $('#check-out').datepicker('option', 'minDate', $('#check-in').datepicker('getDate')); console.log($('#check-out').datepicker('option', 'minDate')); }, altField: '#actual-checkin-date', altFormat: 'mm/dd/yy', dateFormat: 'dd/mm/yy', minDate: 0 });
unknown
d9040
train
RewriteRule ^cn/?(.*)$ en/$1 [L,R=301] This rule alone should work. Match a cn prefix with an optional / and capture all characters after the /.
unknown
d9041
train
Many people (including myself) use _ in front of field names. The reason for this is to easily distinguish them from local variables. However in the ages of IDEs this is not so necessary since syntax highlighting shows this. Using an underscore in front of a class name is just wrong. By convention, class names start with an uppercase letter. A: I think artifacts like these are pre-IDE and C++ vintage. Don't do it. A: A lot of people is it for instance variables as it makes them stand out. Personally I hate it mainly because methods should, for the most part, be no more than 10 lines of code (I hardly ever go over 20). If you cannot see that a variable isn't local in under 10 lines then there is something wrong :-) If you have 100 line methods and you don't declare all your variables at the top of the block that they are used in I can see why you would want to use _ to distinguish them... of course, as with most things, if it hurts then stop doing it! A: It is a matter of personal taste. Martin Fowler appears to like it. I don't care much for it - it breaks the reading pattern, and the information it conveys is already subtly told by color in your IDE. I've experimented with using _ as the name of the variable holding the result to be returned by a method. It is very concise, but I've ended up thinking that the name result is better. So, get your colleagues to agree on what you all like the most and then just do that. A: if you want to follow best practice java , use the code convention outlined here http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html I.e., no underscore for private member variable names. Tho, personally, i m not fussed either way, as long as consistency is applied. A: Using _ before a variable helps in one case where if the developer wants to use a standard/key word as a variable name knowingly or unknowingly. It would not give a conflict if that has an additional character. A: It seems to be a convention that states if an underscore is used as an initial character in the name of method, the method cannot be overridden. For example, in context of JSP, _jspService() method cannot be overridden. However, i dont find any document that states above convention. A: I agree with the others here... It breaks the standard and doesn't really buy you anything if you just use a naming standard. If you need to know the difference between your class and local variables, try a naming convention like lVariableName where the l is used to indicate that it is local. To me this is unnecessary since the IDE highlighting is sufficient, but might be useful to some. A: * *Do not use _ when you use a modern LCD color monitor, with modern IDE like Eclipse, Netbeans, IntelliJ, Android Studio. *Use _ when you need to use a old-style monochrome CRT monitor with only green or white text, or when you have difficulty to identify the color on LCD monitor. *The consensus of your code collaborators overrides the above. A: I am using _ in front of class name, if the class is package private. So in the IDE I have grouped all package private classes on top of the package and I see immediately, that these classes are not accessable from outside of the package.
unknown
d9042
train
From the info you have given, it says that the files are written to m_translator. Once check in your PC in the same directory where you are running your code if there is any folder named m_translator or check in the filepath you have provided while saving the model. Thank You.
unknown
d9043
train
Upto to which I can understand is, you want an auto suggestion functionality for your textbox. You need to do this in the keydown event of the textbox. You can make an AJAX call to get the suggestion.
unknown
d9044
train
Your onclick event handler should successfully handle the click event, but it isn't clear what you want to do with the return value of your function. The browser will not do anything by default. Instead, you need to manage this yourself. For example, you could write the results into some other part of the DOM. In your HTML you can create some nodes to hold the output: <div id="result-1" /> <div id="result-2" /> Then in your event handler: document.getElementById('result-1').innerText = first; document.getElementById('result-2').innerText = second; A: You have a variety of HTML and JavaScript syntax errors. See comments in the code below: // Get references to the DOM elements that you'll work with var btn = document.querySelector("button"); var a = document.getElementById('a'); var b = document.getElementById('b'); var c = document.getElementById('c'); // Do event binding in JavaScript, not with inline HTML attributes btn.addEventListener("click", function(){ // Use "value", not "nodeValue" quEq(a.value, b.value, c.value); }); function quEq(a, b, c) { // Carefull with syntax! var delta = (b * 2) - (4 * a * c); if (a == 0) { // return doesn't show up anywhere alert("Not a quadratic equation"); } else if (delta < 0) { alert("Complex root! No solution in real numbers"); } else { var first= (-b + Math.sqrt(delta)) / (2*a); var second= (-b - Math.sqrt(delta)) / (2*a); alert(first + " " + second); } } <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="index.js"></script> <title>Quadratic Equation</title> </head> <body> <div class="container"> <div class="row justify-content-center"> <div class="bg-red-400"> <div class=""> <form> <div class="form-group"> <label for="a">Enter 'a' value</label> <input type="number" class="form-control" id="a" placeholder="1"> <label for="b">Enter 'b' value</label> <input type="number" class="form-control" id="b" placeholder="5"> <label for="c">Enter 'c' value</label> <input type="number" class="form-control" id="c" placeholder="6"> <button type="button" class="btn btn-primary">Submit</button> </div> <!-- The followng line doesn't have a closing tag and so is invalid. --> <!-- <div class="form-group"> --> </form> </div> </div> </div> </div> </body> </html> A: I see two flaws in this code 1) document.getElementById('a').nodeValue instead of document.getElementById('a').value 2) you should be aware that placeholder is just a text, it seems strange that you can see 6 but there's no number yet, so instead of placeholder set value attribute directly if you want some default numbers <input type="number" class="form-control" id="a" value="1"> A: Now its working a: <input type="number" name="a" id="a"><br> b: <input type="number" name="b" id="b"><br> c: <input type="number" name="c" id="c"><br> <button onclick="quEq(document.getElementById('a').value,document.getElementById('b').value,document.getElementById('c').value)">Submit</button> <script> function quEq(a, b, c) { var delta = (b ** 2) - (4 * a * c); if (a == 0) { alert("Not a quadratic equation"); }; if (delta < 0) { alert("Complex root! No solution in real numbers"); } else { var first= (-b + Math.sqrt(delta)) / (2*a); var second= (-b - Math.sqrt(delta)) / (2*a); alert(first, second); }; }; </script> </body> A: There are a couple of things in your index.html file that are not correct, for example, you opened a second div with a class "form-group" yet you did not close it, also you did not pass properly the value for "a" (.nodeValue when it should be .value). I made some changes to your code and appended the response in the div you weren't using (the second "form-group") and changed it's name, also I added type="button" to your button so it won't submit as soon as you click on it, you can find the html and js in codepen Here is your function: function quEq() { var a = document.getElementById('a').value var b = document.getElementById('b').value var c = document.getElementById('c').value var delta = (b ** 2) - (4 * a * c) if (a == 0) { document.getElementsByClassName("info")[0].innerHTML = "Not a quadratic equation" } if (delta < 0) { document.getElementsByClassName("info")[0].innerHTML = "Complex root! No solution in real numbers" } else { var first= (-b + Math.sqrt(delta)) / (2*a) var second= (-b - Math.sqrt(delta)) / (2*a); document.getElementsByClassName("info")[0].innerHTML = first + ", " + second } } Here is your div changed: <div class="container"> <div class="row justify-content-center"> <div class="bg-red-400"> <div> <form> <div class="form-group"> <label>Enter 'a' value</label> <input type="number" class="form-control" id="a" placeholder="1" value="1"/> <label>Enter 'b' value</label> <input type="number" class="form-control" id="b" placeholder="5" value="5" /> <label>Enter 'c' value</label> <input type="number" class="form-control" id="c" placeholder="6" value="6" /> <button onclick="quEq()" type="button" class="btn btn-primary">Submit</button> </div> <div class="info"></div> </form> </div> </div> </div> </div>
unknown
d9045
train
If you draw to paths and fill them using Even Odd (EO) fill, that should get you what you want (fill the inner part). Default fill on OSX (and iPhone) is non zero winding (NZW) fill You could probably get the same effect using non zero winding too, by changing the winding of the different parts accordingly (the 'clockwise' parameter), but using even odd will be much simpler.
unknown
d9046
train
You try to find a product through the quantity. but "find" expects a primary key Instead of: @quantity = Product.find(params[:quantity]) try this: @quantity = product.quantity UPDATE: def add_to_cart product = Product.find(params[:id]) @cart = find_cart @current_item = @cart.add_product(product) product.decrement!(:quantity, params[:quantity]) respond_to do |format| format.js if request.xhr? format.html {redirect_to_index} end rescue ActiveRecord::RecordNotFound logger.error("Product not found #{params[:id]}") redirect_to_index("invalid product!") end
unknown
d9047
train
You can do it by exposing the ListView public, but don't do that. Instead expose a property in Form for selected items. class Form1 : Form { public ListView.SelectedListViewItemCollection ListViewSelectedItems { get { return yourListView.SelectedItems; } } } class Form2 : Form { public void SomeMethod() { Form1 myForm1Instance = ...;//Get instance somehow var items = myForm1Instance.ListViewSelectedItems;//Use it foreach (var item in items) { //Do whatever } } } A: You would have to either have a reference to Form1 in Form2 and have the DataVisualizationList be publicly accessable, or have a reference to DataVisualizationList in Form2. You could to this with member references. You would have to set the reference of Form1 in Form2. Something like this inside Form1 private void button1_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.f1 = this; f2.Show(); } And then inside Form2 public partial class Form2 : Form { public Form1 f1; public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (f1 != null) { foreach (ListViewItem dr in f1.DataVisualizationList.SelectedItems) { } } } } A: Simplest Solution on Form1 list<your_Type> li = ListView1.items.ToList() Form2 frm = new Form2(li); Frm.Show(); on Form2 list<your_Type> li2; Form2(List<your_Type> li) { InitializeComponent(); li2 = li; }
unknown
d9048
train
Another variation, for fun and profit, demonstrating the FOR XML trick to concatenate values pre-SQL Server 2012. SELECT Customer_Number, STUFF( (SELECT ',' + order1, ',' + order2, ',' + order3, ',' + order4 FOR XML PATH('')), 1, 1, '' ) This is slight overkill for a constant number of columns (and not particularly efficient), but an easy to remember pattern for concatenation. Also, it shows off STUFF, a function any SQL developer should learn to love. A: Example Declare @YourTable Table ([Customer_Number] varchar(50),[order1] varchar(50),[order2] varchar(50),[order3] varchar(50),[order4] varchar(50)) Insert Into @YourTable Values (1,NULL,'X','Y',NULL) ,(2,NULL,'A','B',NULL) ,(3,'V',NULL,'H',NULL) Select Customer_Number ,[Order] = IsNull(stuff( IsNull(','+order1,'') +IsNull(','+order2,'') +IsNull(','+order3,'') +IsNull(','+order4,'') ,1,1,''),'') From @YourTable Returns Customer_Number Order 1 X,Y 2 A,B 3 V,H EDIT - IF the "NULL" are strings and NOT NULL Values Declare @YourTable Table ([Customer_Number] varchar(50),[order1] varchar(50),[order2] varchar(50),[order3] varchar(50),[order4] varchar(50)) Insert Into @YourTable Values (1,'NULL','X','Y','NULL') ,(2,'NULL','A','B','NULL') ,(3,'V','NULL','H','NULL') Select Customer_Number ,[Order] = IsNull(stuff( IsNull(','+nullif(order1,'NULL'),'') +IsNull(','+nullif(order2,'NULL'),'') +IsNull(','+nullif(order3,'NULL'),'') +IsNull(','+nullif(order4,'NULL'),'') ,1,1,''),'') From @YourTable A: This is a bit unpleasant, it needs to be in a subquery to remove the trailing comma efficiently (though you could use a CTE): SELECT Customer_number, SUBSTRING([Order], 0, LEN([Order])) AS [Order] FROM( SELECT Customer_number, COALESCE(order1+',', '') + COALESCE(order2+',', '') + COALESCE(order3+',', '') + COALESCE(order4+',', '') AS [Order] FROM OrderTable) AS SubQuery A: You were on the right track with the Coalesce, or IsNull. Instead of trying to track the length and use substring, left or stuff, I just used a replace to remove the trailing comma that would show up from the coalesce. Select Customer_number, Replace( Coalesce(Order1 + ',','')+ Coalesce(Order2 + ',','')+ Coalesce(Order3 + ',','')+ Coalesce(Order4 + ',','') +',',',,','') --Hack to remove the Last Comma as [Order] from Ordertable
unknown
d9049
train
I was having a similar issue and found a fix via: https://github.com/expo/expo/issues/7155#issuecomment-592681861 Seems like the act() worked magically for me to stop it from returning null (not sure how) Update your test to use it like this: import { act, create } from 'react-test-renderer'; it('renders the root without loading screen', () => { let tree; act(() => { tree = create( <PaperProvider theme={theme}> <App skipLoadingScreen></App> </PaperProvider> ); }); expect(tree.toJSON()).toMatchSnapshot(); }); Note: When I changed how I was using the imports from 'react-test-renderer' my tests couldn't find act() as a function, a simple re-install of npm packages solved this problem!
unknown
d9050
train
One you've assigned srg you can use Match() to check whether it contains any instances of the term you're interested in: '... '... ' Define worksheet and column am working on and getting the range of last used cell using(LastRow) With wb.Worksheets(srcName).Range(srcFirst) LastRow = .Offset(.Worksheet.Rows.Count - .Row).End(xlUp).Row Set srg = .Resize(LastRow - .Row + 1, 10) End With 'Exit if "BOND INSURANCE" is not found in `srg` If IsError(Application.Match("BOND INSURANCE", srg, 0)) Then Exit Sub '... '...
unknown
d9051
train
Step through it in order. First, due to hoisting, the variables firstName, lastName, age are declared, and the function happyBirthdayLocal is also declared. Then, firstName, lastName, age are all assigned their values. Next you call console.log(message);. Uh-oh, message hasn't been defined yet. That doesn't happen until happyBirthdayLocal is actually called for the first time, which would be on the following line. Due to the error, which is fatal, the function is never called, and message remains undefined.
unknown
d9052
train
SELECT post_id FROM `database_table` WHERE `meta_value` REGEXP '<date[1|2|3]>[0-9]+<\/date[1|2|3]>' I think this will do the trick =) Good luck!
unknown
d9053
train
Looks like "Diet" only has one degree of freedom in the statsmodels call which means it was probably treated as a continuous variable whereas in R it has 3 degrees of freedom so it probably was a factor/discrete random variable. To make ols() treat "Diet" as a categorical random variable, use cw_lm=ols('weight ~ C(Diet) + Time', data=cw).fit()
unknown
d9054
train
Try to use sudo command. sudo pip install cython
unknown
d9055
train
This usually happens with apps with lots of dependencies so they take too long to launch, making the debugger to abort and time out. A temporary solution would be: * *Create (or edit in case you already have) a .lldbinit file in your home directory. vim ~/.lldbinit. *Add this to the end of file: settings set plugin.process.gdb-remote.packet-timeout 300. *Restart Xcode and try again. A: I have tried this way and it is working like uncheck debug executable option. Choose Edit Schema->Info->uncheck Debug executable
unknown
d9056
train
Have you tried calling the AddSeries() method twice, once for each database?
unknown
d9057
train
Well, i solved it. It seems to happen only when i'm loading the images via the XML method, if i load them with a 3rd party library like Picasso, the lag seems to dissapear. Something like : Picasso.with(context).load(MovieDetails.getPoster()) .error(R.drawable.placeholder) .placeholder(R.drawable.placeholder) .into(movieViewHolder.imageViewPoster); inside the onBindViewHolder and instead of passing around bitmaps, just pass a String for the URL or location of the image. And pass the Context to the Adapter class.
unknown
d9058
train
Figured it out, I had to add an image tag and then it worked fine. However, there are other PHP files in the site, where <?php the_sub_field('image'); ?> displays the image, but in this particular case I had to write it as <img src="<?php echo esc_url($image['url']); ?>"/> Still trying to understand how this works.
unknown
d9059
train
Yes just use the flex property. Example: column1 flex: 1 column2: flex: 1 |-----Column 1-----|-----Column 2-----| column1 flex: 2 column2: flex: 1 |--------Column 1--------|--Column 2--|
unknown
d9060
train
You can use this: x = '45 is fourth five 45 when 9 and 5 are multiplied' string = re.sub(r'(?<!^)\b\d+\s', '', x) Result: >>> print(string) 45 is fourth five when and are multiplied A: Using Pypi regex library, you can do: import regex x = '45 is fourth five 45 when 9 and 5 are multiplied' print regex.sub(r'(?<=\D*\d+\D+)\d+ ?', '', x) Output: 45 is fourth five when and are multiplied Explanation: (?<= # positive lookbehind, make sure we have before: \D* # 0 or more non digits \d+ # 1 or more digits \D+ # 1 or more non digits ) # end lookbehind \d+ # 1 or more digits ? # optional space
unknown
d9061
train
If I'm reading the question correctly, you have a CSV file you're splitting on , and some of the "values" you're looking for also have a , in them and you don't want it to split on the , in the value... Sorry, but it's not going to work. String.Split does not have any overrides, or regex matching. Your best bet is to sanitize your data first by removing the , from the values, or ensuring the , separating your values matches differently than the , in the values. For example... 12,345 , 23,1566 , 111 , 1 you can split the above on " , " instead of just "," and since the pattern of " , " is consistent, then it will work Alternately, you could open your csv in Excel and save it as a Tab delimited text file and then split on the tab "/t" character
unknown
d9062
train
Do you have duplicate android:id tags in any of those three activities? I've read that such a situation could cause an issue. Ah, here's the link to where I read that: ClassCastException
unknown
d9063
train
I was unable to get it to work with FAT32 so I reformatted my thumb-drive to ext4. Then I created a directory to mount the usb to using: mkdir /media/usb and then editing the etc/fstab and adding to the bottom of the file (where xxxx-xxxx-xxxx is the UUID of the partition of the drive you are using): UUID=xxxx-xxxx-xxxx /path/to/usb ext4 defaults 0 0 /path/to/usb /var/www/html/media/ none bind 0 0 I also found that I had to give permissions to write to my usb using: sudo chown www-data:www-data /path/to/usb
unknown
d9064
train
Update Sep 28,2016 It looks like there is now an open-source library for doing just this: https://github.com/fiffty/react-treeview-mui Self Implementation This answer serves as an example for an Accordion dropdown built using React, though not styled as Material Design. You would need to do that yourself. This setup requires a hierarchy object of parent > child objects/arrays. This base class should be able to handle very deep depths just fine. It uses recursion for its structure setup. I'll also be using ES6 syntax for preference, as it helps setup the recursion easier for me. Accordion Class: // Accordian Class // Dynamic/Recursive // a parent>child>child... relationship is required // the whole object can be named however you like, // but each child object needs to be identified as "children" class Accordian extends React.Component { constructor(props) { super(props); this.state = { openLevelRow: "", // this is the current open level row in an accordian (starts out with none being open) selfLevelObject: props.newLevel // the current level object containing all rows and their data/children }; } // This is our toggle open/close method // if row is already open, close it // uniqueSelector is unique per row, and also a key // in the selfLevelObject (could be a name, id) toggleOpenClose(uniqueSelector) { // simple ternary assignment this.setState({ openLevelRow: this.state.openLevelRow != uniqueSelector ? uniqueSelector : "" }); } render () { // deconstruct assignment from state const { selfLevelObject, openLevelRow } = this.state return ( <div> {selfLevelObject.map((row, i) => {/* Collectively where all children of the same hierchy level are listed*/} <div className="accordian-hold-self-level" key={i} > {/* This is an individual collapsable Row */} <div onClick={this.toggleOpenClose.bind(this, row.uniqueSelector)} className="accordian-title-row"> <p className='accordian-title'> {row.title}</p> </div> {/* When iterating the list, find out if a row has been opened */} {this.state.openLevelRow != row.uniqueSelector ? <span></span> : /* This code block is called if the current row is opened now we to need to find out if there are children, if not, then we are at the bottom, do what ever you'd like with the bottom row */ selfLevelObject[uniqueSelector].children != undefined ? <Accordian newLevel={selfLevelObject[uniqueSelector].children} /> : // else // TODO - whatever you want with bottom row } </div> )} </div> ); } } Accordian.propTypes = { newLevel: React.PropTypes.object }
unknown
d9065
train
So the simple answer to fix your issue is that when install the Selenium.WebDriver Nuget Package make sure its on version 3.11.2 as PhantomJS driver classes were removed in 3.14 (Had the exact same problem) as is no longer maintained. A: The .NET language bindings marked the PhantomJS driver classes deprecated in 3.11, and those classes were removed in 3.14. The PhantomJS project and its driver are no longer being maintained, and the driver code has not (and will not) be updated to support the W3C WebDriver Specification. The preferred “headless” solution is to use Chrome or Firefox in headless mode, as both of those browsers and their drivers support such an operating mode. Alternatively, if you have your heart set on PhantomJS, and you don’t care about cross-browser execution, you can simply use the PhantomJS executable and automate it through its internal JavaScript API.
unknown
d9066
train
I found the solution to the problem. The solution came when I ignored much of what I found on StackOverflow and instead opted just to use the Django docs. I had my code written as it is in my OP -- see how it makes headers out of new Headers()? And how the fetch has serverUrl plugged in as the first argument? Well, I changed it so that it reads like this: const serverUrl = "http://127.0.0.1:8000/" const request = new Request(serverUrl, { headers: { 'X-CSRFToken': getCookie("csrftoken") } }) fetch(request, { method: "POST", mode: "same-origin", body: JSON.stringify(editorState.expirationDate, editorState.contracts, editorState.theta) }).then(response => { console.log(response) }).catch(err => { console.log(err) }); And it worked! The difference was using the new Request() object in the fetch argument.
unknown
d9067
train
It's a bug. Previously only the <a> was allowed as a clickable child element. Icon support was a recent addition. Please see issue and pull request, Selectlist is empty when icon is clicked instead of text label This should be merged into master with release 3.0.3.
unknown
d9068
train
Ordinary function calls are not pushed on the event queue, they're just executed synchronously. Certain built-in functions initiate asynchronous operations. For instance, setTimeout() creates a timer that will execute the function asynchronously at a future time. fetch() starts an AJAX request, and returns a promise that will resolve when the response is received. addEventListener() creates a listener that will call the function when the specified event occurs on an element. In all these cases, what effectively happens is that the callback function is added to the event queue when the corresponding condition is reached. When one of these functions is called, it runs to completion. When the function returns, the event loop pulls the next item off the event queue and runs its callback, and so on. If the event queue is empty, the event loop just idles until something is added. So when you're just starting at a simple web page, nothing may happen until you click on something that has an event listener, then its listener function will run. In interactive applications like web pages, we try to avoid writing functions that take a long time to run to completion, because it blocks the user interface (other asynchronous actions can't interrupt it). So if you're going to read a large file, you use an API that reads it incrementally, calling an event listener for each block. That will allow other functions to run between processing of each block. There's nothing specific that identifies asynchronous functions, it's just part of the definition of each function. You can't say that any function that has a callback argument is asynchronous, because functions like Array.forEach() are synchronous. And promises don't make something asychronous -- you can create a promise that resolves synchronously, although there's not usually a point to it (but you might do this as a stub when the caller expects a promise in the general case). The keyword async before a function definition just wraps its return value in a promise, it doesn't actually make it run asynchronously.
unknown
d9069
train
Here is an example on how to read the queue length in rabbitMQ for a given queue: def get_rabbitmq_queue_length(q): from pyrabbit.api import Client from pyrabbit.http import HTTPError count = 0 try: cl = Client('localhost:15672', 'guest', 'guest') if cl.is_alive(): count = cl.get_queue_depth('/', q) except HTTPError as e: print "Exception: Could not establish to rabbitmq http api: " + str(e) + " Check for port, proxy, username/pass configuration errors" raise return count This is using pyrabbit as previously suggested by Philip A: PyRabbit is probably what you are looking for, it is a Python interface to the RabbitMQ management interface API. It will allow you to query for queues and their current message counts. A: You can inspect the workers in celery by using inspect module. Here is the guide. Also for RabbitMQ there are some command line command.
unknown
d9070
train
<select> tag should contain the value. In your case it is the state: taskTitle. Onchange should also be under select. In your code you use this useState: const [taskTitle, setTaskTitle] = useState(""); So try to change the select to this: <select value={taskTitle} onChange={(e) => setTaskTitle(e.target.value)}> {categories && categories.map((category, i) => ( <option key={i} label={category.categoryName} value={category._id} name={category.categoryName} category={category} > {category.categoryName} </option> ))} </select>
unknown
d9071
train
Keep the class skill-bar-fill and use style binding : <div class="w-100 skill-bar"> <div class=" skill-bar-fill" :style="{width:programming.item1+'%'}"> {{ programming.item1}} %</div> </div> You couldn't modify a property of that class since it's not unique and each item is unique. A: This answer is based on original question. Your requirement has been simplified so your solution is fine and below is probably not required For the first instance, you could use a CSS variable for the width attribute, and programatically change the variable. For subsequence instances, this won't work by itself because they share the CSS so for those you'd need an object style syntax. Pass a property to the first child so it knows it's the first one and it needs to set the variable Setting CSS variable in Vue: Add var into css class For subsequent children use object syntax: https://v2.vuejs.org/v2/guide/class-and-style.html#Object-Syntax-1 It's not clear to me why you the width of divs needs to reference the first uncle - what if the second skill is higher than the first? - but the above might be the answer.
unknown
d9072
train
I dont tested it but you could do something like public function postTags() { return $this->hasManyThrough(Tag::class, Post::class, 'taggable_id')->where('taggable_type', array_search(static::class, Relation::morphMap()) ?: static::class); } This is a normal hasManyThrough and you have to build the polymorphic logic by your self. To Explain your query public function tags() { $posts = $this->posts() ->pluck('id'); // The use of Tag::whereHas returns a Illuminate/Database/Eloquent/Query not an relation like HasMany, HasOne or like in your case a HasManyThrough return Tag::whereHas('posts', function(Builder $query) use ($posts) { $query->whereIn('taggable_id', $posts); }) ->get(); // The get at the end sends the query to your database, so you receive a collection } A: I understand your problem here I have Same type of database relation. In my Category_model table I am storing * *category_id *model_type *model_id Inside the Category model I have following code : public function article() { return $this->morphedByMany(Article::class, 'model', 'category_model', 'category_id'); } and inside controller : // Show posts by Category public function ShowArticleByCategory($category) { $cat = Category::where('name', $category)->firstOrFail(); $posts = $cat->article()->get()->sortByDesc('id'); return view('front.pages.show-by-category', compact('posts')); } This will give me all the posts that belongs selected/Supplied Category. Hope this help you will get the idea of getting data from polymorphic relations. All the parameters tha can be passed inside the relations are defined inside vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasRelationships.php
unknown
d9073
train
jQuery doesn't draw things. You could do this using CSS + HTML only. Here is a cool tutorial showing one way it could be done: http://jtauber.github.com/articles/css-hexagon.html Note: HTML / CSS may not be ideal for all situations. It might be better to look at using SVG instead. A: My best recommendation would to be use either SVG or canvas. One example of a good SVG library is raphaeljs, check it out: http://raphaeljs.com/ http://raphaeljs.com/animation.html For canvas its quite simple to make shapes https://developer.mozilla.org/en-US/docs/HTML/Canvas/Tutorial/Drawing_shapes
unknown
d9074
train
pygame.mouse.get_pressed() get the current state of the mouse buttons. The state of the buttons may have been changed, since the mouse event occurred. Note that the events are stored in a queue and you will receive the stored events later in the application by pygame.event.get(). Meanwhile the state of the button may have been changed because of this he button which causes the MOUSEBUTTONDOWN event is stored in the button attribute of the pygame.event.Event object immediately. In the event loop, whn you get the event the state of event.button and pygame.mouse.get_pressed() may be different. The same goes for pygame.mouse.get_pos(). The position of the mouse is stored in the attribute pos Use event.button and event.pos rather than pygame.mouse.get_pressed() and pygame.mouse.get_pos(): while running: for event in pg.event.get(): if event.type == pg.MOUSEBUTTONDOWN: print(event.button) if grid_space.get_rect(topleft=(adj_x, adj_y)).collidepoint(event.pos): if event.button == 2: do_thing() elif event.button == 4: do_thing() elif event.button == 5: do_thing() else: do_thing() pygame.mouse.get_pos() and pygame.mouse.get_pressed() are not intended to be used in the event loop. The functions should be used directly in the application loop.
unknown
d9075
train
Given you want the predecessor to node N in an in-order traversal sense, there are three possibilities: * *N has a left child. In this case, the predecessor is the rightmost element of N's left subtree. *N does not have a left child, and there is at least one rightward step in the path from the root to N. In this case, the predecessor is the source node of the rightward step nearest to N on that path. *N does not have a left child, and there are no rightward steps along the path to it from the root. In this case, N is the minimum element in the tree, so it has no predecessor. What you must do, therefore, is track the source of the most recent rightward step (not necessarily the immediate parent) as an additional parameter to the recursive search function by which you find node N. When you reach N, you will then have that ready to use in the event that N has no left child, and you can ignore it if N does have a left child.
unknown
d9076
train
why [...] this class defines two GetEnumerator methods: Well, one is generic, the other is not. The non-generic version is a relic from .NET v1, before generics. You have class FormattedAddresses : IEnumerable<string> but IEnumerable<T> derives from the old interface IEnumerable. So it effectively is class FormattedAddresses : IEnumerable<string>, IEnumerable and your class has to implement both. The two methods differ in their return Type so overloading or overriding are not applicable. Note that the legacy version is implemented 'explicitly', hiding it as much as possible and it is often acceptable to not implement it: System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new NotImplemented(); } Only in a full blown library class (as opposed to an application class) would you bother to make it actually work. A: The second method implements the non-generic version of the method. Its an explicit interface implementation to avoid a name conflict (overloads cannot differ only by return type). The whole class should be deleted anyway. Hold a list of FormattedAddress, don't make a custom List class for it!
unknown
d9077
train
Instead of background-repeat-x: no-repeat; background-repeat-y: no-repeat; which is not correct, use background-repeat: no-repeat; A: Try this padding:8px; overflow: hidden; zoom: 1; text-align: left; font-size: 13px; font-family: "Trebuchet MS",Arial,Sans; line-height: 24px; color: black; border-bottom: solid 1px #BBB; background:url('images/checked.gif') white no-repeat; This is full css.. Why you use padding:0 8px, then override it with paddings? This is what you need... A: This is all you need: background-repeat: no-repeat; A: body { background: url(images/image_name.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } Here is a good solution to get your image to cover the full area of the web app perfectly
unknown
d9078
train
It's because classes have higher specificity value than Elements and Pseudo Elements. In your case .top-menu have higher specificity than the element ul, therefore its style is followed/used. Refer to this table for specificity: More on specificity here.
unknown
d9079
train
Addressing two topics here: * *The error you saw at the beginning: kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead. Means that you tried to use a deprecated version of the kubectl exec command. The proper syntax is: $ kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...] See here for more details. *According the the official docs the gpu-operator-test pod should run to completion: You can see that the pod's status is Succeeded and also: State: Terminated Reason: Completed Exit Code: 0 Exit Code: 0 means that the specified container command completed successfully. More details can be found in the official docs.
unknown
d9080
train
For the positioning of your link under the image, you'd have to work on your CSS. For proper working of the code sample, make following changes: * *Update RANDOM_IMAGES_FORMAT to define('RANDOM_IMAGES_FORMAT', '<img src="%s" /><a href="%s" alt="%s" title="%s" style="margin-right:10px">Click Me</a>'); *Change the array to: $images = array ( array ( 'title' => 'Test 2', 'src' => 'pic2.jpg', 'href' => 'http://mylink.com/path/' ), array ( 'title' => 'Test 3', 'src' => 'pic3.jpg', 'href' => 'http://mylink.com/path/' ), array ( 'title' => 'Test 4', 'src' => 'pic4.jpg', 'href' => 'http://mylink.com/path/' ) ); *Use printf like this: printf( RANDOM_IMAGES_FORMAT, $tmp['src'], $tmp['href'], $tmp['title'], $tmp['title'] ); A: Your code have multiple issues: Constant RANDOM_IMAGES_FORMAT is poorly formatted as HTML it should look like: define('RANDOM_IMAGES_FORMAT', '<img src="%s" alt="%s" title="%3$s" style="margin-right:10px"><a href="%s"></a>'); As for that, the order of printf arguments should be reordered, because we have modified displaying them in RANDOM_IMAGES_FORMAT: printf( RANDOM_IMAGES_FORMAT, $tmp['src'],$tmp['href'], $tmp['title'] ); In your $images array, links should be only URL, not full links, as you defined then already in RANDOM_IMAGES_FORMAT. Full code you presented should look like this: define('RANDOM_IMAGES_COUNT', 3); define('RANDOM_IMAGES_FORMAT', '<img src="%s" alt="%s" title="%3$s" style="margin-right:10px"><a href="%s"></a>'); $images = array ( array ( 'title' => 'Test 2', 'src' => 'pic2.jpg', 'href' => 'http://mylink.com/path/' ), array ( 'title' => 'Test 3', 'src' => 'pic3.jpg', 'href' => 'http://mylink.com/path/' ), array ( 'title' => 'Test 4', 'src' => 'pic4.jpg', 'href' => 'http://mylink.com/path/' ) ); if ( count($images) < RANDOM_IMAGES_COUNT ) { trigger_error('Not enough images given', E_USER_WARNING); exit; } for ($i = 0; $i < RANDOM_IMAGES_COUNT; $i++) { shuffle($images); $tmp = array_shift($images); printf( RANDOM_IMAGES_FORMAT, $tmp['src'],$tmp['href'], $tmp['title'] ); } A: <img src="%s"><a href="%s"> alt="%s" title="%3$s" style="margin-right:10px"></a> do not close the tag a after href="%s" and put img inside of a tag, like this: <a><img/></a> A: Check define('RANDOM_IMAGES_FORMAT', '<img src="%s"><a href="%s"> alt="%s" title="%3$s" style="margin-right:10px"></a>'); and array ( 'title' => 'Test 2', 'src' => 'pic2.jpg', 'href' => '<a href=http://mylink.com/path/>Click Me</a>' ), their is a problem with href try to give only link in href
unknown
d9081
train
I think this is a Security issue. There are specific security privileges required to act on behalf of or send emails on behalf of other users. These privileges are on the Business Management tab in the Security Role. In addition to this, the impersonated user must have also authorised emails to be sent on their behalf. This setting is located in the the impersonated users personal settings
unknown
d9082
train
Here is a work around: link to an approved solution it provides a java implementation, and they point out it is more about the version of the library you are using. hopefully it helps.
unknown
d9083
train
Your main problem is that 0xFFFFFFFF is indeed a NaN. A float with a value of 0 is... 0. Changing the array to int[] arry = { 0x00, 0x00, 0x00, 0x00 }; Will change the resulting value to a 0.0f float. A: Well, your bit pattern happens to actually be NaN: IEEE 754 NaNs are represented with the exponential field filled with ones and some non-zero number in the significand. A bit-wise example of a IEEE floating-point standard single precision NaN: x111 1111 1axx xxxx xxxx xxxx xxxx xxxx where x means don't care. If a = 1, it is a quiet NaN, otherwise it is a signalling NaN. Since all your bits are 1, it obviously fits above criteria and is a quiet NaN (although Java iirc doesn't even support quiet or signalling NaNs). A: NaN = Not a Number, iaw, the bit pattern 0xFFFFFFFF does not represent a float value number. (Joachim, you're right .. again :-) )
unknown
d9084
train
You are using a RelativeLayout with too many Views to fit the screen. Either you want to use ConstraintLayout to set the Views in a direct relation to each other or you put a ScrollView around your root layout. Either case there is only so much space to fill.
unknown
d9085
train
in the load-failed callback you need to remove the "setAsHome": g_action_map_remove_action(G_ACTION_MAP (w->app), "setAsHome" the load failed signal also emits when there is a failure and you would be redirectet to an error message page. Keep in mind that your load-change signal will be emitted 2 times once because the url can't be loaded and than to load the error page. In order to pake it "sensitive" again, you need to add it to your menu again.
unknown
d9086
train
Use a subquery to get rid of the duplicates in table a. SELECT SUM(man+woman) AS over65, a.cod, a.city, b.cod2 FROM (SELECT DISTINCT cod, city FROM a) AS a LEFT JOIN b ON b.cod2 = a.cod GROUP BY a.cod I also wonder why table a has those duplicates in the first place. If city is always the same for a given cod, the data is not properly normalized.
unknown
d9087
train
For uncompressed CSV files with 1 million records expect around 10-15 seconds of processing time. But the question to put here is where the file is stored, and how long it will be taken to be uploaded, as that can be more than the above time section. We have successfully imported in 2 minutes CSV files up to 5TB of data in it. Your project can run up to 100,000 load jobs per day. Failed load jobs count toward this limit. But be aware: Your project can make up to 5,000 partition modifications per day to an ingestion-time partitioned table. Your project can make up to 30,000 partition modifications per day for a column-partitioned table. Your project can run up to 50 modifications per partitioned table every 10 seconds. You can have multiple load jobs in parallel. BigQuery is really petabyte scaling, so large jobs fit nice. Although it has some Quotas, but they are quite decent, see them here.
unknown
d9088
train
There are actually quite a few ways to do this. * *As @Badri suggested, you can use the Request object directly in your actions. This is a very straightforward and simple approach but mixes controller logic with formatting/binding logic. If you want to create a better separation of concerns, try one of the following. *There are a number of parameter binding mechanisms you can choose from. Looks to me like a custom model binder could work well in this case. You can access the Request object in the model binder and use something similar to @Badri's code to set up the values you expect (String.Empty or null) before they get passed to your action. *A value provider for the birthdate field might be a better option. You're passing a string that can ultimately be converted to a DateTime object. If you specify that that parameter should use a custom value provider (such as an IntuitiveDateTimeValueProvider), you can actually change the type of the parameter in your action to DateTime or Nullable<DateTime> (DateTime?) and let the value provider fill the value appropriately. You can also use a similar strategy for simpler strings for which you want to differentiate between empty and null (e.g., ExistenceTestingStringValueProvider). *Create additional routes/actions. This isn't a good option if there are a lot of parameters because there are just too many possible combinations, but if there are just a few, this is a very simple solution. One way to do this is to simply create method overloads for each combination. If an overload that only has name is hit, it means birthdate wasn't specified, but if an overload with both parameters was hit, it means that birthdate was specified, even if its value is null, giving you a way to distinguish between specified but empty parameter values and unspecified parameter values. A: If you use ASP.NET Web API binding, it is not possible. Say, you have a DTO class and use it for binding like this. public class MyDto { public string Name { get; set; } public string BirthDate { get; set; } } public void Update([FromUri]MyDto dto) { } When you leave out BirthDate or have it in the query string with an empty value, it is basically the same and BirthDate property will be null in both cases. However, you can read the query string yourself like this. string qs = Request.RequestUri.Query.Substring(1); // leave out ? var pairs = System.Web.HttpUtility.ParseQueryString(qs); In this case, pairs["BirthDate"] will be null, if you leave out the field from the query string (?name=Sherlock). If you have it in the query string with an empty value (?birthdate=&name=Sherlock), then pairs["BirthDate"] will be empty string ("").
unknown
d9089
train
Try running geany with sudo geany.
unknown
d9090
train
It's a bug. You can quickly solve it by adding, after the line: [self.tableView moveRowAtIndexPath:indexPath toIndexPath:newPath]; this lines: UIView *sectionView = [self.tableView headerViewForSection:indexPath.section]; [self.tableView bringSubviewToFront:sectionView]; A: Not a solution but your code has number of issues. Who knows what happens if you fix them ;) (1) Your cell may be nil after this line: ListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; It should look like this: ListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[ListCell alloc] initWithStyle:style reuseIdentifier:cellIdentifier] autorelease]; } (2) Two memory leaks in -(UIView *)tableView:(UITableView *)aTableView viewForHeaderInSection:(NSInteger)section ->>Fix (When you add the label as subview it gets +1 ref). UILabel *textLabel = [[[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 21)] autorelease]; ->>Fix (When you add the view as subview it gets +1 ref). UIImageView *backgroundView = [[[UIImageView alloc]initWithImage:[AXThemeManager sharedTheme].tableviewSectionHeaderBackgroundImage] autorelease]; (3) Not a defect but this may help you. Try using this instead of [table reloadData]. It allows to animate things nicely and is not such a hardcore way to update the table. I'm sure it is much more lightweight. Alternatively try to look for other "update" methods. Given you don't delete rows in your example, something like [updateRowsFrom:idxFrom to:idxTo] would help. [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic]; A: Good news! I was able to fix/workaround your problem in two different ways (see below). I would say this is certainly an OS bug. What you are doing causes the cell you have moved (using moveRowAtIndexPath:) to be placed above (in front of) the header cell in the z-order. I was able to repro the problem in OS 5 and 6, with cells that did and didn't have UITextFields, and with the tableView in and out of edit mode (in your video it is in edit mode, I noticed). It also happens even if you are using standard section headers. Paul, you say in one of your comments: I solved it badly using a loader and "locking" the table while preforming a reloadData I am not sure what you mean by "using a loader and locking the table", but I did determine that calling reloadData after moveRowAtIndexPath: does fix the problem. Is that not something you want to do? [self.tableView moveRowAtIndexPath:indexPath toIndexPath:newPath]; //[self.tableView reloadData]; // per reply by Umka, below, reloadSections works and is lighter than reloadData: [self reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone]; If you dont want to do that, here is another solution that feels a little hacky to me, but seems to work well (iOS 5+): __weak UITableViewCell* blockCell = cell; // so we can refer to cell in the block below without a retain loop warning. ... cell.onTextEntered = ^(NSString* sText) { // move item in my model NSIndexPath *newPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section]; [self.itemNames removeObjectAtIndex:indexPath.row]; [self.itemNames insertObject:sText atIndex:0]; // Then you can move cell to back [self.tableView moveRowAtIndexPath:indexPath toIndexPath:newPath]; [self.tableView sendSubviewToBack:blockCell]; // a little hacky // OR per @Lombax, move header to front UIView *sectionView = [self.tableView headerViewForSection:indexPath.section]; [self.tableView bringSubviewToFront:sectionView]; A: - (void)scrollViewDidScroll:(UIScrollView *)scrollView { float heightForHeader = 40.0; if (scrollView.contentOffset.y<=heightForHeader&&scrollView.contentOffset.y>=0) { scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0); } else if (scrollView.contentOffset.y>=heightForHeader) { scrollView.contentInset = UIEdgeInsetsMake(-heightForHeader, 0, 0, 0); } } A: What I did to solve this problem was to set the zPosition of the view in the section header. headerView.layer.zPosition = 1000 //just set a bigger number, it will show on top of all other cells.
unknown
d9091
train
Create a file named foo.awk with content { print $0 "/32" } (i.e. the awk script) then change line 2 of your bat file from awk "{ print $0 "/32" }" < ip.txt > ipnew.txt to awk -f foo.awk < ip.txt > ipnew.txt. Now run your bat file however you normally do.
unknown
d9092
train
I configured the redirection from HTTP(port 80) to HTTPS(port 443) within server.xml as <Connector connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="443"/>
unknown
d9093
train
There are a few different approaches you can use. You can look at MotionEvent.ACTION_MOVE and act when you receive that in your onTouch. You can look at MotionEvent.ACTION_OUTSIDE and see if they have left the region your are checking. You can also put a listener on your scroll View and change the background when it moves. Synchronise ScrollView scroll positions - android Alternately, you could use a gestureListener and detect that.
unknown
d9094
train
You can use Keyed Services. And then in your registration add a specific Resolve. static void Main(string[] args) { Console.WriteLine("Hello World!"); // Program.cs of my backend micro service var builder = new ContainerBuilder(); builder.RegisterModule(new DataProtectionServiceModule("dbConfig", DeviceState.Db)); builder.RegisterModule(new DataProtectionServiceModule("cacheConfig", DeviceState.Cache)); // I have figured, this is wrong. builder.RegisterType<MyDbRepo>().WithParameter( new ResolvedParameter( (pi, ctx) => pi.ParameterType == typeof(IDataProtectionService), (pi, ctx) => ctx.ResolveKeyed<IDataProtectionService>(DeviceState.Db) ) ).As<IMyDbRepo>().SingleInstance(); builder.RegisterType<MyCacheRepo>().WithParameter( new ResolvedParameter( (pi, ctx) => pi.ParameterType == typeof(IDataProtectionService), (pi, ctx) => ctx.ResolveKeyed<IDataProtectionService>(DeviceState.Cache) ) ).As<IMyCacheRepo>().SingleInstance(); var container = builder.Build(); var cache = container.Resolve<IMyCacheRepo>(); var db = container.Resolve<IMyDbRepo>(); } } public enum DeviceState { Cache, Db } public class DataProtectionServiceModule : Module { private readonly string config; private readonly DeviceState _state; public DataProtectionServiceModule(string config, DeviceState state) { this.config = config; _state = state; } protected override void Load(ContainerBuilder builder) { builder.Register<Token>(compContext => { // a complex logic here }).OnRelease(instance => instance.Dispose()); builder.Register(c => { // a logic to generate an object of IDataProtectionService // this logic involves the use of config field of this class. return new DataProtectionService(config); }).Keyed<IDataProtectionService>(_state); } } public class DataProtectionService : IDataProtectionService { public string Config { get; } public DataProtectionService(string config) { Config = config; } } public class MyDbRepo : IMyDbRepo { IDataProtectionService dataProtectionService; public MyDbRepo(IDataProtectionService dataProtectionService) { this.dataProtectionService = dataProtectionService; } } public interface IDataProtectionService { } public interface IMyDbRepo { } public class MyCacheRepo : IMyCacheRepo { IDataProtectionService dataProtectionService; public MyCacheRepo(IDataProtectionService dataProtectionService) { this.dataProtectionService = dataProtectionService; } } public interface IMyCacheRepo { } Alternatively you can use Named Services and the config-name dbConfig and cacheConfig. This way you do not need to change the constructor of DataProtectionServiceModule. builder.RegisterType<MyDbRepo>().WithParameter( new ResolvedParameter( (pi, ctx) => pi.ParameterType == typeof(IDataProtectionService), (pi, ctx) => ctx.ResolveNamed<IDataProtectionService>("dbConfig") ) ).As<IMyDbRepo>().SingleInstance(); builder.RegisterType<MyCacheRepo>().WithParameter( new ResolvedParameter( (pi, ctx) => pi.ParameterType == typeof(IDataProtectionService), (pi, ctx) => ctx.ResolveNamed<IDataProtectionService>("cacheConfig") And your module: protected override void Load(ContainerBuilder builder) { //builder.Register<Token>(compContext => //{ // a complex logic here //}).OnRelease(instance => instance.Dispose()); builder.Register(c => { // a logic to generate an object of IDataProtectionService // this logic involves the use of config field of this class. return new DataProtectionService(config); }).Named<IDataProtectionService>(config); }
unknown
d9095
train
Depending on what you need you can use some library (free or commercial) for this: * *OpenXML 2.0 from MS *Aspose.Cells (commercial) *Flexcel (commercial) *Create Excel (.XLS and .XLSX) file from C#
unknown
d9096
train
xxxxxxoRtGnOIb_vno1wQ".toCharArray()); } }); I found this is for username and password. But i want to authenticate with specific key only How to do this? Thanks
unknown
d9097
train
Your code seems correct, and compiles for me: Objective Caml version 3.11.1 # let rec sort lst = ... val sort : 'a list -> 'a list = <fun> val insert : 'a -> 'a list -> 'a list = <fun> # sort [ 1 ; 3 ; 9 ; 2 ; 5 ; 4; 4; 8 ; 4 ] ;; - : int list = [1; 2; 3; 4; 4; 4; 5; 8; 9] A: Adding to what Pascal said, the list type is defined as: type 'a list = [] | :: of 'a * 'a list and that's what you are matching your list lst against. A: The symbol “|“ is the horizontal line symbol, it is not l character and the -> are the minus symbol and the bigger symbol. I think you copied and pasted the segment of code in the website of Inria. Please check and rewrite the special symbols. I tested it and it works well. A: Head and tail need not to be defined. They are matched from 'list' you give.
unknown
d9098
train
So you want to create a new box association using an existing Box. We can grab the attributes of the existing box to create the new one. However, an existing box will already have an id, so we need to exclude that from the attributes. Following the above logic, the following should work: def create @modification = Modification.new(change_params) respond_to do |format| if @modification.save @modification.entity.boxes.each do |d| @modification.boxes << d.dup end flash[:success] = "Success" format.html { redirect_to @modification } format.json { render :show, status: :created, location: @modification } else format.html { render :new } format.json { render json: @modification.errors, status: :unprocessable_entity } end end end A: When you declare a has_many association, the declaring class automatically gains 16 methods related to the association as the mention Guide Ruby On Rails Association Has-Many def create @modification = Modification.new(change_params) respond_to do |format| if @modification.save @modification.entity.boxes.each do |d| @modification.boxes << d # if d.present? use if condition there is nay validation in your model. end flash[:success] = "Success" format.html { redirect_to @modification } format.json { render :show, status: :created, location: @modification } else format.html { render :new } format.json { render json: @modification.errors, status: :unprocessable_entity } end end end Hope this helo you !!!
unknown
d9099
train
Guessing here, but does wrapping the code a $(function () { ..your code }) (domready) callback help?
unknown
d9100
train
Import math and use math.sqrt(math.sqrt(number)) import math number=float(input("Please enter a number: ")) square = math.sqrt(math.sqrt(number)) print(square) A: It looks like it is doing the square root (i.e., 1/2) of 1/3 and then applying that to number. You'll want to force the order of operations since it's evaluating the exponent operator from right to left. square = 2*(number**(1/2))**(1/3) By adding parenthesis, you are forcing it to take the square root first, and then the cube root. You are using Python3, but for future readers, Python2 would evaluate 1/2 and 1/3 to 0. To change that you'd use floats instead: square = 2*(number**(1.0/2.0))**(1.0/3.0) A: If you want to find the square root of the square root of a number you can see using some algebra we can see that ((x)^0.5)^0.5) simplifies down to x^(0.25) So you can either do x**(0.25) or you can do the following: import math math.sqrt(math.sqrt(x)) One other thing, in your code you say: square = 2*number**(1/2)**(1/3) and in the title you say "Square root inside a square root python". This indicates to me that you might have made either a typo in your code or mistake in naming the title of your question. If you do want to find a square root of a square root then my suggestions above should be sufficient to do that.
unknown