_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d5701
train
Here I have written simple code for pagination design. You can use it. HTML for pagination <a>1</a> <a>2</a> <a>3</a> Style for pagination link <style> a::after { content: " /"; margin: 0 5px; } a:last-child::after { display: none; } </style> Your pagination link will be look like below You can modified the design as per your site. Hope this will work for you!
unknown
d5702
train
When you use the canvas as both source and destination, the browser is required to do (there are finer steps involved, but these are the main ones): * *Create a scratch bitmap to copy to *Copy current bitmap into scratch bitmap *Copy scratch bitmap back to original bitmap at a different position (ie. drawImage(canvas,...)); *Remove scratch This instead of when you use separate canvases: * *Copy source bitmap to destination bitmap Why not just "blitting"? The official standard define this case in this way (my emphasis): When a canvas or CanvasRenderingContext2D object is drawn onto itself, the drawing model requires the source to be copied before the image is drawn, so it is possible to copy parts of a canvas or scratch bitmap onto overlapping parts of itself. Also take a look at the Drawing Model for the steps involved.
unknown
d5703
train
You want something like this: class User < ActiveRecord::Base has_many :writings has_many :posts, :through => :writings has_many :readings has_many :read_posts, :through => :readings, :class_name => "Post" #.. end By giving the association name something other than just :posts you can refer to each one individually. Now... @user.posts # => posts that a user has written via writings @user.read_posts # => posts that a user has read via readings
unknown
d5704
train
Alright, I feel like this was not really a problem at all to begin with as I discovered the DeserializeObject(string, Type, JsonSerializerSettings) overload for the method. It works splendidly. However, I would still like to hear some feedback on the approach. Do you think using attributes as a way to resolve the type names is reasonable or are there better ways? I don't want to use the class names directly though, because I don't want to risk any sort of man-in-the-middle things be able to initialize whatever. A: Just a few minutes ago we have posted the alternative way to do what you want. Please look here, if you will have any questions feel free to ask: Prblem in Deserialization of JSON A: Try this http://json2csharp.com/ Put your Json string here it will generate a class then public static T DeserializeFromJson<T>(string json) { T deserializedProduct = JsonConvert.DeserializeObject<T>(json); return deserializedProduct; } var container = DeserializeFromJson<ClassName>(JsonString);
unknown
d5705
train
@ManoMarks: Things are getting worse. Browse his file again or e.g., my http://maps.google.com/maps?q=http:%2F%2Fjidanni.org%2Flocation%2Fzaokeng.kmz Unclicking boxes in the LEFT panel no longer turns off that layer! They used to turn on and off what they referred to, that is why they are clickable checkboxes. Now they don't work on any KML map anywhere! (Broken now in Google Maps, but still works OK in Google Earth though.) Furthermore, e.g., turning on the (panoramio) photo layer in the RIGHT pull down menus loses the LEFT panel's menus for the rest of the session no matter what. In conclusion viewing KML files in Google Maps is now at an all time bug threatened low!
unknown
d5706
train
Yuck, I remember using backgrounDRb, it was horrible. I use Resque now, after using delayed_job. Both work well, and you can solve your problem by only running a single worker. You can find both on Github.
unknown
d5707
train
function check_holiday4(ds) { const [m, d, y] = ds.split('/'); const h = [ // keys are formatted as month,week,day ["0,1", "New Year's Day"], ["0,3,1", "Martin Luther King, Jr. Day"], ["0,20", (function() { if (((y - 1937) % 4) == 0) return 'Inauguration Day' })()], ["1,14", "Valentine's Day"], ["1,3,1", "President's Day"], ["2,2,0", "Daylight Savings Time Begins"], ["3,3,3", "Administrative Professionals Day"], ["4,2,0", "Mother's Day"], ["4,5,1", "Memorial Day"], ["5,14", "Flag Day"], ["5,3,0", "Father's Day"], ["5,3,6", "Armed Forces Day"], ["6,4", "Independence Day"], ["6,4,0", "Parents Day"], ["8,1,1", "Labor Day"], ["9,2,1", "Columbus Day"], ["9,31", "Halloween"], ["10,11", "Veterans Day"], ["10,1,0", "Daylight Savings Time Ends"], ["10,1,2", "Election Day"], ["10,4,4", "Thanksgiving Day"], ["11,25", "Christmas Day"] ]; const f = (a, n, d) => (d + 6 - new Date(...a, 7).getDay()) % 7 + n * 7 - 6; const dim = (y, m) => new Date(y, m + 1, 0).getDate(); const hc = (y, m) => h.filter(v => v[0].startsWith(m)).map((val, i) => { const [vm, vn, vdw] = val[0].split(','); let cd = f([y, vm], vn, +vdw); cd = (cd > dim(y, vm)) ? cd - 7 : (val[0].split(',').length === 2) ? vn : cd; val[0] = (+vm + 1) + "/" + cd + "/" + y; return [val[0], val[1]]; }); const ha = hc(y, m - 1); return ha[ha.findIndex(sa => sa[0] === ds)][1]; } console.log(check_holiday4(new Date("10/31/2019").toLocaleDateString())); // "Halloween" console.log(check_holiday4(new Date("5/31/2021").toLocaleDateString())); // "Memorial Day"
unknown
d5708
train
Turns out I actually did need to uninstall the platform, remove the plugin json file, and then reinstall everything. A: Run (this will remove the old ionic ios platform) sudo ionic platform rm ios Then (this will install a new platform with privileges) sudo ionic platform add ios Then build your code ios/android ionic build ios ionic build android This fixed it for me! Might be that you should also run sudo ionic resources to generate new icon and splash screens. A: Basically, re-installation of Platform and Plugins once again resolves the issue.
unknown
d5709
train
I think you're going to need a custom expectation. Based on the testthat pkgdown site, it might look something like this: expect_options <- function(object, options) { # 1. Capture object and label act <- quasi_label(rlang::enquo(object), arg = "object") # 2. Call expect() compResults <- purrr::map_lgl(options, ~identical(act$val, .x)) expect( any(compResults), sprintf( "Input (%s) is not one of the accepted options: %s", toString(act$val), paste(purrr::map_chr(options, toString), collapse = ", ") ) ) # 3. Invisibly return the value invisible(act$val) } expect_options(result, list(matrix(as.raw(0x0c)), matrix(as.raw(0x03))))
unknown
d5710
train
you don’t need a select … from dual, just write: SELECT t.*, dbms_random.value(1,9) RandomNumber FROM myTable t A: Something like? select t.*, round(dbms_random.value() * 8) + 1 from foo t; Edit: David has pointed out this gives uneven distribution for 1 and 9. As he points out, the following gives a better distribution: select t.*, floor(dbms_random.value(1, 10)) from foo t; A: If you just use round then the two end numbers (1 and 9) will occur less frequently, to get an even distribution of integers between 1 and 9 then: SELECT MOD(Round(DBMS_RANDOM.Value(1, 99)), 9) + 1 FROM DUAL A: At first I thought that this would work: select DBMS_Random.Value(1,9) output from ... However, this does not generate an even distribution of output values: select output, count(*) from ( select round(dbms_random.value(1,9)) output from dual connect by level <= 1000000) group by output order by 1 1 62423 2 125302 3 125038 4 125207 5 124892 6 124235 7 124832 8 125514 9 62557 The reasons are pretty obvious I think. I'd suggest using something like: floor(dbms_random.value(1,10)) Hence: select output, count(*) from ( select floor(dbms_random.value(1,10)) output from dual connect by level <= 1000000) group by output order by 1 1 111038 2 110912 3 111155 4 111125 5 111084 6 111328 7 110873 8 111532 9 110953
unknown
d5711
train
There are some helpful graphics on pywt webpage that help visualize what these thresholds are and what they do. The threshold applies to the coefficients as opposed to your raw signal. So for denoising, this will typically be the last couple of entries returned by pywt.wavedec that will need to be zeroed/thresholded. I could initial guess is the 0.5*np.std of each coefficeint level you want to threshold.
unknown
d5712
train
Check if .git is included in your .dockerignore file and if so, remove it.
unknown
d5713
train
You have to present the view controller in this method var completionHandler: SLComposeViewControllerCompletionHandler! You can use the above method like this var shareToFacebook : SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook) shareToFacebook.addImage(self.Img.image) shareToFacebook.completionHandler = { (result:SLComposeViewControllerResult) in } self.presentViewController(shareToFacebook, animated: true, completion: nil) self.performSegueWithIdentifier("goToStarting", sender: self)
unknown
d5714
train
You need to remove the bin from the end of your JAVA_HOME variable. If Android Studio still gives the same error, close and restart it. If you still get the same error, restart your machine.
unknown
d5715
train
I want to know if it's possible to know if the email was actually sent or not No. First, there is no requirement that the user chooses an email client for this startActivity() request. Second, there is nothing in the ACTION_SEND protocol that lets the app offering to share the content know whether or not the user did anything with that content. A: Maybe you could try startActivityForResult() and see whether the resultcode changes depending on what the user did
unknown
d5716
train
Singletons are initialized lazily. scala> :pa // Entering paste mode (ctrl-D to finish) object Net { val address = Config.address } object Config { var address = 0L } // Exiting paste mode, now interpreting. defined object Net defined object Config scala> Config.address = "1234".toLong Config.address: Long = 1234 scala> Net.address res0: Long = 1234 FWIW. A: Using lazy: object Program { var networkAdress: String = _ def main(args: Array[String]): Unit = { networkAdress = args(0) println(NetworkPusher.networkAdress) } object NetworkPusher { lazy val networkAdress = Program.networkAdress } }
unknown
d5717
train
I have done some tests and I think dates are exported as YYYY-MM-DD. I really don't have Excel installed on this computer right now, but I downloaded an xls file from dataclips and imported it on Googlesheets. Dates were correct without any conversion needed.
unknown
d5718
train
No boxing, compiler uses the ldloca.s instruction which pushes a reference to the local variable onto the stack (http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldloca_s(VS.71).aspx) .method private hidebysig static void Func() cil managed { .maxstack 2 .locals init ( [0] int32 num, [1] bool flag) L_0000: nop L_0001: ldstr "5" L_0006: ldloca.s num L_0008: call bool [mscorlib]System.Int32::TryParse(string, int32&) L_000d: stloc.1 L_000e: ret } A: No, there is no Boxing (required/involved). When you do Box a variable, changes to the boxed instance do not affect the original. But that is exactly what out is supposed to do. The compiler 'somehow' constructs a reference to the original variable. A: As others have pointed out, there's no boxing here. When you pass a variable as an argument corresponding to an out or ref parameter, what you are doing is making an alias to the variable. You are not doing anything to the value of the variable. You're making two variables represent the same storage location. Boxing only happens when a value of a value type is converted to a value of a reference type, and there's no conversion of any kind in your example. The reference type must of course be System.Object, System.ValueType, System.Enum or any interface. Usually it is pretty clear; there's an explicit or implicit conversion in the code. However, there can be circumstances where it is less clear. For example, when a not-overridden virtual method of a struct's base type is called, there's boxing. (There are also bizarre situations in which certain kinds of generic type constraints can cause unexpected boxing, but they don't usually come up in practice.) A: There is no boxing; what the out parameter does is specifies that number must be assigned to within the TryParse method. Irrespective of this, it is still treated as an int, not an object.
unknown
d5719
train
Having used Java Pathfinder some time back, I know that its not an applet as the other answer worries. You are getting this error because the Java Pathfinder jar files are not on your classpath. Here is a complete Java Pathfinder Getting Started tutorial that could help others coming to this old thread. A: It's not a URL at all (except in the case of applets, and you didn't mention an applet). You need to put the Pathfinder jar in the classpath when compiling and running, via -cp to javac and java. If it's an applet, it's more complex.
unknown
d5720
train
No all characters are allowed in a xml files. Here is a link for you to find which one is allowed or is discouraged and the reset is not allowed: http://en.wikipedia.org/wiki/Valid_characters_in_XML Yours (→) is not allowed. A: I resolved this by using below code String removedUnicodeChar = "DISPOSABLE COVERALL → XXL</Description></Order> ↔ ↕ ↑ ↓ → ABC"; Pattern pattern = Pattern.compile("[\\p{Cntrl}|\\uFFFD]"); Matcher m = pattern.matcher(removedUnicodeChar); if(m.find()){ System.out.println("Control Characters found"); removedUnicodeChar = m.replaceAll(""); }
unknown
d5721
train
You could do an ArrayList of the characters found in your secret. Then use .contains(Char c) method from the ArrayList An Example: ArrayList<Char> secret = new ArrayList<Char>(); secret.add('w'); secret.add('o'); secret.add('r'); secret.add('l'); secret.add('d'); if(secret.contains(new Char('x')) { System.out.println("Found"); } else { System.out.println("Not Found"); } A: I think this might be homework, so gtgaxiola's answer could be something the teacher doesn't want to see. Here is how to implement the equivalent of .contains() on a normal array of chars so you don't have to change too much in your current code. char[] secretCh = new char[]{'s', 'e', 'c', 'r', 'e', 't'}; char guessCh = 'e'; boolean found = false; for(int i = 0; i < secretCh.length; i++) { // loop through each character in the secretCh array if (secretCh[i] == guessCh) { found = true; break; } } if (found) System.out.println("guessCh is a letter in the secret word."); A: The String object already has this functionality built in. All you really need is something like this: if(secretStr.indexOf(guessCh) < 0) nTurnsLeft--; indexOf returns the index of the location of the char guessCh inside the String secretStr. If guessCh is not found, then indexOf returns -1;
unknown
d5722
train
You should use a parameterized query. This would allow a more understandable query text, avoid simple syntax errors (like the missing comma at the end of the first line (jdate)), avoid Sql Injections and parsing problems with strings containing quotes or decimal separators string slct = @"SELECT Route.Route_Source, Route.Route_Destination, Flight.Flight_Name, Schedule.Depart_Time, Schedule.Arr_Time, Schedule.Route_rate_Ad, Seats." + jdate + ", Schedule.Sch_id " + @"FROM Schedule INNER JOIN Flight ON Schedule.Flight_Id = Flight.Flight_id INNER JOIN Route ON Schedule.Route_id = Route.Route_id INNER JOIN Seats ON Seats.Sch_id = Schedule.Sch_id WHERE (Route.Route_Source = @scode) AND (Route.Route_Destination =@dcode) AND (Seats.Class=@class) ORDER BY Schedule.Depart_Time, Schedule.Arr_Time, Flight.Flight_Name"; cn.Open(); SqlCommand cmd = new SqlCommand(slct, cn); cmd.Parameters.AddWithValue("@scode", scode); cmd.Parameters.AddWithValue("@dcode", dcode); cmd.Parameters.AddWithValue("@class", clas); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds);
unknown
d5723
train
event ondataavailable works after mediaRecorder stop() function
unknown
d5724
train
It is now semantically correct to wrap block level elements in an anchor tag (using the html5 doctype). I would suggest amending your markup to this. HTML <a href="#"> <div class="imgWrapper"> <img src="http://www.google.com/images/srpr/logo4w.png" /> </div> <p>Here is some text</p> </a> A: I have found this to be an annoying trait of IE for some time, to solve it I had to make a transparent image and use it as the background of the anchor tag: background:url(transparent1x1.gif) repeat; http://jsfiddle.net/NUyhF/6/
unknown
d5725
train
This problem occurs because your code try to using non-existing pointer in cocoa pods. You may using framework that using cocoa pods and install needed pods on the main project. The solution is to make cocoa pods version similar in both framework and project , run pod update from the terminal in both framework and project or specify every pod version to be same in both Example framework pod file : pod 'GooglePlaces' '~> 3.1.0' project pod file : pod 'GooglePlaces' '~> 3.1.0' I hope this solve your problem. A: I've seen this error when I had a UITableView in a view controller and: * *I connected the DataSource and Delegate for table view in the Storyboard. *I did NOT declare the UIViewController as UITableViewDelegate and UITableViewDataSource. I usually assign delegate/datasource in code (which would have given me a warning).
unknown
d5726
train
You won't be able to get the grid object by dojo.byId("_selectedDataGrid"). It is better to keep the myGrid object at class level (widget level) and connect using dojo.hitch. dojo.connect(this.myGrid, 'onRowClick', dojo.hitch(this, function(){ //access myGrid using this.myGrid and do the handling })); A: From what you have share, I can see that the node "_selectedDataGrid" is just a Div tag. and your dataGrid widget may be "this._selectedGrid" so you should be add the event on that widget not the container node. Also there is dijit.byId to get the instance of dijits/widgets. and dojo.byId is used to search of dom nodes. Hope this was helpful.
unknown
d5727
train
$(".chooseTheme").click(function () { var src = $(this).closest('li').find("img").attr('src'); alert(src); }); A: $(".chooseTheme").click(function () { var src = $("li").find("img").attr('src'); alert(src); });
unknown
d5728
train
NSIS has a 1024 character limit by default. I'm guessing when $INSTDIR is expanded you exceed that limit. You can download the large string build or execute a batch file instead: Section InitPluginsDir FileOpen $0 "$PluginsDir\test.cmd" w FileWrite $0 '@echo off$\n' ; Write out example command in pieces: FileWrite $0 '"$sysdir\forfiles.exe"' FileWrite $0 ' /P "$windir" /S' FileWrite $0 ' /M "*shell32*"$\n' FileClose $0 ExecWait '"$PluginsDir\test.cmd"' SectionEnd
unknown
d5729
train
In way number 2, the price is an atribute and not a subtag so it should be accessed with the @ symobl. So for way 2, your filter function should be: private function myFilter(xml:XML):Boolean { return Number(xml.@PRICE) >= 9; } Notice the @ before PRICE.
unknown
d5730
train
I apologize that the question was vague. However we had no clue what was causing the problem so what facts would have been relevant? At any rate it turns out we have two web apps running under IIS, both are trying to create ActiveX components. As soon as we turn one of the web apps off the problem goes away. After we verified this behavior, we tried calling some simple ActiveX components (like excel). Lo and behold exactly the same behavior as long as there are more than two web apps running. Our solution for now is to host the second web app elsewhere.
unknown
d5731
train
Ideally it should work. You can also try using request module like below const request = require('request'); request('http://www.google.com', function (error, response, body) { console.error('error:', error); // Print the error if one occurred console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received console.log('body:', body); // Print the HTML for the Google homepage. }); Try and see if it helps. A: Solved by doing await properly. Used this as guide. var https = require('https'); var util = require('util'); const querystring = require('querystring'); var request = require('request') module.exports = async function (context, req) { context.log('JavaScript HTTP trigger function processed a request.'); /*if (req.query.name || (req.body && req.body.name)) {*/ var getOptions = { contentType: 'application/json', headers: { 'Authorization': <bearer_token> }, }; var postData = { "key": "value" }; var postOptions = { method: 'post', body: postData, json: true, url: <post_url>, headers: { 'Authorization': <bearer_token> }, }; try{ var httpPost = await HttpPostFunction(context, postOptions); var httpGet = await HttpGetFunction(context, <get_url>, getOptions); return { res: httpPost }; }catch(err){ //handle errr console.log(err); }; }; async function HttpPostFunction(context, options) { context.log("Starting HTTP Post Call"); return new Promise((resolve, reject) => { var data = ''; request(options, function (err, res, body) { if (err) { console.error('error posting json: ', err) reject(err) } var headers = res.headers; var statusCode = res.statusCode; //context.log('headers: ', headers); //context.log('statusCode: ', statusCode); //context.log('body: ', body); resolve(body); }) }); }; async function HttpGetFunction(context, url, options) { context.log("Starting HTTP Get Call"); return new Promise((resolve, reject) => { var data = ''; https.get(url, options, (resp) => { // A chunk of data has been recieved. resp.on('data', (chunk) => { data += chunk; }) // The whole response has been received. Print out the result. resp.on('end', () => { resolve(JSON.parse(data)); }); }).on("error", (err) => { console.log("Error: " + err.message); reject(err.message); }); }); };
unknown
d5732
train
If you check the documentation for the method onListItemClick() you can see that the last parameter is the row id of the clicked item. This method will be called when an item in the list is selected. Subclasses should override. Subclasses can call getListView().getItemAtPosition(position) if they need to access the data associated with the selected item. Parameters l: The ListView where the click happened v: The view that was clicked within the ListView position: The position of the view in the list id: The row id of the item that was clicked But to get a proper row id it is important that the cursor which was passed to the adapter contains a row called '_id' representing unique id for each row in the table.
unknown
d5733
train
Following cron expression will run 14 days once 0 5 */14 * * /your/command/ If you like to run only once from current date on 20th September 2018 0 0 20 9 ? 2018 /command WARNING: The year column is not supported in standard/default implementations of cron. A: Run a cron-job every 14 days starting from day X If you want to do this, have a look at this answer. Run a cron-job only ones 14 days after day X If you want to do this, there are a few options you have. Assume that day X is today (2018-09-06), then I give you the following options: # Example of job definition: # .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # | | .---------- day of month (1 - 31) # | | | .------- month (1 - 12) OR jan,feb,mar,apr ... # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) # | | | | | # * * * * * command to be executed 0 0 6 9 * [[ `date '+\%Y'` == "2018" ]] && sleep 1209600 && command1 0 0 20 9 * [[ `date '+\%Y'` == "2018" ]] && command2 0 0 * * * /path/to/daytestcmd 14 && command3 * *The first option here is simply checking if the year is correct. If so, sleep for 14 days and then execute command1 *The second option is by computing the day itself and execute the script on that day. Again, you have to check manually for the correct year. The third option is much more flexible for your purpose. The idea is to create a script called daytestcmd which does the check for you. The advantage of this script is that you only need to update one line in the script to change the test and never change the cronjob. The script would look something like: #/usr/bin/env bash # Give reference day reference_day="20180906" # Give the number of days to await execution (defaults to zero) delta_days="${1:-0}" # compute execution day execution_day=$(date -d "${reference_day} + $delta_days days" "+%F") [[ $(date "+%F") == "$execution_day" ]] So, the next time you want to wait 14 days, just update the script and change the variable reference_day. note: the OP updated the question. The above script can also be adjusted where reference_day is obtained via a set of commands, for example to retrieve the day of dev deployment. Imagine get_dev_deployment_day is a command which returns that day, then you just need to update reference_day=$(get_dev_deployment_day)
unknown
d5734
train
Try to use this code, it worked for me : var userID: String = Twitter.sharedInstance().sessionStore.session.userID var client = TWTRAPIClient(userID: userID)
unknown
d5735
train
The component is a single instance and so each time you push a new instance to the ConfirmationService you are overwriting the previous one. To call one after the other, you need to add in some way of waiting for one confirmation to be concluded before making your next call. I did a quick test of this and got it to work by creating a 'confirmationQueue' array and then calling the service recursively like this: this.confirmQueue = []; for (let x of y) { if (conditionIsMet) { this.confirmQueue.push(x); } else { //Do something else } this.displayNextConfirm(); } <snip> private displayNextConfirm(): void { if (this.confirmQueue && this.confirmQueue.length > 0) { setTimeout(() => { let x = this.confirmQueue[0]; this.confirmQueue = this.confirmQueue.slice(1); this.confirmationService.confirm({ message: 'Question Text', header: 'Confirmation', icon: 'fa fa-refresh', accept: () => { //DO Accept Work this.displayNextConfirm(); }, reject: () => { //Do Rejection Work this.displayNextConfirm(); } }); }, 1); } } (Note that the setTimeout(() => {...}, 1) allows the current confirm dialog to clear before the service tries to open the next one.) Obviously there are other ways to implement this, but the key is to only submit one call to the ConfirmationService at a time and wait for that to complete before submitting the next one.
unknown
d5736
train
Both publishToMavenLocal and publish are aggregate tasks without actions. They are used to trigger a bunch of publishPubNamePublicationToMavenLocal tasks and publishPubNamePublicationToRepoNameRepository tasks respectively. $ ./gradlew publishToMavenLocal --info ... > Task :publishMavenPublicationToMavenLocal ... > Task :publishToMavenLocal Skipping task ':publishToMavenLocal' as it has no actions. :publishToMavenLocal (Thread[Execution worker for ':',5,main]) completed. Took 0.0 secs. $ ./gradlew publish --info ... > Task :publishMavenPublicationToMavenRepository ... > Task :publish Skipping task ':publish' as it has no actions. :publish (Thread[Execution worker for ':',5,main]) completed. Took 0.0 secs. Reference: https://docs.gradle.org/current/userguide/publishing_maven.html#publishing_maven:tasks
unknown
d5737
train
Could use something similar: public static readonly char[] CHARS = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; static void Main(string[] args) { static string GenerateGlitchedString(uint wordCount,uint wordslength) { string glitchedString = ""; for (int i = 0; i < wordCount; i++) { for (int j = 0; j < wordslength; j++) { Random rnd = new Random(); glitchedString += CHARS[rnd.Next(CHARS.Length)]; } glitchedString += " "; //Add spaces } return glitchedString; } string output = GenerateGlitchedString(5, 5); Console.WriteLine(output); } A: You can use Linq to generate any number of random characters from an enumerable: int howManyChars = 5; var newString = String.Join("", Enumerable.Range(0, howManyChars).Select(k => st[Random.Range(0, st.Length)])); textbox.text = newString; A: If you want completely glitchy strings, go the way of Mojibake. Take a string, convert it to one encoding and then decode it differently. Most programmers end up familiar with this kind of glitch eventually. For example this code: const string startWith = "Now is the time for all good men to come to the aid of the party"; var asBytes = Encoding.UTF8.GetBytes(startWith); var glitched = Encoding.Unicode.GetString(asBytes); Debug.WriteLine(glitched); consistently results in: 潎⁷獩琠敨琠浩⁥潦⁲污潧摯洠湥琠潣敭琠桴⁥楡⁤景琠敨瀠牡祴 But, if you just want some text with some random glitches, how about something like this. It uses a set of characters that should be glitched in, a count of how many glitches there should be in a string (based on the string length) and then randomly inserts glitches: private static Random _rand = new Random(); private const string GlitchChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%&"; public static string GlitchAString(string s) { var glitchCount = s.Length / 5; var buffer = s.ToCharArray(); for (var i = 0; i < glitchCount; ++i) { var position = _rand.Next(s.Length); buffer[position] = GlitchChars[_rand.Next(GlitchChars.Length)]; } var result = new string(buffer); Debug.WriteLine(result); return result; } The first two times I ran this (with that same Now is the time... string), I got: Original String: Now is the time for all good men to come to the aid of the party First Two Results: LowmiW HhZ7time for all good mea to comX to ths aid oV the p1ray Now is fhO P!me forjall gKod men to @ome to the a@d of F5e Nawty The algorithm is, to some extent, tunable. You can have more or fewer glitches. You can change the set of glitch chars - whatever you'd like.
unknown
d5738
train
As per the documentation the reflected form of __lt__() is __gt__(). There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other’s reflection, __le__() and __ge__() are each other’s reflection, and __eq__() and __ne__() are their own reflection. If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority. Virtual subclassing is not considered.
unknown
d5739
train
gperftools uses autoconf/automake, so you can do ./configure --prefix=/path/to/whereever make make install This works for all autotools projects, unless they are severely broken. On that note, it is generally a good idea to read the INSTALL file in a source tree to find out about this sort of stuff. There is one in the gperftools sources, and this is documented there.
unknown
d5740
train
Looks to me like it might be an off-by-one error. When you call malloc, you are allocating enough space for an array of length elements. Arrays are 0-indexed -- that is, points[0] to points[length-1] are valid memory addresses, while points[length] is not. At the end of your first loop, the last point you set is one element past the end of the array, and it's possible that the value gets overwritten by something by the time you try to draw the last line segment. Try changing your first loop to be: for(i=0; i < length; i++) { // scanf stuff here } and your second loop to: for(i=0; i < length-1; i++) // cvLine stuff here
unknown
d5741
train
Played with this. Couldn't do it. What are you trying to achieve? Are you aware of the contenteditable attribute? This might get you what you need. https://developer.mozilla.org/en-US/docs/HTML/Content_Editable A: What if you just avoid the whole style snafu and do a little text shuffling? You already have everything you need with jQuery. http://jsfiddle.net/2fQgY/8/ The date is <span class="dateSpoof"></span><input class="myDate" type="hidden" value="foo" />. Thanks for coming. $('.myDate').datepicker({ showOn: 'button', buttonText: 'select...', onClose: function () { var dateText = $(this).val(); $('.dateSpoof').html(dateText); $('.ui-datepicker-trigger').hide(); }, dateFormat: 'd M yy' }); Here's an example that's resettable: http://jsfiddle.net/2fQgY/11 And here's one that's all text and nothing but text: http://jsfiddle.net/2fQgY/14
unknown
d5742
train
You need to first understand underline problems that isolation level resolves. * *Dirty read(I saw updated record however it disappeared again) *Non repeatable read(Update - I saw an updated value but now value has changed. Oh someone rolled back.) *Phantom read(Insert - This appeared as a ghost and then disappeared) Try to play around on two connections. First run connection 1 script then connection 2 script without committing anything. Once both scripts are executed then try to commit connection 1. READ UNCOMMITTED - Connection running under this isolation level can read rows that have been modified by other transactions but not yet committed. READ COMMITTED - Connection running under this isolation level cannot read data that has been modified but not committed by other transactions. REPEATABLE READ - Transaction running under this isolation level cannot read data that has been modified but not yet committed by other transactions and that no other transactions can modify data that has been read by this transaction until the this transaction completes. This is done by placing shared lock on records read by this transaction. Having a shared on lock record, no other transaction can modify this record until this transaction completes. SERIALIZABLE - Same conditions as we have for repeatable read with an addition of one more condition i.e. Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes. Think of a record as inserting a record between date range. You are trying to insert a record between the date range read by another connection. DIRTY READ Connection 1 SET TRANSACTION ISOLATION LEVEL READ COMMITTED BEGIN TRAN UPDATE tbl SET Col1 = 'Dummy' WHERE ID = 1 --NO COMMIT YET Connection 2 SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED BEGIN TRAN SELECT * FROM tbl WHERE ID = 1 -- will return you 'Dummy' if script on connection 1 executed first. Since transaction on connection 1 hasn't been committed yet, you did a dirty read on connection 2. --NO COMMIT YET Avoiding Non repeatable read Connection 1 SET TRANSACTION ISOLATION LEVEL REPEATABLE READ BEGIN TRAN SELECT * FROM tbl WHERE id = 5 --Issue shared lock. This prevents other transactions from modifying any rows that have been read by the current transaction. --Not committed yet Connection 2 SET TRANSACTION ISOLATION LEVEL READ COMMITTED BEGIN TRAN SELECT * FROM tbl WHERE id = 5 UPDATE tbl set name='XYZ' WHERE ID = 5 -- this will wait until transaction at connection 1 is completed. (Shared lock has been taken) --Not committed yet Avoiding Phantom read Connection 1 SET TRANSACTION ISOLATION LEVEL SERIALIZABLE BEGIN TRAN SELECT * FROM tbl WHERE Age BETWEEN 5 AND 15 -- This will issue range lock --Not committed yet Connection 2 SET TRANSACTION ISOLATION LEVEL READ COMMITTED BEGIN TRAN INSERT INTO tbl (Age) VALUES(4) -- Will insert successfully INSERT INTO tbl (Age) VALUES(7) -- this will wait until transaction at connection 1 is completed. (Range lock has been taken) --Not committed yet
unknown
d5743
train
Inside of a function, the function's name can be used as a substitute for using an explicit local variable or Result. freq() and OddUserName() are both doing that, but only freq() is using the function name as an operand on the right-hand side of an assignment. freq := freq + 1; should be a legal statement in modern Pascal compilers, see Why i can use function name in pascal as variable name without definition?. However, it would seem the error message is suggesting that the failing compiler is treating freq in the statement freg + 1 as a function type and not as a local variable. That would explain why it is complaining about not being able to add a ShortInt with a function type. So, you will have to use an explicit local variable instead, (or the special Result variable, if your compiler provides that), eg: function freq(charToFind: char; username : String): Integer; var i, f: Integer; begin f := 0; for i := 1 to Length(username) do if charToFind = username[i] then f := f + 1; //writeln(f); freq := f; end; function freq(charToFind: char; username : String): Integer; var i: Integer; begin Result := 0; for i := 1 to Length(username) do if charToFind = username[i] then Result := Result + 1; //writeln(f); end;
unknown
d5744
train
Initially Even I got the same error. Done few changes in Program.cs . My Program.cs: using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; class Program { static async Task Main() { var builder = new HostBuilder() .ConfigureWebJobs(b => { b.AddTimers(); b.AddAzureStorageCoreServices(); }) .ConfigureLogging((context, b) => { b.AddConsole(); }) .ConfigureAppConfiguration((hostContext, configApp) => { configApp.SetBasePath(Directory.GetCurrentDirectory()); configApp.AddEnvironmentVariables(prefix: "ASPNETCORE_"); configApp.AddJsonFile($"appsettings.json", true); configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true); }) .ConfigureServices(services => { services.AddDbContext<ApplicationDbContext>( options => options.UseSqlServer("MyDefaultConnection")); services.AddTransient<ApplicationDbContext, ApplicationDbContext>(); }); var host = builder.Build(); using (host) { await host.RunAsync(); } } } If you are running locally, cross check the local.settings.json file once. My local.settings.json : { "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "UseDevelopmentStorage=true", "FUNCTIONS_WORKER_RUNTIME": "dotnet" } } My appsettings.json: { "ConnectionStrings": { "AzureWebJobsStorage": "Storage Account Connection String" } } Also have a look at SO Thread once. References taken from MSDoc. A: I do the steps from the beginning. 1- public class ApplicationDbContext: IdentityDbContext<User, Role, Guid> { public ApplicationDbContext(DbContextOptions options) : base(options) { } } 2-add in appsettings.json "ConnectionStrings": { "SqlServer": "Data Source=;Initial Catalog=SpaceManagment;User ID=sa;Password=654321;MultipleActiveResultSets=true;TrustServerCertificate=True;Connection Timeout = 60" }, 3- add in program.cs builder.Services.AddDbContext<ApplicationDbContext>(options => { options .UseSqlServer(settings.SqlServer); //Tips // .ConfigureWarnings(warning => warning.Throw(RelationalEventId.QueryClientEvaluationWarning)); });
unknown
d5745
train
public class A { private String s; public A() { s = "blah"; } public void print() { System.out.println(s); } } Class B: public class B{ private A a[]; public B(){ a = new A[100]; for (int i=0; i<100;i++) { a[i] = new A(); } } public void print() { for (int i=0; i<100; i++) { a.print(); //SHOULD BE a[i].print(); } } } Class Main: public class Main { public static void main(String args[]) { B b = new B(); b.print(); } } Why do I get an outputpattern like B@#, where # is a number. I think it has something to do with indirect adressing but im not quite sure. Why doesn't it print out 100 s? A: You are printing the array rather than the object in the array. As a result, it is printing the address of the object (the number) and the object it is a member of. I suspect you wanted to call each of the prints, you should, in B.print(). You are also missing an increment for i, meaning it will loop indefinitely. for(int i = 0; i < 100; ++i) { a[i].print(); }
unknown
d5746
train
There is no need to do this. Have you tried it without casting them to ints? If you are not able to do this post what version of laravel you are using so people who come across this later don't do needless work. In laravel 4.2.* the following code will return the proper rows. I have just tested this. Route::get('/', function(){ $t = DB::table('users')->whereIn('id', array('1','2','3'))->get(); dd($t); }); This also works. Route::get('/', function(){ $t = DB::table('users')->whereIn('id', array(1,2,3))->get(); dd($t); }); Furthermore this code you have array(4) { [0]=> string(1) "1" [1]=> string(1) "4" [2]=> string(1) "6" } And this code are exactly the same. One has just being displayed using var_dump. array("1", "4", "6") Unless you are literally storing unserialized arrays in your database in which case you have a ton of other issues. EDIT: After controller was posted I don't believe whereIn takes 3 parameters. You are trying to cast '=' to an array in your whereIn statements remove this and it should work or at least get ride of the Array to string error. Link to whereIn Laravel function. A: First: I think Laravel can handle string typed items to be put in a sql where clause where the column is an integers. Second: if it doesn't work you can always 'cast' those strings to integers with the array_map method. More information here: http://php.net/manual/en/function.array-map.php In your example: $ids = array('1', '4', '6'); $ids = array_map(function ($value) { return (int) $value; }, $ids); $users = DB::table('users')->whereIn('id', $ids)->get(); Hope this helps.
unknown
d5747
train
I think what you're after is a left_join which from the docs: https://dplyr.tidyverse.org/reference/join.html returns all rows from x, and all columns from x and y. i.e. pops <- data.frame( "Country" = c("America", "Argentina", "Australia","Brazil", "Japan"), "Population" = seq(100, 200, 25) ) landmass <- data.frame( "Country" = c("Argentina", "Mexico", "Uruguay","Maldives"), "Landmass" = seq(1250, 2000, 250) ) dplyr::left_join(pops, landmass, by = c("Country"= "Country")) yields
unknown
d5748
train
library(data.table) dcast(data.table(df1), ID + date ~ event_name,value.var = 'Time_duration', fun.aggregate = sum) Key: <ID, date> ID date a b c <num> <char> <num> <num> <num> 1: 1 2021-11-01 4 0 0 2: 1 2021-11-02 0 0 5 3: 2 2021-11-01 9 2 0 4: 2 2021-11-02 0 4 0 5: 3 2021-11-01 1 6 0 6: 3 2021-11-02 0 0 8
unknown
d5749
train
To check if dictionary contains specific key use: 'ORG' in Entity statement which returns True if given key is present in the dictionary and False otherwise. A: You can use the .keys() function on the dictionary to check before accessing the data structure. For example: def does_key_exist(elem, dict): return elem in dict.keys() A: if all([a in Entity for a in ('ORG', 'PERSON', 'MONEY')]): Class['Signal'] = 'strong' elif all([a in Entity for a in ('ORG', 'PERSON')]): Class['Signal'] = 'middle' elif not any([a in Entity for a in ('ORG', 'PERSON', 'MONEY')]): Class['Signal'] = 'weak' Note that, according to your question, if Entity contains only 'ORG' or only 'PERSON', no 'Signal' will be set in Class.
unknown
d5750
train
This .jar file is to be used as a library, not a as an executable application. To access the functionalities, you should write your own application in Java and import the needed classes contained in the j-text-utils-0.3.3.jar file. To be able to compile your Java code, the j-text-utils-0.3.3.jar needs to be available on the classpath. See this question for more info : What is a classpath and how do I set it?
unknown
d5751
train
According to the documentation: The PostgreSQL backend (django.db.backends.postgresql_psycopg2) is also available as django.db.backends.postgresql. The old name will continue to be available for backwards compatibility. Actually, this question is already solved here.
unknown
d5752
train
You are passing function(err, key) to verifyToken, but there is not callback in the signature of verifyToken. Try changing the verifyToken function to verifyToken: function(token, admin, callback){ if(admin){ //admin authentication jwt.verify(token, config.SECRET_WORD.ADMIN, callback); }else{ //user authentication jwt.verify(token, config.SECRET_WORD.USER, callback); } } Update : Without callback verifyToken: function(token, admin){ try { if(admin){ //admin authentication jwt.verify(token, config.SECRET_WORD.ADMIN, callback); }else{ //user authentication jwt.verify(token, config.SECRET_WORD.USER, callback); } return true; } catch(err) return false; } } And use like this in your middleware: if (TokenManager.verifyToken(token,true)){ return next(); } else { return res.json({ success : false, message : "Failed to authenticate token"}); }
unknown
d5753
train
I found the solution to my own issue, my project has extra maven plugin called YUI Compressor, it is trying to compress them and causing issue. by adding code to excluded the higchart files in pom.xml and directly added minified files in to project solved the issues.
unknown
d5754
train
On the frontend, you are making an HTTP request with the GET method, which has no body. On the backend, req.body.id will be undefined because there is no request body in the first place. So you have several options: First: use a POST request on the front end axios({ method: 'POST', url:"http://localhost:3000/recette/rec_recette", headers: {}, data: { id: 'votre_id_ici', // This is the body part } }); The backend code to handle the post request: (Use async/await to make the code cleaner) router.post('/recette_light', async (req, res) => { try { // Assuming you are searching for your recette using MongoDB doc.id const cat_recette = await db.cat_recette.findById(req.body.id); // If there are no matching docs. if (!cat_recette) { return res.json("il n'y a pas de cat_recettes"); } // Otherwise send the data to the frontend res.status(200).json({ cat_recette: cat_recette, }); } catch (err) { console.log(err); res.status(500).json({ msg: 'Server Error', }); } }); Second: use the GET method still but with URL parameters axios.get("http://localhost:3000/recette/rec_recette/votre_id_ici") The backend code to handle it: // Note the /:id at the end router.get('/recette_light/:id', async (req, res) => { try { // Assuming you are searching for your recette using MongoDB doc. id // Note the req.params.id here not req.body.id const cat_recette = await db.cat_recette.findById(req.params.id); // If there are no matching docs. if (!cat_recette) { return res.json("il n'y a pas de cat_recettes"); } res.status(200).json({ cat_recette: cat_recette, }); } catch (err) { console.log(err); res.status(500).json({ msg: 'Server Error', }); } });
unknown
d5755
train
With the other syntax errors fixed, this compiles without warnings in GCC 9: #include <iostream> #include <chrono> void Fun(const std::chrono::milliseconds someNumberInMillis = std::chrono::milliseconds(100)) { if (someNumberInMillis > std::chrono::milliseconds{0}) { std::cout << "someNumberInMillis is: " << someNumberInMillis.count() << std::endl; } } int main() { unsigned int someValue = 500; Fun(std::chrono::milliseconds(someValue)); }
unknown
d5756
train
With attribute routing, you just need to decorate your action method with your specific route pattern. public class ProductController : Controller { EFDbContext db = new EFDbContext(); private IProductsRepository repository; public int PageSize = 4; public ProductController (IProductsRepository productrepository) { this.repository = productrepository; } [Route("Product/list/{category}/{page}")] public ViewResult List(string category, int page = 1) { // to do : Return something } } The above route definition will send the request like yourSite/Product/list/phones and yourSite/Product/list/phones/1 to the List action method and the url segments for category and page will be mapped to the method parameters. To enable attribute routing, you need to call the method MapMvcAttributeRoutes method inside the RegisterRoutes method. public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); A: To generate an URL like you want: localhost/Product/List/Cars you can create a custom route like this: routes.MapRoute( name: "ProductList", url: "Product/List/{category}", defaults: new { controller = "Product", action = "List" } ); Remember that custom routes have to come before the most general route (the one that comes with the default template). Regarding your page parameter, if you are comfortable with this URL: localhost:3288/Product/List/teste?page=10 the above already work. But if you want this: localhost:3288/Product/List/teste/10 10 meaning the page number, then the simplest solution would be create two different routes: routes.MapRoute( name: "ProductList", url: "Product/List/{category}", defaults: new { controller = "Product", action = "List" } ); routes.MapRoute( name: "ProductListPage", url: "Product/List/{category}/{page}", defaults: new { controller = "Product", action = "List" , page = UrlParameter.Optional} ); Another cleaner way, is to create a custom route constraint for your optional parameter. This question has a lot of answers to that: ASP.NET MVC: Route with optional parameter, but if supplied, must match \d+
unknown
d5757
train
FragmentScreenD which is extended From FragmentActivity does not Fragment and the second arguement of FragmentManager's replace method needs a Fragment , FragmentScreenD can be started via intent and its behavior is like an Activity, change FragmentActivity to Fragment and implement the methods in FragmentScreenA,B,C,... A: I have several fragments and I want a google map activity in one of those. You don't want an Activity, you want a Fragment, as the error is trying to tell you. You can add a new SupportMapFragment() directly to the FrameLayout, or you need to instead extend that rather than FragmentActivity A: Just take a map fragment in fragment XML and check this link it will helpful to solve problem android MapView in Fragment
unknown
d5758
train
The solution, incredibly, is to give the columns the same alias. I didn't think SQL would allow this, but it does and Dapper maps it all perfectly. IEnumerable<Contact> GetContacts() { return Connection.Query<Contact, Address, Address, Contact>( "SELECT Name, HomeHouseNumber as HouseNumber, HomePostcode as Postcode, WorkHouseNumber as HouseNumber, WorkPostcode as Postcode FROM Contacts", (contact, home, work) => { contact.HomeAddress = home; contact.WorkAddress = work; return contact; }, splitOn: "HouseNumber,HouseNumber"); }
unknown
d5759
train
std::bind stores copies of its arguments (here a move-constructed future), and later, uses them as lvalue arguments (with some exceptions to that rule that include reference wrappers, placeholders and other bind expressions; none applicable here). std::future is not copy-constructible. That is, a function that accepts a parameter by-value, of a type that is not copy-constructible, like your callback does, is not callable with an lvalue. In order to make your code work, you need to adjust the signature of the callback: std::function<void(std::future<my_result_t>&)> callback = [] (auto& result) { // ~^~ ~^~ Preferably, though, don't use std::bind at all. A: It might be worth mentioning that the actual solution is used was to replace the bind by a lambda. What I forgot to mention in my question was that changing the signature of the callback to a reference is not a suitable option for me, since the f callable will be copied/moved into an asynchronous queue, i.e. reactor pattern, i.e. boost::asio::post. A reference would rise lifetime challenges for the lifetime of that future. I didn't mentioned it first since I hope it would still be somehow possible with std::bind, but @piotr-skotnicki did nicely explain why its not possible. So for completeness of other searches without further ado: std::future<my_result_t> future = promise.get_future(); auto f = [callback, future = std::move(future)] () mutable{ callback(std::move(future)); }; f();
unknown
d5760
train
use the following expression string value = Regex.Replace(response.Split(',')[1], "[^.0-9]", "");
unknown
d5761
train
first create class like CVEDictTextView import Foundation import SwiftUI class CVEDictTextView: UITextView { override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { let newInstanceItem = UIMenuItem(title: "Lookup", action:#selector(lookup)) UIMenuController.shared.menuItems = [newInstanceItem] UIMenuController.shared.hideMenu() if(action == #selector(lookup)){ return true } return false } @objc func lookup() { if(self.selectedRange.location != NSNotFound ){ let str = self.value(forKey: "text") as! String var str2 = String(str.dropFirst(self.selectedRange.location)) str2 = String(str2.dropLast(str2.count - self.selectedRange.length)) print(str2) } } } and create TextView UIViewRepresentable struct TextView: UIViewRepresentable { @Binding var text: String @Binding var textStyle: UIFont.TextStyle func makeUIView(context: Context) -> UITextView { let textView = CVEDictTextView() textView.delegate = context.coordinator textView.font = UIFont.preferredFont(forTextStyle: textStyle) textView.autocapitalizationType = .sentences textView.isSelectable = true textView.isUserInteractionEnabled = true textView.isEditable = false return textView } func updateUIView(_ uiView: UITextView, context: Context) { uiView.text = text uiView.font = UIFont.preferredFont(forTextStyle: textStyle) } func makeCoordinator() -> Coordinator { Coordinator($text) } class Coordinator: NSObject, UITextViewDelegate { var text: Binding<String> init(_ text: Binding<String>) { self.text = text } func textViewDidChange(_ textView: UITextView) { self.text.wrappedValue = textView.text } } } in SwitfUI view using it @State private var message = "hello how are you \n\t are you ok? email : [email protected]" @State private var textStyle = UIFont.TextStyle.body TextView(text: $message, textStyle: $textStyle) .padding(.horizontal)
unknown
d5762
train
This code snippet isn't using curl specifically, but it retrieves and prints the remote certificate text (can be manipulated to return whatever detail you want using the various openssl_ functions) $g = stream_context_create (array("ssl" => array("capture_peer_cert" => true))); $r = fopen("https://somesite/my/path/", "rb", false, $g); $cont = stream_context_get_params($r); openssl_x509_export($cont["options"]["ssl"]["peer_certificate"],$cert); print $cert; outputs: -----BEGIN CERTIFICATE----- ...certificate content... -----END CERTIFICATE----- A: You will get the certificate as a resource using stream_context_get_params. Plug that resource into $certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']); to get more certificate information. $url = "http://www.google.com"; $orignal_parse = parse_url($url, PHP_URL_HOST); $get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE))); $read = stream_socket_client("ssl://".$orignal_parse.":443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get); $cert = stream_context_get_params($read); $certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']); print_r($certinfo); Example result Array ( [name] => /C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com [subject] => Array ( [C] => US [ST] => California [L] => Mountain View [O] => Google Inc [CN] => www.google.com ) [hash] => dcdd9741 [issuer] => Array ( [C] => US [O] => Google Inc [CN] => Google Internet Authority G2 ) [version] => 2 [serialNumber] => 3007864570594926146 [validFrom] => 150408141631Z [validTo] => 150707000000Z [validFrom_time_t] => 1428498991 [validTo_time_t] => 1436223600 [purposes] => Array ( [1] => Array ( [0] => 1 [1] => [2] => sslclient ) [2] => Array ( [0] => 1 [1] => [2] => sslserver ) [3] => Array ( [0] => 1 [1] => [2] => nssslserver ) [4] => Array ( [0] => [1] => [2] => smimesign ) [5] => Array ( [0] => [1] => [2] => smimeencrypt ) [6] => Array ( [0] => 1 [1] => [2] => crlsign ) [7] => Array ( [0] => 1 [1] => 1 [2] => any ) [8] => Array ( [0] => 1 [1] => [2] => ocsphelper ) ) [extensions] => Array ( [extendedKeyUsage] => TLS Web Server Authentication, TLS Web Client Authentication [subjectAltName] => DNS:www.google.com [authorityInfoAccess] => CA Issuers - URI:http://pki.google.com/GIAG2.crt OCSP - URI:http://clients1.google.com/ocsp [subjectKeyIdentifier] => FD:1B:28:50:FD:58:F2:8C:12:26:D7:80:E4:94:E7:CD:BA:A2:6A:45 [basicConstraints] => CA:FALSE [authorityKeyIdentifier] => keyid:4A:DD:06:16:1B:BC:F6:68:B5:76:F5:81:B6:BB:62:1A:BA:5A:81:2F [certificatePolicies] => Policy: 1.3.6.1.4.1.11129.2.5.1 [crlDistributionPoints] => URI:http://pki.google.com/GIAG2.crl ) ) A: No. EDIT: A CURLINFO_CERTINFO option has been added to PHP 5.3.2. See http://bugs.php.net/49253 Apparently, that information is being given to you by your proxy in the response headers. If you want to rely on that, you can use curl's CURLOPT_HEADER option to trueto include the headers in the output. However, to retrieve the certificate without relying on some proxy, you must do <?php $g = stream_context_create (array("ssl" => array("capture_peer_cert" => true))); $r = fopen("https://www.google.com/", "rb", false, $g); $cont = stream_context_get_params($r); var_dump($cont["options"]["ssl"]["peer_certificate"]); You can manipulate the value of $cont["options"]["ssl"]["peer_certificate"] with the OpenSSL extension. EDIT: This option is better since it doesn't actually make the HTTP request and does not require allow_url_fopen: <?php $g = stream_context_create (array("ssl" => array("capture_peer_cert" => true))); $r = stream_socket_client("ssl://www.google.com:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $g); $cont = stream_context_get_params($r); var_dump($cont["options"]["ssl"]["peer_certificate"]); A: To do this in php and curl: <?php if($fp = tmpfile()) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"https://www.digicert.com/"); curl_setopt($ch, CURLOPT_STDERR, $fp); curl_setopt($ch, CURLOPT_CERTINFO, 1); curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); $result = curl_exec($ch); curl_errno($ch)==0 or die("Error:".curl_errno($ch)." ".curl_error($ch)); fseek($fp, 0);//rewind $str=''; while(strlen($str.=fread($fp,8192))==8192); echo $str; fclose($fp); } ?> A: This could done the trick [mulhasan@sshgateway-01 ~]$ curl --insecure -v https://yourdomain.com 2>&1 | awk 'BEGIN { cert=0 } /^\* SSL connection/ { cert=1 } /^\*/ { if (cert) print }'
unknown
d5763
train
You can use a simple regular expression for this: boolean matches = s.matches("^X+Y*$"); This means: * *^ matches the start of the string *X+ means one or more consecutive Xs *Y* means zero or more consecutive Ys *$ is the end of the string Alternatively, you can check the string character-wise: int i = 0; while (i < s.length() && s.charAt(i) == 'X') { ++i; } if (i < s.length()) { if (s.charAt(i) != 'Y') { return false; } while (i < s.length() && s.charAt(i) == 'Y') { ++i; } } return i == s.length(); A: You can use the following regular expression to detect the particular pattern. String pattern = "^(X){1,}Y*$"; Here's the complete java code, import java.util.regex.Matcher; import java.util.regex.Pattern; public class PatternMatch { public static void main(String[] args){ // String to be scanned to find the pattern. String line = "XXXXY"; String pattern = "^(X){1,}Y*$"; // Create a Pattern object Pattern r = Pattern.compile(pattern); // Now create matcher object. Matcher m = r.matcher(line); if (m.find( )) { System.out.println("Found value: " + m.group(0) ); } else { System.out.println("NO MATCH"); } } }
unknown
d5764
train
A single & is a bitwise AND, which means that the result is the bits that are set on BOTH left and right side of the operator. As an example 15 & 7 or as they are represented in binary: 1111 & 0111 The bitwise AND will result in the a number with the common bits set: 1111 & 0111 = 0111 When you make the (a & 1) you are testing whether the least significant bit (lsb) is set, since you are performing a test like this: a & 00000001 If a had the bitwise value: 00000110 then the result would be 0, since there are no common bits set, if a had the bitwise value: 00000111 then the result would be 1 since the lsb is set on a. This is used for different situations, if the lsb is set you know that the number is odd, so this test is really whether the number is odd or not (1, 3, 5, 7, ...). Looking at the first part of your solution: a * (a & 1) you are multiplying a with the value of (0 or 1 remember), 1 if a is odd, and 0 if it is even. A: Here & is a Bitwise Operator(works on bits and perform bit-by-bit operation).For more details see this and this
unknown
d5765
train
The function is called after excecuting the block of code, so the var location was assigned a value after it was adressed, this is why you saw undefined. There are two ways to fix this, 1) put the block of code inside the function or 2) call the function directly after initializing it ! General tip: do not use the ready function instead put the script just before body tag ends and avoid many problems !
unknown
d5766
train
"why is it critical to determine whether or not the value is an array?" Because trim expects a string and the function might not work when passing an array. It has nothing to do with security.
unknown
d5767
train
I was running MediaWiki 1.16.0. I upgraded to MediaWiki 1.16.2 and this resolved the issue.
unknown
d5768
train
With WScript.CreateObject("WScript.Shell") .Environment("PROCESS")("PATH") = .ExpandEnvironmentStrings(Replace( _ .Environment("USER")("PATH") & ";" & .Environment("SYSTEM")("PATH"), ";;", ";" _ )) End With This will overwrite the in memory current process PATH environment variable with the information retrieved from registry for the user and system environment variables. note: Previous code only updates the environment copy of the [c|w]script process that executes the code. It does not update the installer's copy of the environment (you can not update another process environment). A: Alternately, from jscript (still the cscript interpreter, but the jscript language) // Re-read PATH vars in case they've changed var shell = new ActiveXObject("WScript.shell"); var newPath = (shell.Environment("USER")("PATH") + ";" + shell.Environment("SYSTEM")("PATH")).replace(/;;/g, ";"); // Expand any %STRINGS% inside path and set to the new running process shell.Environment("PROCESS")("PATH") = shell.ExpandEnvironmentStrings(newPath); shell.Exec('myprocess.exe'); // throws exception if not found
unknown
d5769
train
Is there a specific reason that you are using Transform.Try using ora:getElement('/thresholdRequestInterface /thresholdRequest',bpws:getVariable(loopCounter))
unknown
d5770
train
My guess would be that you're spending a lot of time in the serializer. Put a trace target in the app and watch the console when it runs to see what's being sent. The most likely problems are from DisplayObjects - if they've been added to the application they will have a reference to the application itself, and will cause some serializers to start serializing the entire app. The bindable object might have some odd events attached that eventually attach to DisplayObjects - try copying the relevant values in it into your object instead of just taking a reference to the existing object.
unknown
d5771
train
Try to install ngCordova Media plugin. Install ngCordova, and inject in your app module 'ngCordova'. * *See de following steps *Install plugin *If you want create a service to provide a media resources see (Not required)
unknown
d5772
train
Is this what you want? x = 0:.01:1; y1 = 5+sin(2*pi*x); y2 = y1-1; y3 = y1+1; %// example values fill([x x(end:-1:1)],[y3 y1(end:-1:1)],[.6 .6 .6]) %// light grey hold on fill([x x(end:-1:1)],[y2 y1(end:-1:1)],[.4 .4 .4]) %// dark grey
unknown
d5773
train
Use php's in_array instead of trying to compare a string. To get the id of the query where you insert the form data, you can return the id of the insert row from your prepared statement. if ($form_data->action == 'Insert') { // assuming $age, $date, $first_name, $last_name // already declared prior to this block $data = array( ':date' => $date, ':first_name' => $first_name, ':last_name' => $last_name, ':age' => $age ); $query = " INSERT INTO tbl (date, first_name, last_name, age) VALUES (:date, :first_name, :last_name, :age) "; $statement = $connect->prepare($query); if ($statement->execute($data)) { $message = 'Data Inserted'; // $id is the last inserted id for (tbl) $id = $connect->lastInsertID(); // NOW you can insert your child row in the other table $ages_to_insert = array(28, 30, 25, 21); // in_array uses your array...so you don't need // if($form_data->age == $age_str){ if (in_array($form_data->age, $ages_to_insert)) { $query="UPDATE tbl SER VE = '8' WHERE id= '".$id."'"; $statement2 = $connect->prepare($query); $statement2->execute(); } } }
unknown
d5774
train
The issue was I had two php.ini, one from XAMPP and the other one inside another folder from a previous installation. Due to the fact that the PATH variable is pointing to the old one, than it wasn't picking my changes. Fixed via uncommenting the correct php.ini
unknown
d5775
train
a. \d implies digit. b. + sign implies one or more occurance of previous character. c. \. -> since . is a special character in regex, we have to escape it with \. d. Also, \ is a special escape character in java , hence from java perspective we need to add an additional \ to escape the backslash (\). Thus, the pattern will reprent any number like: 0.01, 0.001, 1.0001, 100.00001 and so on. Basically any decimal number with a digit before and after the decimal point. A: The regex is a simplified version to recognize floating-point numbers: At least one digit optionally followed by a dot and at least a digit. It's simplified because it only covers only number without a sign (i.e. only positive numbers, because you can't provide a - minus sign), it allows number presentations that are considered invalid, e.g. 000123.123 and lacks the support of numbers written in scientific syntax (e.g. 1.234e56).
unknown
d5776
train
In Unit Tests, you should only test your controller's Java code, without using any Servlet technology. In integration tests you can do one of several things: Use the org.springframework.mock.web package in the spring-test artifact, which contains Mock Objects for request, response, servletContext to fire fake requests at your controllers and read the data from the fake responses. Or use a web testing framework like Selenium that works against a deployed webapp. A: How do I test that this create() method gets called when somebody requests http://example.com/create url. Looks really like a integration test. Sean Patrick Floyd already mentioned some ways how to test that, but to my understanding none of this options really tests that a request to an url really invokes the method. -- The mocking way simulates the request and the selenium test tests only the return value, but not the Invocation. -- Don't get my wrong, I believe that this two other tests are in most cases better (easyer to test and even more valid test results), but if you really want to test the invokation I would come up with this solution. Use a web testing framework like Selenium (or Selenium 2/Webdriver) or only a simple one that only generates HTTP requests. -- To do that tests you will need of curse the deployed application. -- so it is realy an integration test. To check that the method is invoked. I would recommend to use a logging tool (Log4J). Then use a Tool like AspectJ or Spring AOP Support to add logging statements to your controller method. The logging should be written to some logger that writes to an other destination then the other loggers you use. At the end the last step is, that you need to verify that the expected logging statement is is the logfile after the test sends the http request. (Pay attention to the fact, that the logging may is asynchronous.)
unknown
d5777
train
Since products is list of Product, you have to iterate over that list. On thymeleaf you can use th:each attribute to do iteration. So for your case you can use something as below. Give it a try. <th:each="product,iterStat: ${products}" th:if="${iterStat.index} <3"> I am not entirely sure but based on your question you wanted only first three objects. For this you can use status variable that are defined in th:each. More detail you can find here. A: Here's the way you do it with the #{numbers} context object. <th:block th:each="i: ${#numbers.sequence(0, 2)}" th:with="product=${products[i]}"> <a th:class="production_Page" th:href="@{'product/'+${product.id}}"> <p th:text="${product.productName}"/> </a> <a th:class="production_Page" th:href="@{'productDelete/'+${product.id}}">Delete</a> <a th:class="production_Page" th:href="@{'productEdit/'+${product.id}}">Edit</a> <img th:class="productImage" th:src="${product.pathImage}"/> <br/> </th:block>
unknown
d5778
train
instead of : .nav ul li{ width: 100%; } use: .nav li{ width: 100%; margin-bottom: 0; } if you don't want to have a margin .nav{ margin: 0; padding: 0; } A: I'm not entirely sure what you'd like it to look like with 100% width. If you give a little more information I can help further. However, I noticed a few things that might be confusing your CSS. 1) The height is showing as "0" due to a float being applied to the list items. When you apply float to your items they are removed from the normal flow of the document. To solve, try first removing this: .nav li { float: left; } 2) Most browsers add default padding and/or margin to ol and ul I recommend you reset, and then try to style. RESET: ul { margin: 0; padding: 0; } TARGET RE-STYLE: .nav { margin: /* your style here */; padding: /* your style here */; } A: This .nav ul li{ width: 100%; } is saying : * *an element with class .nav *with a descendant of type ul *with a descendant of type li Since .nav is a class of your ul, and not of an ancestor of your ul, you should use ul.nav li { width: 100%; } that instead means : * *an element of type ul with class .nav *with a descendant of type li EDIT: for the margin problem, you should probably use position: relative; instead of position: absolute;, that should not be used if not completely aware of how it works
unknown
d5779
train
Actually, this code works. I just didn't built full app, I tested it trough sublime build for node-webkit. Preforming full build with grunt solved every spawn issues.
unknown
d5780
train
You first attempt is almost right, just don't echo each row, collect the result then echo: while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $rows[] = $row; } echo json_encode($rows);
unknown
d5781
train
Editing XML in AS3 is actually pretty easy and pretty basic - it's a core part of AS3. AS3 automatically adds nodes as you call them, like so: var xml:XML = <data />; xml.player.money = 15831; xml.player.shiptype = 1; xml.player.ship.fuelCur = 450; Will result in: <data> <player> <money>15831</money> <shiptype>1</shiptype> <ship> <fuelCur>450</fuelCur> </ship> </player> </data> Then to add multiples of the same node, just start a new XML object of the type you want, and append it to the XML object you're working on. Or skip the separate xml object entirely. Repeat as many times as needed: var segment:XML = <planet />; xml.appendChild(segment); // xml.planet[0] xml.appendChild(segment); // xml.planet[1] xml.appendChild(<planet />); // xml.planet[2] //etc... Then you can add values to them by their indexes. //Assuming this is the 4th planet you've added... xml.planet[3].population = 29827632; A: In FlashDevelop, try creating a separate XML file entirely. That will give you better code prompting. For XML, though, I have found that Adobe's rudimentary docs on their XML class has a wealth of useful examples and tools for creating and using XML objects.
unknown
d5782
train
So I'm answering my own question here because I contacted PayPal tech support and was told that the GetVerifiedStatus API is now deprecated and can't be used. This is the reason for the error.
unknown
d5783
train
Linq way: int min = 3; int max = 10; int increments = 15; Enumerable .Range(min, max - min + 1) .Concat(Enumerable .Range(min, max - min + 1) .Reverse() .Skip(increments % 2)) .ToArray(); A: This should work: public static IEnumerable<decimal> NewMethod(decimal min, decimal max, int count) { var increment = (max - min) / (int)((count - 1) / 2); for (var i = min; i < max; i += increment) yield return i; if (count % 2 == 0) yield return max; for (var i = max; i >= min ; i -= increment) yield return i; } Sample test: var min = 3.0m; var max = 10.0m; var count = 16; MessageBox.Show(string.Join(", ", NewMethod(min, max, count))); Edit: You have to cope with floating point types losing precision, otherwise you will be missing an element in the final result set. Tinker a bit with Math.Round over the i += and i -= part, that's up to you. I have updated code to replace double with more reliable decimal type. But there is no guarantee this should not fail every time. Easier is to avoid cases where you will need decimal types in the result like { 1, 2.2, 3.4 } etc. A: Here's a one-way ramp that handles floating point values correctly. You should be able to modify it to make a triangle waveform. When implementing a ramp, care must be taken to make sure not to accumulate either round-off errors, or off-by-one errors for various inputs. void Packet::SetRamp( const SampleType start /*= Signal::One*/, const SampleType finish /*= -Signal::One */ ) { SampleType slope, current; SampleOffsetType len; len = GetLength(); if ( len < 2 ) throw std::range_error( "packet is not large enough to set ramp into" ); slope = ( finish - start ) / ( len - 1 ); for ( SampleOffsetType row = 0; row < len; row++ ) { current = slope * row + start; SetSample( row, current ); } }
unknown
d5784
train
IS your host allows to load images from external source. means out side of server ? This may be a problem. A: HostGator do not allow absolute paths to use with TimThumb (even if it's hosted in your own account) as described in this article: http://support.hostgator.com/articles/specialized-help/technical/timthumb-basics. To fix the absolute path issue, you'll would need to hack your theme functions to strip off your domain from the image path: $url = "/path/to/timthumb.php?src=" . str_replace(site_url(), '', $path_to_image);
unknown
d5785
train
You can create a dictionary that relates the number to the image name. You can use the following syntax: std::map<char, const char*> my_map = { { '1', 'hero.png' }, { '2', 'wall.png' }, { '3', 'monster.png' } }; And you can search by the number inside this map. The docs are: http://www.cplusplus.com/reference/map/map/
unknown
d5786
train
You should only have one long-living DeviceClient instance. Especially if you are using MQTT or AMQP as transport protocol, the DeviceClient will open the connection - and keep it open. Over that open connection it will send the messages. And also the for cloud-to-device messages / twin updates, the same channel is used. Also, the client usually handles any connection-retry logic so you don't have to deal with that manually.
unknown
d5787
train
This is all very possible in PHP, but what you are asking is for an explanation that requires a book. Speaking of books, there are tons of great books offering help with exactly what you need: PHP 5 CMS Framework Development: Would teach you about many of the pieces you are trying to assemble by hand including MVC principles. "Obviously there is no standard open source package.." Just to name one, WordPress allows users to log in and add stuff to a daily log (it's called a blog), has content sections, and has forum and commerce plugins. Personally, I've been amazed at how customizable WordPress is! A: I don't understand your comment about using cookies instead of sessions. I recommend you use the PHP $_SESSION superglobal to keep users logged in during their session. If you have super-sensitive data in these logs, one option might be to verify that the user's IP has not changed between requests. I see no reason why ASP.net would be preferable. Personally, I like to learn programming by opening up vim and going at it. P.S. Be sure you are escaping data provided to you by users before writing it to your SQL database.
unknown
d5788
train
Try putting these settings in Tomcat startup script: export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 export LANGUAGE=en_US.UTF-8 From experience, Java will print up-side-down question mark for characters it does not know how to encode. A: The filename is indeed in UTF-8 in the zip .war file. try (ZipFile zipFile = new ZipFile(path, StandardCharsets.UTF_8)) { zipFile.stream() .forEachOrdered(entry -> System.out.printf("- %s%n", entry.getName())); } catch (IOException e) { e.printStackTrace(); } However the zip does not has added the encoding (as bytes[] extra information). Three solutions would be imaginable: * *One short solution might be to run TomCat under a UTF-8 locale. *The best would be to have maven build a war with UTF-8 encoding. (<onfiguration><encoding>UTF-8</encoding></configuration>) *Repairing the war by converting it. With the first two solutions I have no experience. A quick search didn't yield anything ("encoding" is a bit ubiquitous). The repair code is simple: Path path = Paths.get(".../api.war").toAbsolutePath().normalize(); Path path2 = Paths.get(".../api2.war").toAbsolutePath().normalize(); URI uri = URI.create("jar:file://" + path.toString()); Map<String,String> env = new HashMap<String,String>(); env.put("create", "false"); env.put("encoding", "UTF-8"); URI uri2 = URI.create("jar:file://" + path2.toString()); Map<String,String> env2 = new HashMap<String,String>(); env2.put("create", "true"); env2.put("encoding", "UTF-8"); try (FileSystem zipFS = FileSystems.newFileSystem(uri, env); FileSystem zipFS2 = FileSystems.newFileSystem(uri2, env2)) { Files.walkFileTree(zipFS.getPath("/"), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { System.out.println("* File: " + file); Path file2 = zipFS2.getPath(file.toString()); Files.createDirectories(file2.getParent()); Files.copy(file, file2); return FileVisitResult.CONTINUE; } }); } catch(IOException e) { e.printStackTrace(); }
unknown
d5789
train
Adding the field: @Id private String id; to my model seems to have resolved the issue.
unknown
d5790
train
First of all, serializer fields with (many=True) create nested objects. If you input data with Rooms as already serialized, then it means that you create other Rooms instances. It will be shown with if module_serializer.is_valid(): part. Therefore, if you intended to implement as just link already instantiated Rooms to Module, it's better to make it as primary key list. Here are my example codes. class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializer(many=True, read_only=True) def create(self, validated_data): rooms_data = validated_data['room_list'] module = Module.objects.create(**validated_data) for data in rooms_data.split(' '): room = Rooms.objects.get(room_id=data) module.rooms.add(room) return module def update(self, instance, validated_data): # Updating rooms rooms_data = validated_data.get('rooms') instance.rooms.clear() for room_data in rooms_data: room = Rooms.objects.get(**room_data) instance.rooms.add(room) # Updating other fields fields = [ 'title', 'desc', 'thumbnail', 'is_deleted', ] for field in fields: setattr(instance, field, validated_data[field]) instance.save() return instance class Meta: model = Module fields = '__all__' class AddModule(APIView): def post(self, request, format=None): # creating the module module_serializer = ModuleSerializer(data=request.data) if module_serializer.is_valid(): module_serializer.save() return Response(module_serializer.data['module_id']) return Response(module_serializer.errors) Any other parts are same as yours. Regardless of whether data are sent by form-data or json raw data, results are same as below.
unknown
d5791
train
context.times is an array containing activities, right? Well, in javascript, .length of an array represents the length of the array itself, so it represents how many activities you have. Javascript has no way to know what you're trying to sum or achieve. You need to sum the durations yourself by iterating the array of activities, so you need to have: const TimeTotal = ({ time }) => { const context = useContext(TimeContext); let totalDuration = 0; context.times.forEach((entry) => { totalDuration += entry.time; }); return <div className="time-total">Total: {totalDuration}</div> } A shorter version would be: const context = useContext(TimeContext); const totalDuration = context.times.reduce((total, entry) => entry.time + total, 0) const TimeTotal = ({ time }) => { const context = useContext(TimeContext)l const totalDuration = context.times.reduce((total, entry) => entry.time + total, 0); return <div className="time-total">Total: {totalDuration}</div> } You can read more about reduce here. A: You can use .reduce() method of Array, something like const timesSum = context.times.reduce((acc, {time}) => { return acc + time }, 0) Take into account that I assumed time as numeric type. In real life you may need to cast time to number on manipulate it's value the way you need. Maybe you'll have to format timesSum. Finally you'll have something like: const TimeTotal = ({ time }) => { const context = useContext(TimeContext) console.log(context) const timesSum = context.times.reduce((acc, {time}) => { return acc + time }, 0); return <div className="time-total">Total: {timesSum}</div> }
unknown
d5792
train
Use a JavaScript Modal popup! eg. JQuery UI Modal Popup A: its a browser property for the client,if he doesnt want to view these alerts. you cant remove that check box and message. if this message is shown then what the problem, leave it for the user. why you want to force him to view these alerts, it must be user's wish to see or not see these alerts. for better user experience and for your purpose you can use fancybox or facebox fancy box fiddler check this http://jsfiddle.net/BJNYr/ A: This is a browser matter, so you as a developer cant do anything with that behavior. Here is a similar question already answered here A: unfortunately you can't be sure that user has his browser settings with javascript alerts popup on ( that called with 'alert('...') function'). You should use javascript dialog plygin instead. For example: http://fancybox.net/
unknown
d5793
train
No, that's not a problem. It means that your objects come and go - you create them in scope, use them, and then they're eligible for GC. I don't think that's an indication that something's wrong. The other extreme would be an issue: objects are created, age, and stick around too long. That's where memory leaks and filled perm space happens. A: I think you do have a problem here. I'm not an expert on reading GC logs, but I think it is saying that you have a 'young' space of 76672K, and a total heap size of 11525824K. Furthermore, the total heap usage after each GC cycle is 10765868K ... and growing. And it is (apparently) spending ~30% of its time garbage collecting. My diagnosis is that your heap is nearly full, and you are spending a significant (and increasing) percentage of time garbage collection as a direct result. My advice would be restart the application (short term), and look for memory leaks (long term). If there are no memory leaks (i.e. your application is using all of that heap space) then you need to look for ways to reduce you application's memory usage. Your application does seem to be generating a fair bit of garbage, but that is not necessarily a worry. The HotSpot GCs can reclaim garbage pretty efficiently. It is the amount of non-garbage that it has to deal with that causes performance issues.
unknown
d5794
train
I need a way of determining which particular class of the 5 classes called the IntentService, so the appropriate action is taken. Put an extra on the Intent that you pass to startActivity() that indicates what the IntentService should do. You get a copy of that Intent in onHandleIntent() in the IntentService, so you can retrieve the extra and take appropriate steps based upon its value. A: At the top of the activity I add:- private final static String THIS_ACTIVITY = "AddProductToShopActivity"; for the intent I add: intent.putExtra("CALLER", THIS_ACTIVITY); In the started activity :- final String caller = getIntent().getStringExtra("Caller");
unknown
d5795
train
This is what I ended up adding to my proguard-project.txt file: # Needed by google-api-client to keep generic types and @Key annotations accessed via reflection -keep public final class * -keep public class * -keepclassmembers class * { public <fields>; static <fields>; public <methods>; protected <methods>; } -keepclassmembers class * extends com.google.api.client.json.GenericJson{ public <fields>; static <fields>; public <methods>; } -keepattributes Signature,RuntimeVisibleAnnotations,AnnotationDefault
unknown
d5796
train
Yes this is absolutely possible. The less files just get compiled into css in the pub directory. To add your own static css files you will just put them in your css directory (/app/design/frontend/{vendor}/{theme}/web/css) and they will be accessed just like any less compiled css file. Depending on your magento configuration you may need to first run bin/magento setup:static-content:deploy from your magento installation's root directory.
unknown
d5797
train
The fastest way I usually do this is using find > replace... Do something like this: * *Select the cells that have the formulas you want *Use the find > replace feature in excel and replace all = with some other, unused character (I usually use #) - This will change them from formulas to plain text *Copy those cells and paste them where you want *Use the find > replace feature to replace that other character back to = In effect, you are changing the formula to text, copying and pasting it as the plain text (so preserving the cell references), then changing it back to the original formula. Hope this helps and makes sense.
unknown
d5798
train
in your code, you have created from HardwareDetailApp in two place, in every creation of that you must set the same property with same order. for example if in linq to entity you Select something like: Place1: ... Select new MyClass() { PropA: 1, } ... and in that query you need to another Select from MyClass but with some other properties like PropB, Like: Place2: ... Select new MyClass() { PropB: 2, } ... you must change all Select from MyClass into same, and set the properties you dont need to them, to its default, and set the properties in same order like: Place1: ... Select new MyClass() { PropA: 1, PropB: default(int), } ... and Place2: ... Select new MyClass() { PropA: default(int), PropB: 2, } ... my codes are in c#.. in this part of your code Dim Data = (From p In DB.TT_HARDW .... try to set Firmware and SerialNum at first like the second select, (i have not checked other properties carefully)
unknown
d5799
train
If you don't want to add a scroll bar, and you don't want to rearrange the widgets, then the only options left are * *Lay the items out on more than one window (two pages for example). *Change the scaling of the items (shrink them) There is not an infinite number of approaches. The more approaches you decide are unsuitable will limit the opportunities to address the key issues. In your case, you have two dramatically different screen layouts, the obvious solution would be to detect the screen parameters, and select one of two different layouts, each tailored to look good. A: Too much controls in a window is much boring. So why don't you categorize the controls and add them in different tabs using JTabbedPane ? A: I think this is more suitable. If this is not desired, then adding a scroll pane would be better. Well shrinking the controls may not be that helpful
unknown
d5800
train
You misunderstood the way Random is used: it is not a number, it is a class that can be used to generate random numbers. Try this: // Make a generator Random gen = new Random(); // Now we can use our generator to make new random numbers like this: int num1 = gen.Next(); int num2 = gen.Next(); Every time you call gen.Next() you get a new random number. If you would like the sequence of random numbers to be repeatable, pass a number (any number) to the constructor of the Random. Beware that every time you run your program the result will stay the same. A: There are quite a few issues with the code snippet you pasted. I'd suggest (if you haven't already) investing in a decent beginning C# book. Generating random numbers, in fact, is one of the most popular "example programs" you find in those kinds of books. However, to get you started, here's some key points: * *When you paste sample code to a site like this, make sure it is a short, self-contained, correct example. Even if we fix the compiler error in your code, there are several other issues with it, including unbalanced and/or missing braces. Start simple and build your example up until you get the error, then paste that code. Note that a good 75% of the time this will help you fix the error yourself. For example, if you removed the lines of code that did not compile, and just ran the first part, it would print out "What is System.Random - System.Random?", which should give you a pretty clear idea that your num1 and num2 are not what you thought they were. *As the rest of the answers here have pointed out, you have a fundamental misunderstanding of how the C# Random class works. (Don't feel bad, computer-generated "random numbers" make no sense to anyone until someone explains them to you.) The solution provided in those answers is correct: Random is a random number generator, and you need to call one of the Next functions on your instance to get an integer from it. Also, you usually will not want multiple instances of Random unless you actually want to produce the same random sequence more than once. The MSDN article has a very thorough example. *While not "wrong" per-se, you're not being very efficient with your console output. Console's read and write functions operate entirely on string objects, and they have built-in composite formatting capabilities. For example, your first few lines of code could be rewritten as: var random = new Random(); var x = random.Next(); var y = random.Next(); Console.Write("What is {0} + {1}? ", x, y); *As I mentioned in my comment, Console.Read() is not the correct function to read in complete user input; it returns data a single UTF-16 character at a time. For example, if the user typed in 150 you would get 49, 53, and 48, in that order. Since you presumably want to allow the user to type in more than one digit at a time, you should instead called Console.ReadLine(), which returns the entire string, then convert that to an integer using Int32.Parse() or some similar function. A: You are trying to add two random generators not random numbers, use this: Random randomGenerator = new Random(0); var num1 = randomGenerator.Next(); var num2 = randomGenerator.Next(); A: You need to call one of the overloads of Random.Next() http://msdn.microsoft.com/en-us/library/9b3ta19y.aspx to get the actual random number.
unknown