_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d7501
train
As much as I didn't want to, I ended up writing my own directive for my charts and now I have complete control over the charts without having to write a ton of code to undo what angularjs-nvd3-directives did in a callback.
unknown
d7502
train
Use coord_map, like this. Full explanation here. ggplot() + geom_polygon(aes(x = long, y = lat, group = group), data = mp) + coord_map(xlim = c(-180, 180)) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())
unknown
d7503
train
Choose a string a^2p b^p. The pumping lemma says we can write this as w = uvx such that |uv| <= p, |v| < 0 and for all natural numbers n, u(v^n)x is also a string in the language. Because |uv| <= p, the substring uv of w consists entirely of instances of the symbol a. Pumping up or down by choosing a value for n other than one guarantees that the number of a's in the resulting string will change, while the number of b's stays the same. Since the number of a's is twice the number of b's only when n = 1, this is a contradiction. Therefore, the language cannot be regular. A: L={anbm|n=2m} Assume that L is regular Language Let the pumping length be p L={a2mbm} Since |s|=3m > m (total string length) take a string s S= aaaaa...aabbb....bbb (a2mbm times taken) Then, u = am-1 ; v= a ; w= ambm. && |uv|<=m Now If i=2 then S= am-1 a2 ambm = a2m-1bm Since here we are getting an extra a in the string S which is no belong to the given language a2mbm our assumption is wrong Therefore it is not a regular Language
unknown
d7504
train
As mentioned by Samcarter, when using tex you need to also be aware of any tex-related special meanings. In this instance - the "_" symbol is used in tex math mode for signalling a subscript is about to follow. When passing my R strings that contained "_" into the tex expression it would throw an error as the "_" is reserved for math mode (unless escaped) - this is why I got no error when I enclosed it with $...$ The solution for me was to add in escapes before every tex special character: #original words <- c("plz_work","better_yet","what_is_this") #modified version. Replace collapse with other tex functions if needed words2 <- lapply(strsplit(words,"_"), paste, collapse = '\\_') for (i in 1:3) { cat('\\subsection{',words2[[i]],'}') } The underscores here are a little long for my liking but you can easily replace the 'collapse' argument to something else which you prefer eg. ... collapse ='\\textunderscore ') ... also works
unknown
d7505
train
I get the same issue. Definitely a bug in the Design Editor. My work around was to: * *Style the email with the Design Editor. *Export HTML. *Go back and create a new version of the transaction email using the 'Code Editor' and not the 'Design Editor'. *Paste in the previously exported HTML. *Find the table that needs the {{each}} loop and place the functions exactly as you did. A: I found a undocumented way to make this works. You will need to comment out the each helper like this: <table> <tbody> <!-- {{#each items}} --> <tr> <td>Col 1</td> <td>Col 2</td> </tr> <!-- {{/each}} --> </tbody> </table>
unknown
d7506
train
There's no reason to get an object from the request in Struts2. If you are using Struts2 tag you can get the object from the valueStack via OGNL. However in Struts2 is possible to get the value from the request attributes using OGNL. For this purpose you should access the OGNL context variable request. For example <s:select list="%{#request.repTypList}" listKey="id" listValue="val" /> The select tag requires not null value returned via OGNL expression in the list tag, as a result of null value you got the error. So, better to check this in the action before the result is returned. public class showSchdulesAction extends ActionSupport public String execute() throws Exception { ... HttpServletRequest request = ServletActionContext.getRequest(); List list = someObj.getCommonList(); if (list == null) list = new ArrayList(); request.setAttribute("repTypList", list); ... } } This code will save you from the error above. A: Did you try like this.. list="%{#repTypList}" OR list="%{#request.repTypList}" in struts 2 select tag
unknown
d7507
train
I forgot to add the doc ID to the gameData before adding it to the results. I did that in the "added" section, but not in the "modified" section (thinking that it was already included), forgetting that I hadn't added it as an actual field in the database (it just exists as the doc id).
unknown
d7508
train
You should use the JSON package (that is built-in python, so you don't need to install anything), that will convert the text into a python object (dictionary) using the json.loads() function. Here you can find some examples. A: You can use following code snippet: import requests, json response = requests.get('https://clinicaltrials.gov/api/query/study_fields?expr=heart+attack&fields=NCTId%2CBriefTitle%2CCondition&min_rnk=1&max_rnk=&fmt=json') jsonResponse = json.loads(response.content)
unknown
d7509
train
Jetpack Media3 has launched! https://developer.android.com/jetpack/androidx/releases/media3 This blog post gives a great explanation about how the media libraries evolved. I strongly recommend integrating with androidx.media3. If for whatever reason you cannot use androidx.media3, my recommendation is to stick with androidx.media instead of androidx.media2 due to the latter not being supported by other media integrations, such as Cast Connect. Integrating Media2 with ExoPlayer is also quite a bit more complex. From my perspective, the key benefit of switching from Media1 to Media2 is the ability to provide more fine-grained permission controls. See Jaewan Kim's blog post that goes in depth about the more complex SessionPlayerConnector API and permissions to accept or reject connections from a controller in media2. If you have an existing Media1 implementation using MediaSession (preferably using ExoPlayer with MediaSessionConnector), and have no need for the permission controls in Media2, you can either stick with Media1 or upgrade to Media3. The “What's next for AndroidX Media and ExoPlayer” talk from Android Dev Summit 2021 goes much more in depth on Media3. A: All the documentation I was able to find was useless and outdated. androidx.media and the appcompat media libraries are both superseded by androidx.media2 (but not deprecated for some reason). The most high-level API for media apps appears to be MediaLibraryService for the service and MediaBrowser for the frontend. Just make absolutely sure you declare the right intent filters on the service (which are in the javadoc :P) A: Here is my working solution using Media2 libs (AndroidX): * *Add 3 dependencies in Build.gradle implementation "androidx.media2:media2-session:1.2.0" implementation "androidx.media2:media2-widget:1.2.0" implementation "androidx.media2:media2-player:1.2.0" *Create layout activity_video_player.xml and put this code into it: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/accompany_agent_details" style="@style/Layout.Default"> <LinearLayout android:id="@+id/videoLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:orientation="vertical"> <android.widget.VideoView android:id="@+id/simpleVideoView" android:layout_width="match_parent" android:layout_height="300dp" /> </LinearLayout> </RelativeLayout> <style name="Layout.Default"> <item name="android:layout_width">match_parent</item> <item name="android:layout_height">match_parent</item> </style> *Create activity class SimpleVideoActivity: public class VideoPlayerActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_player_android_x); VideoView simpleVideoView = findViewById(R.id.simpleVideoView); MediaMetadata mediaMetaData = new MediaMetadata.Builder().putString(MediaMetadata.METADATA_KEY_TITLE, "Put your video text here").build(); UriMediaItem item = new UriMediaItem.Builder(Uri.parse("Put your video URL here")).setMetadata(mediaMetaData).build(); MediaPlayer mediaPlayer = new MediaPlayer(this); simpleVideoView.setPlayer(mediaPlayer); mediaPlayer.setMediaItem(item); mediaPlayer.prepare(); mediaPlayer.play(); } }
unknown
d7510
train
Looks like holes was never initialized for beaver prototypes. Try modifying the constructor function to look like so. var Beaver = function(x, y) { this.x = x; this.y = y; this.img = getImage("creatures/Hopper-Happy"); this.sticks = 0; this.holes = 0; }; Performing a ++ operation on an undefined variable returns a NaN result.
unknown
d7511
train
The most "quicker" way to iterate an array in javascript is: var i; for (i = myarray.length; i--;) { console.log(myarray[i]); } Iteration counter in a reverse order - from the biggest number to zero, usually increases the speed, because operation of comparison with 0 is a little more effective, than operation of comparison with array length or with any other number, different to 0. To iterate object inside of each array element you can use for in cycle: var i, j; for (i = myarray.length; i--;) { for (j in myarray[i]) { console.log(j, myarray[i][j]); } } A: With lodash: _.forEach(operationalHours, function(el, key) { }); You can also find element: var items = _.findWhere(operationalHours[0], {"opens": "11: 30AM"})
unknown
d7512
train
I suggest you to use a simple bash script like that: #!/bin/bash OLD="old-domain.com\/_img" NEW="cdn1.cdn.com\/_img" DPATH="/home/of/your/files/*.html" for f in $DPATH do sed "s/$OLD/$NEW/g" "$f" > temp; mv temp "$f"; done It replaces old-domain.com/_img with cdn1.cdn.com/_img on all your .html files on /home/of/your/files/. A: Are you actually writing HTML from FileMaker? If that's the case, and you want to manipulate the HTML using Perform AppleScript, then you can do something like the following. Best Practice: Always use "Native AppleScript" instead of "Calculated AppleScript". To get data in and out of AppleScript, create a pair of global fields for reading and writing between FileMaker and AppleScript. This helps you isolate AppleScript errors when talking to other applications so that they don't bleed into later script steps. (I prefer to create a Global table and create a table occurrence called @Global. In that Global table I create two fields: AppleScriptInput and AppleScriptOutput. Note that you must create a record in this table or you will get mysterious "object not found" errors in AppleScript.) Set Field [@Global::AppleScriptInput; $myHtml] Perform AppleScript [“ -- Read HTML from a global field in FileMaker set html to get data (table "@Global")'s (field "AppleScriptInput") -- Split html on old domain fragment set my text item delimiters to "<img src=\"http://old-domain.com/_img/" set html_fragments to text items of html -- Prefix resource with CDN domain fragment repeat with i from 2 to length of html_fragments set cdn_number to (i - 2) mod 6 + 1 set cdn_fragment to "<img src=\"http://cdn" & cdn_number & ".cdn.com/_img/" set item i of html_fragments to cdn_fragment & item i of html_fragments end repeat -- Re-join html fragments set my text item delimiters to "" set html to html_fragments as text -- Write html back to a global field in FileMaker set data (table "@Global")'s (cell "AppleScriptInput") to html ”] Set Variable [$revisedHtml; @Global::AppleScriptOutput] The above script steps will read the input you provided from the FileMaker variable $html and save the output you provided to $revisedHtml. You can do the same thing in pure FileMaker script of course: Set Variable [$html; "<p>Argle bargle.</p> <img src=\"http://old-domain.com/_img/image-a.jpg\"> <img src=\"http://old-domain.com/_img/image-b.jpg\"> <img src=\"http://old-domain.com/_img/image-c.jpg\"> <img src=\"http://old-domain.com/_img/image-d.jpg\"> <img src=\"http://old-domain.com/_img/image-e.jpg\"> <img src=\"http://old-domain.com/_img/image-f.jpg\"> <img src=\"http://old-domain.com/_img/image-g.jpg\"> <img src=\"http://old-domain.com/_img/image-h.jpg\"> <p>Whiz bang.</p>" ] Set Variable [$oldDomain; "http://old-domain.com/_img/"] Set Variable [$itemCount; PatternCount ( $html ; $oldDomain )] Loop Exit Loop If [Let ( $i = $i + 1 ; If ( $i > $itemCount ; Let ( $i = "" ; True ) ) )] Set Variable [$html; Let ( [ domainPosition = Position ( $html ; "http://old-domain.com/_img/" ; 1 ; 1 ); domainLength = Length ( "http://old-domain.com/_img/" ); cdnNumber = Mod ( $i - 1 ; 6 ) + 1 ] ; Replace ( $html ; domainPosition ; domainLength ; "http://cdn" & cdnNumber & ".cdn.com/_img/" ) ) ] End Loop Show Custom Dialog ["Result"; $html]
unknown
d7513
train
Its easy. Just define an action function to catch the values from the dataTable: 1) First defining three vars tht we will pass to controller: raw-id, cell-value, cell-type public String clickedRowId { get; set; } public String clickedCellValue { get; set; } public String clickedCellType { get; set; } public PageReference readCellMethod(){ System.debug('#### clickedRowId: ' + clickedRowId); System.debug('#### clickedCellValue: ' + clickedCellValue); System.debug('#### clickedCellType: ' + clickedCellType); return null; } 2) Second we create an action function, that calls our apex method an pass three vars to it: <apex:actionFunction name="readCell" action="{!readCellMethod}"> <apex:param name="P1" value="" assignTo="{!clickedRowId}"/> <apex:param name="P2" value="" assignTo="{!clickedCellValue}"/> <apex:param name="P3" value="" assignTo="{!clickedCellType}"/> </apex:actionFunction> 3) And third we create our dataTable, where each cell has onClick listener: <apex:pageBlockTable value="{!someArray}" var="item"> <apex:column value="{!item.name}" onclick="readCell('{!item.id}','{!item.name}','name')" /> <apex:column value="{!item.CustomField1__c}" onclick="readCell('{!item.id}','{!item.CustomField1__c}','custom1')" /> <apex:column value="{!item.CustomField2__c}" onclick="readCell('{!item.id}','{!item.CustomField2__c}','custom2')" /> </apex:pageBlockTable> We can access our actionFunction like any other JavaScript function. If user clicks on the cell - three vars will be send to the actionFunction and then to controller.
unknown
d7514
train
This error usually means that the uploading is cancelled by the user , and some times it can be server problem also which can cause this. Try to contact to your hosting provider and see what can he do
unknown
d7515
train
You can do this with the markup you suggested by positioning .hover-time relative to .bubble. To do this, add position: relative to .bubble and position: absolute to .hover-time. Here's some more info on the technique. <div class="bubble you"><span class="hover-time">13.45</span>Test Message</div> CSS for positioning timestamp to the right: .bubble { position: relative; } .hover-time { position: absolute; left: 110%; color: #999; } Same approach goes for positioning it to the left, but in this case you'll need to add a bit of margin to the bubble in order to free up space for the timestamp: .bubble { position: relative; margin-left: 50px; } .hover-time { position: absolute; left: -50px; color: #999; } A: <style> .hover-time { position: relative; left: 60px; display: none; } .bubble:hover .hover-time { background-color: #ccc; color: #000; display: inline-block; } </style> <div class="bubble you">Test Message <span class="hover-time">13.45</span></div> Works for me. You'll probably want to spice it up a little with some transform or other fancy anim stuff. EDIT: Perhaps you meant like so: <style> .bubble { border: 1px solid #ccc; width: 300px; } .hover-time { float: right; display: none; } .bubble:hover .hover-time { background-color: #ccc; color: #000; display: inline-block; } </style> <div class="bubble you">Test Message <span class="hover-time">13.45</span></div> Border and width just to have a visual guide. A: Maybe I'm misunderstanding, but are you styling the DIV as the speech bubble, then taking the span inside the div and telling it 'but not you buddy, you are special'? If so, isn't it cleaner and less headaches to put your text message in a span also, styling the span as text bubble, and keeping the div as an invisible structural element?
unknown
d7516
train
Whenever you're iterating with {{#each ...}} your helper should return either a cursor or an array. Your helper is returning a scalar: the count. In your {{#each }} block you refer to {{PTR}} and {{KOM}} but those won't exist. I suspect that you weren't actually looking for the count in this case and your helper should just be: Template.laporankategori.helpers({ profil: function() { return Profil.find({kategori: { $in: ['PTR', 'KOM'] } }); } }); Also you don't often need to count things in a helper since in a template you can refer to {{profil.count}} and get the count of the cursor directly. A: <template name="laporankategori"> <table class="table"> <thead> <tr> <th>Jenis Peralatan</th> <th>Kuantiti</th> </tr> </thead> <tbody> {{#each profil}} <tr> <td>{{count}}</td> </tr> {{/each}} </tbody> </table> </template> //js Template.laporankategori.helpers({ profil: function() { var PTR = { count: Profil.find({kategori: { $in: ['PTR'] } }).count() }; var KOM = { count : Profil.find({kategori: { $in: ['KOM'] } }).count() }; var resultArr = [PTR, KOM]; return resultArr; } });
unknown
d7517
train
You can transform values in handleSubmit function before passing it to api. const handleSubmit = (values) => { values.some_value = parseNumber(values.some_value); fetch(apiUrl, { body: values }) };
unknown
d7518
train
buf = urllib2.urlopen(URL).read() sbuf = StringIO.StringIO(buf) Image = wx.ImageFromStream(sbuf).ConvertToBitmap() wx.StaticBitmap(Panel, -1, Image, (10,10)) A: import requests import io url = "" content = requests.get(url).content io_bytes = io.BytesIO(content) image = wx.Image(io_bytes).ConvertToBitmap() staticImage = wx.StaticBitmap(Panel, wx.ID_ANY, image, wx.DefaultPosition, wx.DefaultSize, 0) replace url and Panel with your url and panel object
unknown
d7519
train
You could simply try to telnet from the server to itself. So if you'd want to check if port 443 is responding, run: telnet localhost 443 if the response is telnet: Unable to connect to remote host: Connection refused then there's probably nothing listening on that port.
unknown
d7520
train
Try this: { "description" : "schema validating people and vehicles", "type" : "object", "oneOf" : [ { "type" : "object", "properties" : { "firstName" : { "type" : "string" }, "lastName" : { "type" : "string" }, "sport" : { "type" : "string" } } }, { "type" : "object", "properties" : { "vehicle" : { "type" : "string" }, "price" : { "type" : "integer" } }, "additionalProperties":false } ] } A: oneOf need to be used inside a schema to work. Inside properties, it's like another property called "oneOf" without the effect you want.
unknown
d7521
train
Please refer : https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete If you look at the sample code in the 'JavaScript + HTML' section, the API allows you to set filters, for example, establishments. So, just set the types to your criteria and you should be good to go. Cheers, Mrugesh A: How to limit google autocomplete results to City and Country only You can refer this answer. function initialize() { var options = { types: ['(regions)'], componentRestrictions: {country: "us"} }; var input = document.getElementById('searchTextField'); var autocomplete = new google.maps.places.Autocomplete(input, options); }
unknown
d7522
train
You could use Object.assign persona = Object.assign({}, persona, { testing: function(){ console.log('Yes, I know'); } }); or persona.prototype.testing = function(){}; A: You should use prototype when you want to create one or more instances of a function. in your case initweb3 is a constructor function. make sure your constructor function starts with uppercase letter. For example: function Person(){ /*...*/ } Person.prototype.sayHi = function() { }; const p = new Person(); p.sayHi(); in your use case persona is already an instance object, if you want to add a new function to it you simply do persona.testing = function() {} OR You can also try extending the initweb3 function. initweb3.prototype.testing = function(){ /* code goes here */} . . . persona.testing(); Watch this video to learn more about prototypes in JavaScript. https://www.youtube.com/watch?v=riDVvXZ_Kb4
unknown
d7523
train
It's a list of dictionaries, three items in a list. Easier to see if using the pprint.pprint() module function: [{u'Adj_Close': u'35.83', u'Close': u'35.83', u'Date': u'2014-04-29', u'High': u'35.89', u'Low': u'34.12', u'Open': u'34.37', u'Symbol': u'YHOO', u'Volume': u'28720000'}, {u'Adj_Close': u'33.99', u'Close': u'33.99', u'Date': u'2014-04-28', u'High': u'35.00', u'Low': u'33.65', u'Open': u'34.67', u'Symbol': u'YHOO', u'Volume': u'30422000'}, {u'Adj_Close': u'34.48', u'Close': u'34.48', u'Date': u'2014-04-25', u'High': u'35.10', u'Low': u'34.29', u'Open': u'35.03', u'Symbol': u'YHOO', u'Volume': u'19391100'}] You can read them like: readings = yahoo.get_historical('2014-04-25', '2014-04-29') for reading in readings: print reading['Volume'] The high for the day could be: high_reading = max(readings, key=lambda reading: float(reading['High'])) (which is the max() function which returns the biggest thing in a sequence, provided with a custom function to say what it should look at when comparing the items). A: Why don't you use a syntax like: for dayData in dict to separate the values for each day and do the processing in the for loop with something like dayDict['Volume']. Then you can just add any details to a master array outside the loop for further processing or analytics later in the code.
unknown
d7524
train
To test if the kvm support is enabled in the current host (ie, it works in the virtual machine) do: grep -E "(vmx|svm)" /proc/cpuinfo flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc extd_apicid aperfmperf pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 popcnt aes xsave avx f16c lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs xop skinit wdt lwp fma4 tce tbm topoext perfctr_core perfctr_nb arat cpb hw_pstate npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold vmmcall bmi1 In the question: grep -E "(vmx|svm)" /proc/cpuinfo | wc -l 0 It means that the support is disabled, and enable-kvm won't work. Action in the bare metal machine is required. A: By default, Linux KVM has nested virtualization support disabled. You have to enable it in the host of the outermost VM (in your question you tried to do that inside the outermost VM, instead). For example, for an Intel CPU: # rmmod kvm_intel # modprobe kvm_intel nested=1 Verification (on the host of the outermost VM): $ cat /sys/module/kvm_intel/parameters/nested Y (The KVM module for AMD is unsurprisingly called kvm_amd.) Nesting can be enabled persistently via dropping a config file into /etc/modprobe.d. This is a necessary condition for nested virtualization. In addition to that, you need to tell QEMU to enable virtualization support in the outermost VM by supplying the right CPU argument, e.g.: -cpu host or something more specific like: -cpu Haswell-noTSX-IBRS,vmx=on Inside the outermost VM, you can verify virtualization support via: $ grep -o 'vmx\|svm' /proc/cpuinfo $ kvm-ok INFO: /dev/kvm exists KVM acceleration can be used
unknown
d7525
train
Use min-height See: http://jsfiddle.net/jN9SV/ <div id="wrapper"> <div id="left" style="float:left; width:15%; min-height:1px"> <span style="width:15%"; id="dog">Hi i'm a dog</span> </div> <div id="right" style="float:left; width:85%;"> <p>Hello world</p> </div> </div> A: Using float: right for the second division helps if you are dealing with just two divisions. <div id="wrapper"> <div id="left" style="float:left; width:15%;"> <span style="width:15%"; id="dog">Hi i'm a dog</span> </div> <div id="right" style="float:right; width:85%;"> <p>Hello world</p> </div> </div> A: See below - use a combination of "min-width" and change the right div to "float:right": <div id="wrapper"> <div id="left" style="float:left; width:15%; min-width:15%"> <span style="width:15%"; id="dog"></span> </div> <div id="right" style="float:right; width:85%;"> <p>Hello world</p> </div> </div>
unknown
d7526
train
Since your GameViewController is presenting your GameScene you can just hold a reference to it and get the score and high score from properties in your GameScene. Something like this: class GameViewController: UIViewController { var gameScene: GameScene! override func viewDidLoad() { super.viewDidLoad() // Hold a reference to your GameScene after initializing it. gameScene = SKScene(...) } } class GameScene: SKScene { var currentScore: Int = 0 var highScore: Int = 0 func updateScore(withScore score: Int) { currentScore = score highScore = currentScore > score ? currentScore : score } } Update: You could use this values in your pressedShareButton like this: func pressedShareButton(sender: UIButton!) { let currentScore = scene.currentScore let highScore = scene.highScore ... let myText = "WOW! I made \(currentScore) points playing #RushSamurai! Can you beat my score? https://itunes.apple.com/us/app/rush-samurai/id1020813520?ls=1&mt=8" ... }
unknown
d7527
train
There are a few things that need to be done here: * *If your app is going to render data dynamically, then your data should be assigned to some reactive expression. *Now the downloading of the data becomes easy, as you just call the reactive expression written in (1). * *Points (1) and (2) above will ensure that the user is downloading the same data that is seen on the screen. Try the following: library(shiny) ui <- fluidPage( titlePanel("Downloading Data"), sidebarLayout( sidebarPanel(downloadButton("downloadData", "Download")), mainPanel(tableOutput("table")) ) ) server <- function(input, output) { data <- shiny::reactive(data.frame(a = c(1, 2, 3), b = c("q", "s", "f"))) output$table <- renderTable(data()) output$downloadData <- downloadHandler( filename = function() { paste("test.csv") }, content = function(file) { write.csv(data(), file, row.names = FALSE) } ) } shinyApp(ui,server) A: You cannot export a renderTable{} as this puts many of the elements into HTML, you need to previously save the data going into the table and export it seperately. dataTable<-data.frame(a =c(1,2,3),b=c("q","s","f")) output$downloadData <- downloadHandler( filename = function() { ('test.csv') }, content = function(con) { write.table(dataTable,row.names = FALSE,col.names=T, sep=",",con) }, contentType="csv" )
unknown
d7528
train
<?php $entries = [ [111, '14/02/2020', 36], [222, '29/12/2019', 1], [222, '27/11/2019', 3], [333, '12/09/2019', 4], ]; $results = []; foreach ($entries as $entry) { $results[$entry[0]] = [ $entry[0], ($results[$entry[0]][1] ?? 0) + 1, ($results[$entry[0]][2] ?? 0) + $entry[2], ]; } $results = array_values($results); print_r($results); or <?php $entries = [ [111, '14/02/2020', 36], [222, '29/12/2019', 1], [222, '27/11/2019', 3], [333, '12/09/2019', 4], ]; $results = []; foreach ($entries as $entry) { if (!isset($results[$entry[0]])) { $results[$entry[0]] = [$entry[0], 0, 0]; } ++$results[$entry[0]][1]; $results[$entry[0]][2] += $entry[2]; } $results = array_values($results); print_r($results);
unknown
d7529
train
Don't use a RelativeLayout as your holder. Use a LinearLayout with orientation="vertical" instead. <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@+id/top_km" android:orientation="vertical" android:id="@id/textLayout" /> then in code myLayout = (LinearLayout) page.findViewById(R.id.textLayout); followed by // rest of your code A: It's because you use RealativeLayout for proper adding use 1. RelativeLayout.LayoutParams for st LayoutParams 2. In LayoutParams use field below Example: RelativeLayout rl=new RelativeLayout(this); LinearLayout ll1=new LinearLayout(this); TextView tx1=new TextView(this); tx1.setText("Test1"); ll1.addView(tx1); rl.addView(ll1); LinearLayout ll2=new LinearLayout(this); TextView tx2=new TextView(this); tx2.setText("Test1"); ll2.addView(tx1); rl.addView(ll2); RelativeLayout.LayoutParams lp2=(LayoutParams) ll2.getLayoutParams(); And then use lp2.addRule Here some help: Parameters verb One of the verbs defined by RelativeLayout, such as ALIGN_WITH_PARENT_LEFT. anchor The id of another view to use as an anchor, or a boolean value(represented as TRUE) for true or 0 for false). For verbs that don't refer to another sibling (for example, ALIGN_WITH_PARENT_BOTTOM) just use -1. A: Maybe it's easier for you to add it in the XML file with android:visibility="GONE" and then in the code just show it (View.VISIBLE) or hide it (View.GONE).
unknown
d7530
train
See the Prototype.js documentation $ — id (String | Element) — A DOM node or a string that references a node's ID $$(cssRule...) — Takes an arbitrary number of CSS selectors (strings) and returns a document-order array of extended DOM elements that match any of them.
unknown
d7531
train
I don't know if you're going to laugh at this or what because it's so far away from what you where expecting, but the main problem I see in this code is that you're trying to transpose items in a collection (Item1, Item2) to properties in an object ("Item1": 4, "Item2": 36), that forces me to think about dynamic creation of objects by using ExpandoObject class: (You have to install and import MoreLinq in order to use DistinctBy) var unitsNames = o["Assets"].SelectMany(a => a["Items"]).DistinctBy(i=>i["Name"]).Select(i=>i["Name"].ToString()); var allUnits=o["Assets"].SelectMany(a=>a["Items"]); var kgs=GetExpandoObject(unitsNames, allUnits,"KGs"); var cartons = GetExpandoObject(unitsNames, allUnits, "Cartons"); var containers = GetExpandoObject(unitsNames, allUnits, "Containers"); List<ExpandoObject> res = new List<ExpandoObject>() { kgs as ExpandoObject,cartons as ExpandoObject,containers as ExpandoObject }; string jsonString = JsonConvert.SerializeObject(res); ... private static IDictionary<string, object> GetExpandoObject(IEnumerable<string> unitsNames, IEnumerable<JToken> allUnits, string concept) { var eo = new ExpandoObject() as IDictionary<string, Object>; eo.Add("unit", concept); foreach (var u in unitsNames) { var sum = allUnits.Where(un => un["Name"].ToString() == u).Sum(_ => (int)_[concept]); eo.Add(u, sum); } return eo; } This is the result: [ {"unit":"KGs","Item1":343,"Item2":1110}, {"unit":"Cartons","Item1":1262,"Item2":3032}, {"unit":"Containers","Item1":4,"Item2":36} ] I'm not saying this is not possible to do with a single Linq query, but I didn't see it that clear, perhaps someone smarter and/or with more available time might achieve it
unknown
d7532
train
What you want to do is check all the elements y position in the document and return the one that is just passed? function getRelatedNavigation() { var elements = $('.anchor'); var currentScroll = $(document).scrollTop(); elements.each(function(index,value) { if (currentScroll > $(value).position.y) return $(value); }); }); $('.desktopnav ul li a[href="#'+getRelatedNavigation().attr('id')+'"]').addClass('selected').siblings().removeClass('selected'); $('#mobileselect').children().removeAttr('selected'); $('#mobileselect').children('[value="'+getRelatedNavigation().attr('id')+'"]').attr('selected','selected'); I dont know what labeling you are using for your waypoints, or anchors. In the example above I would mark them as class='anchor' so // Navigation <ul class='desktopnav'> <li><a href="#something">something</a></li> <li><a href="#other">other</a></li> </ul> //// Ways down <div id='something' class='anchor'>some content</div> <div id='other' class='anchor'>other content</div>
unknown
d7533
train
Depending on the type of data I'm not sure that encryption is necessary providing you secure access to the system and the database itself. All of our production database servers are behind a firewall. Only systems that are on the administrative network are allowed access through the firewall and then only on specific, required ports. Database servers don't host web servers. Access to the database servers themselves is strictly limited to DBAs and platform support personnel. They use administrative logins, not their personal login ids. That way if their personal account is compromised the database servers aren't. For web servers only web admins and platform support have access (I happen to wear two hats, web developer and web admin, although that is rare in our organization). Developers have access to shares where they can publish their application, usually coordinated with the web admin for any setup/configuration. Some senior developers are given administrator access to databases in order to create/modify schemas. Usually, what happens is you develop using a locally installed database server, upload code to QA servers that have a little looser access policy, but are only accessible from company networks, then have the DBAs copy the database schema and roles to production and publish your app to the production web server. Web apps are often configured to run under limited credential service accounts which have read/write, but not admin, access to the database. I typically encrypt any part of my web.config that contains connection information as well. The general idea is to give enough access to get your job done without too much bother, but limit access to the minimum required. Oh. And no "real" data on development or QA servers. [EDIT] We don't keep SSNs or credit card numbers. If you do, you'll need to be even more careful. Most of my apps do access logging, some are required to due to HIPPA, but I find that it is a good practice for just about anything meaningful A: Well the developers should probably do all their work on a development database that doesn't contain sensitive information to start with. A: Here in the UK we have legislation known as the Data Protection Act. If you worked for a UK company I would advise you to speak to your company's 'data controller' (being the individual whom the Information Commissioner's Office can pursue legally in instances of non-compliance) and they will be able to furnish you with a definitive answer about what 'secure' means as regards the data in question, probably enshrined in a written company policy. If you are in the US I'd guess your corporation might have a bunch of highly paid lawyers who will be able to similarly give a definitive answer :) I'm no legal expert but would suggest that obfuscating data does not make it fit for any purposes other than that for which it was obtained e.g. integration testing by developers using obfuscated 'real life' data is probably a no-no. A: You need to pratice standard security for a windows server. A good place to start is to use integrated logins rather that SQL logins. You will need to study the books on-line. You can give some users read-only access. Others can be denied access to sensitive tables. A: I would use Active Directory to control access to SQL Server or any network resource. By grouping the users and applying security to the group, it will make it so much easier to make changes in the future. Here is a guide from Microsoft on SQL Server 2005 Security Best Practices: http://download.microsoft.com/download/8/5/e/85eea4fa-b3bb-4426-97d0-7f7151b2011c/SQL2005SecBestPract.doc *Note: it downloads a Word document, so you will need MS Word or the MS Word viewer This document has a lot of detail so you may want to grab some coffee first :). However, I agree with the others, active development shouldn't happen against production data. We currently use a process of cleaning production data before it gets to the QA or Dev environments. Another option we explored is developing a solution to generate data for Dev and QA.
unknown
d7534
train
The usual solution with semaphores is to allow multiple simultaneous readers or one writer. See the Wikipedia article Readers-writers problem for examples. A: Semaphores are an higher abstraction. Semaphores controls the ability to create processes and make sure the instance created is distinct in which case it is kicked out. In a nutshell.
unknown
d7535
train
Here is the approach to make your layouts fit to retina & non retina form factors. I am not saying these are the rules, but I follow this approach & hardly get any conflicts which is difficult to resolve. * *First & foremost : Always try to design your storyboard on non-retina form factor (I mean in your case design it on iPhone4 size & then apply retina-Form Factor & verify how it fits on iPhone5 size.). *Definitely your view at the bottom of its parent will be having a fix constraint for "Y" position. Usually, you need to make a relative constraint. So when you show it up on iPhone4, the Y & the height might be going beyond the maximum Y axis value. *Try checking these values for your layout in Assistant Editor like topSpace, leadingSpace, trailingSpace, bottomSpace . *AutoLayout doesn't mean that it will fit to your needs, however it adjusts the component accordingly. *In case of any warning in Storyboard, try using the help & suggestion provided like, add missing constraint or adjust frame to suggested Storyboard will never behave in the same manner for each & every screen or view your design. You need to practise it more & more & you get to know how to add constraints. Hope that helps.
unknown
d7536
train
The Mercurial over subversion case is pretty convincingly made in the first section at http://hginit.com/ Git and Mercurial can each read and write one another's repos over the wire now, so it really comes down to whichever interface you prefer. A: One thing's for sure, don't start with CVS. A: I've been using Mercurial and enjoy it very much. You can get a free Bitbucket account and start storing your repos in the cloud. It's also being used on some codeplex projects if you ever have the desire/opportunity to work on an OSS project that's on codeplex. The basic gist I have found/heard is Mercurial is a little easier to work with but not as powerful as Git. However, both are excellent choices. There's a really good free video on tekpub for Mercurial and Codeplex. It takes you through all the basics. As already mentioned the http://hginit.com link is another good resource. It's also made by the same team who made FogBugz & Kiln. Kiln is an integrated environment for Mercurial and FogBugz with extras like code review. I was using SVN on my local box to store my personal work but no more. With Bitbucket & Mercurial I won't have to worry about my local box dying and making sure I had everything backed up.... Bottom line is you can't go wrong with either Hg or Git but I would go with Hg unless you needed some of the advanced features which sounds like you don't. Learning SVN isn't necessarily bad as there are a lot of Organizations using it but I would really concentrate on Distributed VCS instead. They really are the future. :-) A: Given the choice between Git and Hg, I'd probably go with Git - any disagreement? Warning, I'm a mercurial fanboy. Git is not bad, but it has some quirks you have to know when you use it: * *You can push into a non-bare git repo, but this will screw up the working copy there (It moves the branch HEAD to the pushed revision, but does not update the working copy. When you are not aware of this push, the next commit will undo the changes which were pushed into the repo, mixed with the changes you just introduced.). In hg a push to a non-bare repo just add the new history to the repo, and you get a new head on your next commit, which you then can merge with the pushed head. *You can't easily switch between a bare and a non-bare repo (you can make a hg repo bare with hg up -r null, and get a working copy with hg up [some-revision] from a bare one). *When you check out an older revision by a tag, remote branch name or commit-hash you get a detached head (I really like the title of that question). This means commits there are on no branch, and can get removed by the garbage collector. In hg a commit on an old state create a permanently stored anonymous head (You get a warning on the commit). *When you come from SVN you have to know that git revert and svn revert do completely different things. *Git has all features enabled, also the ones which can cause data loss (rebase, reset). In hg these features are there, but must be enabled prior use. *git tag makes local tags by default, when you want a globally visible tag you need git tag -a or git tag -s. On the opposite hg tag creates a global visible tag, local tags are created with hg tag -l. Some things many don't like about mercurial: * *Branches are stored permanent in the project history, for git-like local branches bookmarks can be used *There are no git-like remote tracking branches (although bookmarks can be shared, and recently there's been work on them to work more like git's branch labels) *Creating a tag creates a new commit in the project history (technically git does it the same way, but is much better at hiding this commit) *You have to enable features that modify history, or are experimental (hg comes pre-packed with many, ... but they are disabled by default). This is why many think that mercurial has less features than git. *There is no git rebase -i equivalent packaged with mercurial, you have to get the third-party histedit extension yourself. Second, why not Subversion? It seems to be the consensus (not just here) that it's old or otherwise obsolete. Why's that? Svn has no clue what a branch or a tag is, it only know copies. Branches and tags are simulated by having the convention that a svn repo contains a trunk/, branches/ and tags/ folder, but for svn they are only folders. Merging was a pain in svn, because older versions (prior svn 1.5) dit not track the merge history. Since svn1.5 subversion can track merge history, but I don't know if the merging part is better now. Another thing is that in svn every file and folder has it's own version number. In git and hg there is one version for the entire directory structure. This means that in svn you can check out an old revision an one file, and svn will say that there are no local changes in your working copy. When you check out an old revision of one file in git or hg, both tools will say your working copy is dirty, because the tree is not equal to their stored tree. With subversion you can get a Frankenstein version of your sources, without even knowing it. A minor nastiness in svn is that it places a .svn folder in every checked out folder (I heard rumors that they want to change this behavior in 1.7), where the clean reference files for the checked out ones live. This makes tools like grep -r foo not only list the real source files, but also files from these .svn folders. Svn has an advantage when you have big or unrelated projects, since you can check out only subtrees of a repository, while in git and hg you can get only the whole tree at once. Also does svn support locking, which is an interesting feature if you have files which can't easily be merged. Keyword substitution is also supported by svn, but I wouldn't call this a feature. A: I'd pick mercurial. * *The set of commands are limited so there's not a lot to remember. *http://www.hginit.com *Mercurial's hg serve command lets you setup a repo server for small operations in 5 seconds. *Cross platform *You can use it locally, without branches and be quite successful until you want to get deeper into the advanced stuff. A: Being a newbie myself , I've used git and found it remarkably easy to use and intuitive, while the others have been a bit too overwhelming.Coupled with GitHub it makes for a wonderful little tool for source control,sharing and backing up code. A: The best open-source choice is GIT. Check Git documentation. you Would also find lots of tutos over internet (youtube, and some developers blogs). A must not do is (start using CVS or Subsversion). Well at least is my personal opinion. A: Use git and github Once upon a time, cvs almost completely replaced its competition and ruled the world of version control. Then it was itself replaced by svn. And now, svn is being replaced by git. Git is more complex than svn, so there might still be reasons to pick svn for a new project. But its days are numbered. Git, Mercurial, and some proprietary systems are clearly the future of the VCS world. Both git and svn can be used in a cvs-like checkout/pull/commit mode, so the bottomless pit of complexity (it's a lifestyle) that is git won't affect you unless you jump in the deep end.
unknown
d7537
train
First of all, think if displaying a controller view inside a cell is a good idea. I'm not sure, but since i'm not familiar with your project, it's something only you can tell. Secondly, You can create your own pool of controllers. When you need a controller to put inside the cell (in cellforIndexPath method), take one from the pool. If the pool is empty, create a new one. The cell shouldn't come with a controller of it's own, put it only in cellForItemMethod.
unknown
d7538
train
Have you tried {% if distro == 'centos' or distro == 'redhat' %}
unknown
d7539
train
To not let the pipe process the output of the start command, you need to escape it: start "" cmd /C "C:\Program Files (x86)\Streamlink\bin\streamlink.exe" -O "%URL%/%%x" best ^| ffmpeg -y -i pipe:0 -c:v copy -c:a copy -absf aac_adtstoasc "%NAME%p%%x.mp4" Since quotation is not modified this way, the used path and all variable parts still appear quoted to the calling cmd instance too, so no more additional escaping is required, unless these strings may contain quotation marks on their own, in which case I strongly recommend delayed expansion: setlocal EnableDelayedExpansion rem // some other code... set /P URL="Enter video URL: " set /P NAME="Enter video name: " rem // some other code... start "" cmd /C "C:\Program Files (x86)\Streamlink\bin\streamlink.exe" -O "!URL!/%%x" best ^| ffmpeg -y -i pipe:0 -c:v copy -c:a copy -absf aac_adtstoasc "!NAME!p%%x.mp4" rem // some other code... endlocal The "" behind the start command should be stated to provide a window title; otherwise an error could occur as the first quoted item was taken as the title rather than as part of the command line. The above line still could cause problems, since the cmd instance executing the actual commands receives the already expanded values rather than the variable. So you might even need to do this: rem // Supposing delayed expansion is disabled in the hosting `cmd` instance: start "" cmd /C /V "C:\Program Files (x86)\Streamlink\bin\streamlink.exe" -O "!URL!/%%x" best ^| ffmpeg -y -i pipe:0 -c:v copy -c:a copy -absf aac_adtstoasc "!NAME!p%%x.mp4" setlocal EnableDelayedExpansion rem // Supposing delayed expansion is enabled in the hosting `cmd` instance: start "" cmd /C /V "C:\Program Files (x86)\Streamlink\bin\streamlink.exe" -O "^!URL^!/%%x" best ^| ffmpeg -y -i pipe:0 -c:v copy -c:a copy -absf aac_adtstoasc "^!NAME^!p%%x.mp4" endlocal Note that the pipe | creates two more cmd instances one for either side, implicitly.
unknown
d7540
train
As long as you have ajaxCall_item returning the jQuery deferred object, you can have save_part1 return a deferred object, collect the returned promises into an array, call them with $.when and resolve the "promise" once all of the requests have completed. Then you will be able to write: save_part1().then(save_part2);. Here is an untested example: function save() { save_part1().then(save_part2).fail(function(err) { // ohno }); } function ajaxCall_item1(row) { return $.ajax({ ... }); } function save_part1() { var dfd = jQuery.Deferred(); var promises = []; db.transaction(function (tx) { tx.executeSql("SELECT * FROM TABLE1", [], function (transaction, results) { for (var i = 0; i < results.rows.length; i++) { var row = results.rows.item(i); promises.push(ajaxCall_item1(row)); } $.when.apply($, promises).then(function() { dfd.resolve.apply(dfd, arguments); }); }, function(err) { dfd.reject(err); }); }); return dfd; }
unknown
d7541
train
For getting rid of the IndexOutOfBoundsException try caching the result of (int)(sf*o.width) and (int)(sf*o.height). Additionally you might want to make sure that x and y don't leave the bounds, e.g. by using Math.min(...) and Math.max(...). Finally, it should be int y = round((i / sf) * o.width; since you want to get the pixel in the original scale and then muliply with the original width. Example: Assume a 100x100 image and a scaling factor of 1.2. The scaled height would be 120 and thus the highest value for i would be 119. Now, round((119 * 100) / 1.2) yields round(9916.66) = 9917. On the other hand round(119 / 1.2) * 100 yields round(99.16) * 100 = 9900 - you have a 17 pixel difference here. Btw, the variable name y might be misleading here, since its not the y coordinate but the index of the pixel at the coordinates (0,y), i.e. the first pixel at height y. Thus your code might look like this: int scaledWidth = (int)(sf*o.width); int scaledHeight = (int)(sf*o.height); PImage out = createImage(scaledWidth, scaledHeight, RGB); o.loadPixels(); out.loadPixels(); for (int i = 0; i < scaledHeight; i++) { for (int j = 0; j < scaledWidth; j++) { int y = Math.min( round(i / sf), o.height ) * o.width; int x = Math.min( round(j / sf), o.width ); out.pixels[(int)((scaledWidth * i) + j)] = o.pixels[(y + x)]; } }
unknown
d7542
train
Instead of using a List maybe try using an IEnumerable w/ yield? static IEnumerable<ListKeywords> Keywords() { using (StreamReader sr = File.OpenText(path)) { string s = String.Empty; while ((s = sr.ReadLine()) != null) { yield return new ListKeywords(s); } } } Note that Jon Skeet's C# in Depth offers a great explanation about this in Chapter 6. I imagine he also has some articles or posts on StackOverflow about this topic. As he points out, you want to be careful about modifying this method to pass in a StreamReader (or TextReader as is used in his example) as you would want to take ownership of the reader so it will be properly disposed of. Rather, you would want to pass in a Func<StreamReader> if you have such a need. Another interesting note he adds here - which I will point out because there are some edge cases where the reader will not actually be properly disposed of even if you don't allow the reader to be provided by the caller - it's possible for the caller to abuse the IEnumerable<ListKeywords> by doing something like Keywords().GetEnumerator() - this could result in a memory leak and could even potentially cause security issues if you have security-related code which relies on the using statement to clean up the resource.
unknown
d7543
train
$sql=" SELECT * FROM ART where 1=1 "; if(!empty($category) { $sql.=" and category= $value"; } if(!empty($subject) { $sql.=" and subject= $value"; } if(!empty($medium) { $sql.=" and medium= $value"; } where 1=1 is just to keep the syntax correct else you need to have some login to add where accordingly as you can't add where in all three checks (will make incorrect sql string). Read about sql injection. Use parameter binding to add parameter, this is just for you to get an idea, this will work but is vulnerable to sql injection A: Try all the filters in the where condition with OR not AND as shown below SELECT * FROM ART WHERE category=val OR subject=val OR medium=val;
unknown
d7544
train
If this is a homework writing the complete script will be a disservice. Some hints: the function you should be using is gsub in awk. The fifth field is $5 and you can set the field separator by -F'|' or in BEGIN block as FS="|" Also, line numbers are in NR variable, to skip first line for example, you can add a condition NR>1 A: An awk one liner: awk 'BEGIN { FS="|" } { gsub("-","",$5); print }' infile.txt A: To keep "|" as output separator, it is better to define OFS value as "|" : ... | awk 'BEGIN { FS="|"; OFS="|"} {gsub("-","",$5); print $0 }'
unknown
d7545
train
Actually, I see a lot of current containers being set: max-width in css. You can take a look at some classes: inner-wrap, elementor-widget-container, ... then set: - max-width: 100% !important; - Remove padding or margin if it needs A: .inner-wrap { max-width: 100% !important; float: left; width: 100%; } .inner-wrap .elementor-container { max-width: 94% !important; } header .inner-wrap { padding: 0 30px; } Try With this one
unknown
d7546
train
This is just my point of observation: Based on the documentation, after you call capture, irrespective of destination location ( I mean CaptureToFile or CaptureToBuffer) the image is saved to a file. note this statemet in below link: If an empty file is passed, the camera backend choses the default location and naming scheme for photos on the system. http://doc.qt.io/qt-5/qcameraimagecapture.html#capture The additional advantage with "CaptureToBuffer", your image is saved in some specified buffer format. My wild guess, if at all they are not supporting ( as i am unable to find any offical information on it) only capture to buffer, the reason could be, the user is allowed to set the bufferformat using setBufferFormat. And the device may not support the buffer format (isCaptureDestinationSupported() is there to check it.). May be because of this they are saving to local pictures folder always. If this saving is unavoidable by capture, and if your business strictly needs not to maintain those saved files, when your buffer is doing good, probably you can delete them in below slot. QObject::connect(YOURCAMERACAPTUREOBJECT, SIGNAL(imageSaved), this,SLOT(saved(int id, const QString &fileName))); void saved(int id, const QString &fileName) { //Delete the file by checking you have content in buffer. //to check the buffer probably you can use "imageAvailable" signal } A: I believe that bug you are describing were in GStreamer camerabin plugin. When you look to https://code.qt.io/cgit/qt/qtmultimedia.git/tree/src/plugins/gstreamer/camerabin/camerabinsession.cpp?h=5.15#n587 m_imageFileName is setup independently on capture destination. File is saved by this filter then https://code.qt.io/cgit/qt/qtmultimedia.git/tree/src/plugins/gstreamer/mediacapture/qgstreamercapturesession.cpp?h=5.15#n404 edit: This bug seems to be fixed somehow in Qt 5.15.
unknown
d7547
train
B C B: C E C: G D: A Output File: A: B C E G B: C E G C: G D: A B C E G So far this is what I've got (separating the first and second token): import java.util.StringTokenizer; import java.io.*; public class TestDependency { public static void main(String[] args) { try{ FileInputStream fstream = new FileInputStream("input-file"); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); String strLine; while ((strLine = br.readLine()) != null) { StringTokenizer items = new StringTokenizer(strLine, ":"); System.out.println("I: " + items.nextToken().trim()); StringTokenizer depn = new StringTokenizer(items.nextToken().trim(), " "); while(depn.hasMoreTokens()) { System.out.println( "D: " + depn.nextToken().trim() ); } } } catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } } Any help appreciated. I can imagine Perl or Python to handle this easily. Just need to implement it in Java. A: This is not very efficient memory-wise and requires good input but should run fine. public class NodeParser { // Map holding references to nodes private Map<String, List<String>> nodeReferenceMap; /** * Parse file and create key/node array pairs * @param inputFile * @return * @throws IOException */ public Map<String, List<String>> parseNodes(String inputFile) throws IOException { // Reset list if reusing same object nodeReferenceMap = new HashMap<String, List<String>>(); // Read file FileInputStream fstream = new FileInputStream(inputFile); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); String strLine; // Parse nodes into reference mapping while((strLine = br.readLine()) != null) { // Split key from nodes String[] tokens = strLine.split(":"); String key = tokens[0].trim(); String[] nodes = tokens[1].trim().split(" "); // Set nodes as an array list for key nodeReferenceMap.put(key, Arrays.asList(nodes)); } // Recursively build node mapping Map<String, Set<String>> parsedNodeMap = new HashMap<String, Set<String>>(); for(Map.Entry<String, List<String>> entry : nodeReferenceMap.entrySet()) { String key = entry.getKey(); List<String> nodes = entry.getValue(); // Create initial node set Set<String> outSet = new HashSet<String>(); parsedNodeMap.put(key, outSet); // Start recursive call addNode(outSet, nodes); } // Sort keys List<String> sortedKeys = new ArrayList<String>(parsedNodeMap.keySet()); Collections.sort(sortedKeys); // Sort nodes Map<String, List<String>> sortedParsedNodeMap = new LinkedHashMap<String, List<String>>(); for(String key : sortedKeys) { List<String> sortedNodes = new ArrayList<String>(parsedNodeMap.get(key)); Collections.sort(sortedNodes); sortedParsedNodeMap.put(key, sortedNodes); } // Return sorted key/node mapping return sortedParsedNodeMap; } /** * Recursively add nodes by referencing the previously generated list mapping * @param outSet * @param nodes */ private void addNode(Set<String> outSet, List<String> nodes) { // Add each node to the set mapping for(String node : nodes) { outSet.add(node); // Get referenced nodes List<String> nodeList = nodeReferenceMap.get(node); if(nodeList != null) { // Create array list from abstract list for remove support List<String> referencedNodes = new ArrayList<String>(nodeList); // Remove already searched nodes to prevent infinite recursion referencedNodes.removeAll(outSet); // Recursively search more node paths if(!referencedNodes.isEmpty()) { addNode(outSet, referencedNodes); } } } } } Then, you can call this from your program like so: public static void main(String[] args) { try { NodeParser nodeParser = new NodeParser(); Map<String, List<String>> nodeSet = nodeParser.parseNodes("./res/input.txt"); for(Map.Entry<String, List<String>> entry : nodeSet.entrySet()) { String key = entry.getKey(); List<String> nodes = entry.getValue(); System.out.println(key + ": " + nodes); } } catch (IOException e){ System.err.println("Error: " + e.getMessage()); } } Also, the output is not sorted but that should be trivial. A: String s = "A: B C D"; String i = s.split(":")[0]; String dep[] = s.split(":")[1].trim().split(" "); System.out.println("i = "+i+", dep = "+Arrays.toString(dep));
unknown
d7548
train
.row selects all the elements which have the class row which means that you're not appending the .square divs to only the last created row, you're appending them to all the previously created ones as well. To prevent that, you can do something like this. for (var i = 0; i < 16; i++) { var row = $("<div class = 'row'></div>"); for (var j = 0; j < 16; j++) { var square = $("<div class='square'></div>"); row.append(square); } $('.grid').append(row); } OR for (var i = 0; i < 16; i++) { $('.grid').append("<div class='row' id='row"+i+"'></div>"); for (var j = 0; j < 16; j++) { $('#row'+i).append("<div class='square'></div>"); } } A: Moving your inner for loop outside of the outer for loop should create the proper amount of squares, as such: for (var i = 0; i < 16; i++) { $('.grid').append("<div class = 'row'></div>"); // Each grid gets 16 rows } for (var i = 0; i < 16; i++) { $('.row').append("<div class='square'></div>"); // Each row gets 16 squares } Explicitly setting the width of the row is not necessary, as it will automatically be 16 times the width of your square plus any padding/margin you add. Note that all your squares would need display: inline-block; in the CSS to ensure that they are side by side. Also, the rows would wrap if there are too many squares in each row or the squares are too wide.
unknown
d7549
train
it looks like this issue was wrongly closed. I reopened it. http://hub.darcs.net/simon/darcsden/issue/48
unknown
d7550
train
You basically want the inputs to be fed to the network using queue runners during training, but then during inference you want to input it through feed_dict. This can be done by using tf.placeholder_with_default(). So when the inputs are not fed through feed_dict, it will read from the queues, otherwise it takes from 'feed_dict'. Your code should be like: col1_batch, col2_batch = tf.train.shuffle_batch([col1, col2], ... # if data is not feed through `feed_dict` it will pull from `col*_batch` _X = tf.placeholder_with_default(col1_batch, shape=[None], name='X') _y = tf.placeholder_with_default(col2_batch, shape=[None], name='y')
unknown
d7551
train
The error is occurring as a result of your code trying to create a database. The error is indicating that the edition/performance level being created is not supported by your subscription offer type - a DreamSpark subscription is limited to creating free resources. See https://azure.microsoft.com/en-us/offers/ms-azr-0144p/. Creating a database without specifying an edition will create a Standard S0 database by default, which is not free. If you create a free website or mobile service and elect to create a free Azure SQL Database as part of the template that should work for your subscription's offer type. You could then access this database from any application although it will have limited storage and performance. A: You can put the default constructor to the DTO class. Ex: public class User { public User() { } } or you can try to put the following lines at the top of your Application_Start method in the Global.asax file: GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
unknown
d7552
train
You can do this by downloading the TRX file from TFS and parsing it manually. To download the TRX file for a test run, do this: TfsTeamProjectCollection tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://my-tfs:8080/tfs/DefaultCollection")); ITestManagementService tms = tpc.GetService<ITestManagementService>(); ITestManagementTeamProject tmtp = tms.GetTeamProject("My Project"); ITestRunHelper testRunHelper = tmtp.TestRuns; IEnumerable<ITestRun> testRuns = testRunHelper.ByBuild(new Uri("vstfs:///Build/Build/123456")); var failedRuns = testRuns.Where(run => run.QueryResultsByOutcome(TestOutcome.Failed).Any()).ToList(); failedRuns.First().Attachments[0].DownloadToFile(@"D:\temp\myfile.trx"); Then parse the TRX file (which is XML), looking for the <TestMethod> element, which contains the fully-qualified class name in the "className" attribute: <TestMethod codeBase="C:/Builds/My.Test.AssemblyName.DLL" adapterTypeName="Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.Adapter, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" className="My.Test.ClassName, My.Test.AssemblyName, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" name="Test_Method" /> A: Here you have a way to get the Assembly name: foreach (ITestCaseResult testCaseResult in failures) { string testName = testCaseResult.TestCaseTitle; ITmiTestImplementation testImplementation = testCaseResult.Implementation as ITmiTestImplementation; string assembly = testImplementation.Storage; } Unfortunately, ITestCaseResult and ITmiTestImplementation don’t seem to contain the namespace of the test case. Check the last response in this link, that might help. Good Luck! EDIT: This is based on Charles Crain's answer, but getting the class name without having to download to file: var className = GetTestClassName(testResult.Attachments); And the method itself: private static string GetTestClassName(IAttachmentCollection attachmentCol) { if (attachmentCol == null || attachmentCol.Count == 0) { return string.Empty; } var attachment = attachmentCol.First(att => att.AttachmentType == "TmiTestResultDetail"); var content = new byte[attachment.Length]; attachment.DownloadToArray(content, 0); var strContent = Encoding.UTF8.GetString(content); var reader = XmlReader.Create(new StringReader(RemoveTroublesomeCharacters(strContent))); var root = XElement.Load(reader); var nameTable = reader.NameTable; if (nameTable != null) { var namespaceManager = new XmlNamespaceManager(nameTable); namespaceManager.AddNamespace("ns", "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"); var classNameAtt = root.XPathSelectElement("./ns:TestDefinitions/ns:UnitTest[1]/ns:TestMethod[1]", namespaceManager).Attribute("className"); if (classNameAtt != null) return classNameAtt.Value.Split(',')[1].Trim(); } return string.Empty; } internal static string RemoveTroublesomeCharacters(string inString) { if (inString == null) return null; var newString = new StringBuilder(); foreach (var ch in inString) { // remove any characters outside the valid UTF-8 range as well as all control characters // except tabs and new lines if ((ch < 0x00FD && ch > 0x001F) || ch == '\t' || ch == '\n' || ch == '\r') { newString.Append(ch); } } return newString.ToString(); } A: Since the details of the testcase are stored in the work item you can fetch the data by accessing the work item for the test case ITestCaseResult result; var testCase = result.GetTestCase(); testCase.WorkItem["Automated Test Name"]; // fqdn of method testCase.WorkItem["Automated Test Storage"]; // dll A: public string GetFullyQualifiedName() { var collection = new TfsTeamProjectCollection("http://tfstest:8080/tfs/DefaultCollection"); var service = collection.GetService<ITestManagementService>(); var tmProject = service.GetTeamProject(project.TeamProjectName); var testRuns = tmProject.TestRuns.Query("select * From TestRun").OrderByDescending(x => x.DateCompleted); var run = testRuns.First(); var client = collection.GetClient<TestResultsHttpClient>(); var Tests = client.GetTestResultsAsync(run.ProjectName, run.Id).Result; var FullyQualifiedName = Tests.First().AutomatedTestName; return FullyQualifiedName; }
unknown
d7553
train
Assuming the matrix passed in is 8x8 (since we want [1,2,...,64] as the elements): for (int i = 0; i < 64; i++){ matrix[i%8,i/8] = i+1; } or for (int i = 0; i < 64; i++){ matrix[i/8,i%8] = i+1; } Depending on the desired orientation of the matrix
unknown
d7554
train
Have you debugged it to check if 'v' is null? If so, you need to use a layoutInflator to retrieve the view. if(v == null) { LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.service_list, null); }
unknown
d7555
train
After looking at the $con dump, it appears that the last query you're executing on this connection is not using its result. mysqli uses unbuffered queries by default, so you need to either fetch the result of the previous query executed into a buffer manually, or free the memory that it's using to make room for your new query, with either store_result() or free_result(), respectively.
unknown
d7556
train
There are 2 similar functions within Presenter.cpp that process frames but I cannot figure out what the difference is between them. ProcessFrameUsingD3D11()uses VideoProcessorBlt() to actually do the render. The functions are not rendering - they are two ways to scale video frames. Scaling might be done with a readily available Media Foundation transform internally managed by the renderer's presenter, or scaling might be done with the help of Direct3D 11 processor. Actually both utilize Direct3D 11, so the two methods are close one to another and are just one step in the rendering process. I cannot find anything that does decoding unless by some MF magic chant phrase that I haven't stumbled across yet. There is no decoding and the list of sink video formats in StreamSink.cpp suggests that by only listing uncompressed video formats. The renderer presents frames carried by Direct3D 11 textures, which in turn assumes that a decode, esp. hardware decoder such as DXVA2 based already supplies the decoded textures on the renderer input.
unknown
d7557
train
This Node.js/Lambda tutorial might help get you going: https://dev.to/adnanrahic/getting-started-with-aws-lambda-and-nodejs-1kcf
unknown
d7558
train
The chained assignment warnings / exceptions are aiming to inform the user of a possibly invalid assignment. There may be false positives; situations where a chained assignment is inadvertantly reported. The purpose of this warning is to flag to the user that the assignment is carried out on a copy of the DataFrame slice instead of the original Dataframe itself. You generally want to use .loc (or .iloc, .at, etc.) type indexing instead of 'chained' indexing which has the potential to not always work as expected. To make it clear you only want to assign a copy of the data (versus a view of the original slice) you can append .copy() to your request, e.g. df = data[columns].copy() See the documentation for more details.
unknown
d7559
train
If the SQL of a listbox is set to: SELECT Id, SomeOtherField FROM aTable Then the value of the list box is Id, not SomeOtherField. In this case you should say: If Me.[location] = 1 Then ''Where 1 is the Id you want. To check the value of a control, you can click on an item and use ctrl+G to get the immediate window, then type ?Screen.ActiveControl
unknown
d7560
train
The links you see on github.com are routes that are designed to be used on the website in web browsers. The domain githubusercontent.com is designed to be separate to prevent any malicious user content from trying to steal cookies for github.com. In general, if you're just using a web browser, click on the link or the button, and it will automatically redirect you to the right place. Otherwise, you should use the REST API to either get the raw file contents directly or fetch the download URL. Using the API will always give you the correct location and contents. If you just want to use curl with the API and don't want to fetch the download_url key manually, you can run this: curl -H'Accept: application/vnd.github.v3.raw' https://api.github.com/repos/hasura/graphql-engine/contents/cli/get.sh. Note also that none of these ways are designed for high-speed automated access; for that, you should host your repository on your own server with a CDN in front.
unknown
d7561
train
The above query will insert 5M documents into ArangoDB in a single transaction. This will take a while to complete, and while the transaction is still ongoing, it will hold lots of (potentially needed) rollback data in memory. Additionally, the above query will first build up all the documents to insert in memory, and once that's done, will start inserting them. Building all the documents will also consume a lot of memory. When executing this query, you will see the memory usage steadily increasing until at some point the disk writes will kick in when the actual inserts start. There are at least two ways for improving this: * *it might be beneficial to split the query into multiple, smaller transactions. Each transaction then won't be as big as the original one, and will not block that many system resources while ongoing. *for the query above, it technically isn't necessary to build up all documents to insert in memory first, and only after that insert them all. Instead, documents read from users could be inserted into canSee as they arrive. This won't speed up the query, but it will significantly lower memory consumption during query execution for result sets as big as above. It will also lead to the writes starting immediately, and thus write-ahead log collection starting earlier. Not all queries are eligible for this optimization, but some (including the above) are. I worked on a mechanism today that detects eligible queries and executes them this way. The change was pushed into the devel branch today, and will be available with ArangoDB 2.5.
unknown
d7562
train
i cant even see where the reCaptcha should get its style from? reCaptcha Docs A: I ended up using the AJAX API for the ReCaptcha, which works like a charm! More info about there here: http://code.google.com/intl/nl/apis/recaptcha/docs/display.html#AJAX
unknown
d7563
train
The problem is that there is no namespace of UnityEngine.Experimental.Input. But, it only says “'Input' does not exist in the namespace 'UnityEngine.Experimental'”. ‘Experimental’ does exist and ‘Input’ does not. However, ‘InputSystem’ does. And that is the one you are looking for, not ‘Input’. You should change the first line to this: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.InputSystem; public class Player01 : MonoBehaviour ... A: Just in case, if the first solution did not work, Close vs studio / code if open, then go to Edit -> Project Settings -> Input System Manager. There will be only one option available. Click the button, save your scene. Open a script. This worked for me. A lot of tutorials do not mention this part.
unknown
d7564
train
Do this: $rosh=mysql_query("select distinct term from search_terms") or die("Error with query: " . mysql_error()); and this: $bash=mysql_query($bashq) or die("Error with query: " . mysql_error(); That will tell you when it fails. You are correct though, you're getting that message because mysql_query has returned "false" and isn't a valid result resource. A: Because your querying within a loop, one of the terms isn't processed (probably because search_terms is missing rows for that specific turn. Which is odd, since you're querying the same table. However, since it's a Warning, and not a fatal Error, it will still continue. Either way, it's seems like wrong way to pulling your data, you can probably do taht with one query, adequate sorting (ORDER BY) directly in the SQL server, GROUP BY and SUM() for getting the sum of your terms. You should read up on your SQL instead :) SELECT term, SUM(term_number) as term_sum FROM search_terms GROUP BY terms ORDER BY term_sum DESC LIMIT 10 then just copy it to your hashtable and it should already be sorted, aswell as limited to 10 entries.
unknown
d7565
train
What's about extension like this? import android.annotation.SuppressLint import android.os.Build import android.view.View import android.view.ViewTreeObserver inline fun View.doOnGlobalLayout(crossinline action: (view: View) -> Unit) { val vto = viewTreeObserver vto.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { @SuppressLint("ObsoleteSdkInt") @Suppress("DEPRECATION") override fun onGlobalLayout() { action(this@doOnGlobalLayout) when { vto.isAlive -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { vto.removeOnGlobalLayoutListener(this) } else { vto.removeGlobalOnLayoutListener(this) } } else -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { viewTreeObserver.removeOnGlobalLayoutListener(this) } else { viewTreeObserver.removeGlobalOnLayoutListener(this) } } } } }) } Finally, you can call OnGlobalLayoutListener from View directly val view: View = ... view.doOnGlobalLayout { val width = view?.measuredWidth val height = view?.measuredHeight } A: Simple / clear approach (no generics or anonymous objects): You could create the listener in advance, then add / use / remove as needed: private var layoutChangedListener: ViewTreeObserver.OnGlobalLayoutListener? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // create the listener layoutChangedListener = ViewTreeObserver.OnGlobalLayoutListener { // do something here // remove the listener from your view myContainerView.viewTreeObserver.removeOnGlobalLayoutListener(layoutChangedListener) layoutChangedListener = null } // add the listener to your view myContainerView.viewTreeObserver.addOnGlobalLayoutListener(layoutChangedListener) } use case: I had to be able to remove the listener, in order to adjust the layout inside the listener itself - not removing the listener may result in a deadlock A: Referencing a lambda from inside it is not supported. As a workaround, you might use anonymous object instead of lambda SAM-converted to Java functional interface OnGlobalLayoutListener: containerLayout.viewTreeObserver.addOnGlobalLayoutListener(object: OnGlobalLayoutListener { override fun onGlobalLayout() { // your code here. `this` should work } }) A: Another solution is to implement and use self-reference: class SelfReference<T>(val initializer: SelfReference<T>.() -> T) { val self: T by lazy { inner ?: throw IllegalStateException() } private val inner = initializer() } fun <T> selfReference(initializer: SelfReference<T>.() -> T): T { return SelfReference(initializer).self } Then the usage would be containerLayout.viewTreeObserver.addOnGlobalLayoutListener(selfReference { OnGlobalLayoutListener { containerLayout.viewTreeObserver.removeOnGlobalLayoutListener(self) // ... } } Instead of this, self property is used.
unknown
d7566
train
Using str.split with list slicing Ex: import datetime for i in ("X-XXX_2020-11-05_13-54-55-555__XX.csv", "X-XXX_2020-11-05_13-54-55-555__XXX.csv"): print(datetime.datetime.strptime("_".join(i.split("_")[1:3]), "%Y-%m-%d_%H-%M-%S-%f")) OR using regex. Ex: import re import datetime for i in ("X-XXX_2020-11-05_13-54-55-555__XX.csv", "X-XXX_2020-11-05_13-54-55-555__XXX.csv"): d = re.search(r"(?<=_)(.+)(?=__)", i) if d: print(datetime.datetime.strptime(d.group(1), "%Y-%m-%d_%H-%M-%S-%f")) Output: 2020-11-05 13:54:55.555000 2020-11-05 13:54:55.555000
unknown
d7567
train
It is going to show you blank screen with the url Account/Register since you are returning void from your HttpPost action method. Ideally, you should be doing the PRG pattern. POST - REDIRECT-GET * *The form is displayed that asks the user for some input. *When the user submits the form, the code does some business logic/transaction (Save some thing to db etc). After successfully doing that, Send a 302 response to browser. *The 302 response tells the browser to issue a totally new GET request to the url provided by the server.In MVC, We can use RedirectToAction method to send the 302 response to the browser. So your code will be [HttpPost] public void Register(RegisterViewModel viewModel) { if (ModelState.IsValid) { // to do :Save return RedirectToAction("SuccesfullyRegistered","Account"); } return View(viewModel); } So when user submits the form, we will save the user and send a 302 response to the browser and browser will issue a request to Account/SuccessfullyRegistered action method. The PRG pattern prevents the duplicate form submission issue when user reloads the new view. A: Based upon your comment, you should use Ajax Helper or jquery to submit your form via ajax. Working with Ajax Helper in ASP.NET MVC is a good tutorial of using Ajax Helper and there are lots of questions in stackoverflow about using jquery to submit a form. It's up to you to employ one of them. It seems that Ajax Helper is more easier to use. A: If you really want to fire and forget the POST request of a form submit, then you can add an invisible iframe and let the target attribute of your form point to that iframe. Then the content of the reply to the POST will land there and the user won't see it since the iframe is hidden. Your iframe definition could look like this: <iframe id="nulframe" name="nulframe" style="width:0;height:0;border:0; border:none;" /> and you would add the target attribute to the first line of your code like this: @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { id="frmRegister", @class = "form-horizontal", role = "form", target = "nulframe" })) You could even handle the load event of the iframe to get signalled when the POST is completed.
unknown
d7568
train
The syntax is wron: $db = "SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON p.'supp_id2` = s.`supp_id` WHERE p.purch_id = $purch_id "; copy this select $db = "SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON p.`supp_id2` = s.`supp_id` WHERE p.purch_id = $purch_id "; A: As you can see at the error Error Number: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''supp_id2` = s.`supp_id` WHERE p.purch_id =' at line 1 SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON p.'supp_id2` = s.`supp_id` WHERE p.purch_id = Filename: C:/xampp/htdocs/codeigniter/system/database/DB_driver.php Line Number: 691 Purchase id is not passing to the query.
unknown
d7569
train
You can use \ character to escape special characters like below. See this DEMO if in doubt. INSERT INTO tablename VALUES('\!\^\'\"twco\\dq'); Per MySQL documentation, below are the defined escape sequences Table 9.1 Special Character Escape Sequences \0 An ASCII NUL (0x00) character. \' A single quote (“'”) character. \" A double quote (“"”) character. \b A backspace character. \n A newline (linefeed) character. \r A carriage return character. \t A tab character. \Z ASCII 26 (Control+Z). See note following the table. \\ A backslash (“\”) character. \% A “%” character. See note following the table. \_ A “_” character. See note following the table. A: No, there is no "scope" in MySQL to automatically escape all special characters. If you have a text file containing statements that were created with potentially unsafe "random values" like this: INSERT INTO tablename VALUES('!^'"twco\dq'); ^^^^^^^^^^^ You're basically screwed. MySQL can't unscramble a scrambled egg. There's no "mode" that makes MySQL work with a statement like that. Fortunately, that particular statement will throw an error. More tragic would be some nefariously random data, x'); DROP TABLE students; -- if that random string got incorporated into your SQL text without being escaped, the result would be: INSERT INTO tablename VALUES('x'); DROP TABLE students; --'); The escaping of special characters has to be done before the values are incorporated into SQL text. You'd need to take your random string value: !^'"twco\dq And run it through a function that performs the necessary escaping to make that value safe for including that as part of the the SQL statement. MySQL provides the real_escape_string_function as part of their C library. Reference https://dev.mysql.com/doc/refman/5.5/en/mysql-real-escape-string.html. This same functionality is exposed through the MySQL Connectors for several languages. An even better pattern that "escaping" is to use prepared statements with bind placeholders, so your statement would be a static literal, like this: INSERT INTO tablename VALUES ( ? )
unknown
d7570
train
You can use numpy.apply_along_axis to apply a function for certain axis in your data. def func(row): # return the computation result for "row" def obj(theta): """ Computes the objective function to be differentiated. Args: theta: np.array of shape (n, d) Return: res: np.array of shape (n,) """ theta = np.atleast_2d(theta) n = theta.shape[0] res = np.apply_along_axis(func1d=func, axis=1, arr=a) return res
unknown
d7571
train
A much easier way: Calculate the score before adding the record, save all needed data in variables instead of recordset fields. Then only if score > 0 do the rs1.AddNew etc.
unknown
d7572
train
First, you need to work with Worksheet_Calculate() event, as already mentioned by Sam. But there's something more: why are you using a 26-conditions if-clause? Create a next worksheet (Application_Sheet), with two columns, something like this: R_Value Application 1 Select_Facility 2 No_Facility ... ... Instead of the complicated if-clause, do something like this (not tested): Application.Run(Range(Application_Sheet!B1).Offset(r.Value).Value) A: I have implemented some of the changes recommended above, and while the code does seem neater, I cannot get this to work at all, here is my code for the worksheet_calculate() and the referenced macro. I keep getting a code execution interrupted error which then points back to the Worksheet_Calculate() name when I hit the debug option. Private Sub Worksheet_Calculate() 'Define the worksheets & Ranges for use in this routine Dim r As Range: Set r = Range("N19") 'Hiding facility Rows based on product line Application.Run (Range("AB1").Offset(r.Value).Value) End Sub and one of the macro's is Sub Select_Facility() Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Supplier Details") ws.Activate Rows("22:24").EntireRow.Hidden = True Rows("25:27").EntireRow.Hidden = True Rows("28:30").EntireRow.Hidden = True Rows("31:33").EntireRow.Hidden = True Rows("37").EntireRow.Hidden = True Rows("38").EntireRow.Hidden = True Rows("39").EntireRow.Hidden = True Rows("40").EntireRow.Hidden = True Rows("41").EntireRow.Hidden = True Rows("42").EntireRow.Hidden = True Rows("43:45").EntireRow.Hidden = True Rows("46:48").EntireRow.Hidden = True Rows("49").EntireRow.Hidden = True Rows("51:52").EntireRow.Hidden = True Rows("36").EntireRow.Hidden = True ws.Rows("50").EntireRow.Hidden = True End Sub Perhaps its something simple I am doing wrong, but.... Oh and all the rows in the above list are set to hidden as standard before I start.
unknown
d7573
train
Install the modified plugin * *Clone locally and pull the changes * *Clone PushPlugin locally git clone https://github.com/phonegap-build/PushPlugin.git *Add a remote to the repository where the modifications are git remote add bigpicture-repo https://github.com/ajoyoommen/PushPlugin.git *Then fetch the changes git fetch bigpicture-repo *Merge the changes you just fetched (from the remote) into you master git merge bigpicture-repo/master OR *Directly clone my repository containing the feature git clone https://github.com/ajoyoommen/PushPlugin Uninstall the old plugin cordova plugin remove com.phonegap.plugins.PushPlugin Install the new plugin from your filesystem cordova plugin add /home/myname/Documents/PushPlugin Send messages from your server to your application. If the payload has bigPicture in it, with a URL, that image will be downloaded and displayed in a Big Picture style notification.
unknown
d7574
train
My solution to this was to use the .Default style instead of .Cancel for the cancelAction. A: Since iOS9 there is a preferredAction property on UIAlertController. It places action on right side. From docs: When you specify a preferred action, the alert controller highlights the text of that action to give it emphasis. (If the alert also contains a cancel button, the preferred action receives the highlighting instead of the cancel button.) The action object you assign to this property must have already been added to the alert controller’s list of actions. Assigning an object to this property before adding it with the addAction: method is a programmer error.
unknown
d7575
train
Your code works well, but you can improve some things please check the following example thar will return a nested array with the links your looking: <?php $sUrl1="http://www.phanmemtoday.com/sitemap.xml?page=1"; $sUrl2="http://www.phanmemtoday.com/sitemap.xml"; $aXmlLinks = array($sUrl1,$sUrl2); $aOtherLinks = array(); while (!empty($aXmlLinks)) { foreach ($aXmlLinks as $i =>$sTmpUrl){ unset($aXmlLinks[$i]); $aTmp = getlinkfromxmlsitemap($sTmpUrl); array_push($aOtherLinks,$aTmp); } echo "<br>Array xml link:<br>"; print_r($aXmlLinks); echo "<br>Array product link:<br>"; print_r($aOtherLinks); echo "<br>-----------------------------------------<br>"; } print_r($aOtherLinks); function getlinkfromxmlsitemap($sUrl) { // echo "Get link from: $sUrl<br>"; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch,CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0"); curl_setopt($ch, CURLOPT_URL, $sUrl); $data = curl_exec($ch); $error= curl_error($ch); curl_close($ch); $links = array(); $count = preg_match_all('@<loc>(.+?)<\/loc>@', $data, $matches); for ($i = 0; $i < $count; ++$i) { $links[] = $matches[0][$i]; } return $links; } ?>
unknown
d7576
train
Typically you would perform the copy from a batch file itself. For example, your batch file would do the copy, run a MaxL script, and then do other things. That said, you can run shell commands from within MaxL if you need to (I don't usually recommend it though). In this case, you need to pass the whole statement to the shell command. Your statement should work if you write it like this instead: shell "copy 'E:\RPTG\Export.txt' 'E:\FCST\'"; Note that I have enclosed your command in double quotes. There are some nuances to using double quotes and single quotes at the same time, but in this case you should be okay.
unknown
d7577
train
You can not use "gpu" mode and Stage3D. You need to specify "direct". Hope this works. Confusing, I know :) If not, try making a regular flash player project first, and run with all debug flags on. AIR is usually more complicated with all the SDKs and stuff. A: Got it! The solution turned out to be building from the command line, rather than using Flash Builder (4, can't speak for 4.5/6). Here is the sequence of commands: I. axmlc compile the application (Main.as) file, with all the correct options: $FLEX_4.6_SDK/bin/amxmlc -static-link-runtime-shared-libraries=true -library-path+='$ALTERNATIVA/Alternativa3D.swc' -debug=true -swf-version=13 -load-config $FLEX_4.6_SDK/frameworks/air-config.xml -- Main.as (where $FLEX_4.6_SDK and $ALTERNATIVA are the locations of the Flex SDK and Alternativa3D SWC, naturally) II. adl run the application $FLEX_4.6_SDK/bin/adl Main-app.xml which for convenience I setup in my .bash_profile like so: alias run_virtual_library="cd '/Users/joverton/Documents/Prototyping and Testing/Virtual Library/src/' && /Applications/Adobe\ Flash\ Builder\ 4/sdks/4.6/bin/amxmlc -static-link-runtime-shared-libraries=true -library-path+='/Users/joverton/Documents/Libraries & Tools/Alternativa3D/Alternativa3D_8.17.0/Alternativa3D.swc' -debug=true -swf-version=13 -load-config /Applications/Adobe\ Flash\ Builder\ 4/sdks/4.6/frameworks/air-config.xml -- Main.as && '/Applications/Adobe Flash Builder 4/sdks/4.6/bin/adl' Main-app.xml &" Note that in my AIR application descriptor file I set the renderMode to "gpu", but "direct" will also work. Also, in the amxmlc command you needn't set the debug compiler option to true; I only do for the sake of testing. EDIT: Additional note is that - because I was building from the command line rather than from Flash Builder - I had to explicitly set the value of in my AIR Descriptor file (in this case to "Main.swf"), else I received "content not found" errors when trying to run the application.
unknown
d7578
train
Are you sure you need to make cameraNode a child of marble? Because according to SKNode docs: when a node’s coordinate system is scaled or rotated, this transformation is applied both to the node’s own content and to that of its descendants see SKNode So i assume you need to un-child camera from marble. And to achive that followint the object behavior from camera, you may update camera coordinates somewhere in the code, that moves the marble A: I have un-childed my camera to my sphere and made my class a SCNSceneRendererDelegate protocol and added this to the rendering loop: -(void) renderer:(id)renderer updateAtTime:(NSTimeInterval)time { [cameraNode setPosition: SCNVector3Make(marbleNode.presentationNode.position.x, marbleNode.presentationNode.position.y + 5, marbleNode.presentationNode.position.z + 10)]; } If I log the coordinates of the marble.presentationNode they are changing but my camera still doesn't move!
unknown
d7579
train
What I see, with the parenthetical clauses, is a recursive problem crying out for a recursive solution. The following is a rethink of your program that might give you some ideas of how to restructure it, even if you don't buy into my recursion argument: import sys from enum import Enum class Type(Enum): # This could also be done with individual classes leftparentheses = 0 rightparentheses = 1 operator = 2 empty = 3 operand = 4 OPERATORS = { # get your data out of your code... "+": "add", "-": "subtract", "*": "multiply", "%": "modulus", "/": "divide", } def textOperator(string): if string not in OPERATORS: sys.exit("Unknown operator: " + string) return OPERATORS[string] def typeof(string): if string == '(': return Type.leftparentheses elif string == ')': return Type.rightparentheses elif string in OPERATORS: return Type.operator elif string == ' ': return Type.empty else: return Type.operand def process(tokens): stack = [] while tokens: token = tokens.pop() category = typeof(token) print("token = ", token, " (" + str(category) + ")") if category == Type.operand: stack.append(token) elif category == Type.operator: stack.append((textOperator(token), stack.pop(), process(tokens))) elif category == Type.leftparentheses: stack.append(process(tokens)) elif category == Type.rightparentheses: return stack.pop() elif category == Type.empty: continue print("stack = ", stack) return stack.pop() INFIX = "1 + ((C + A ) * (B - F))" # pop/append work from right, so reverse, and require a real list postfix = process(list(INFIX[::-1])) print(postfix) The result of this program is a structure like: ('add', '1', ('multiply', ('add', 'C', 'A'), ('subtract', 'B', 'F'))) Which you should be able to post process into the string form you desire (again, recursively...) PS: type and next are Python built-ins and/or reserved words, don't use them for variable names. PPS: replace INFIX[::-1] with sys.argv[1][::-1] and you can pass test cases into the program to see what it does with them. PPPS: like your original, this only handles single digit numbers (or single letter variables), you'll need to provide a better tokenizer than list() to get that working right.
unknown
d7580
train
Install python-dateutil pip install python-dateutil A: Step 1. First thing is upgrade pip for corresponding python version (3 or 2) you have. pip3 install --upgrade pip or pip2 install --upgrade pip Step2. Some times directly running command wont work since There are probably multiple versions of python-dateutil installed. * *Try to run pip uninstall python-dateutil will give below message if python-dateutil is already un installed. Cannot uninstall requirement python-dateutil, not installed *Then, you can run pip install python-dateutil again. NOTE : Directly running step2 wont work for users whose python and pip versions are not compatible.
unknown
d7581
train
When it is checked, iOS will draw the entire area covered by the object in transparent black before it actually draws the object.It is rarely needed. Beginning IOS 5 Development: Exploring the IOS SDK, page 81, paragraph3. A: It will apply an OpenGL "clear context" before starting the DrawRect function of the UIView: glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT);
unknown
d7582
train
You need to use ? at the end of target URI to strip off any existing query string. Also you can use a relative target URI also if target is on same domain. Use this rule: RewriteEngine On RewriteCond %{QUERY_STRING} ^id= [NC] RewriteRule ^(?:index\.php)?$ /? [R=301,L,NC]
unknown
d7583
train
From the jq dialog api documentation: "If you want to reuse a dialog, the easiest way is to disable the "auto-open" option with: $(foo).dialog({ autoOpen: false }) and open it with $(foo).dialog('open'). To close it, use $(foo).dialog('close'). A more in-depth explanation with a full demo is available on the Nemikor blog"
unknown
d7584
train
In resume: .NET + EF + ORACLE Prerequisites * *.Net 4 or above *At least one Oracle Home installed *ODAC 11.2.0.3.0 or above *Make sure the bit signature of oracle and of your software are the same *In case you are using 32bit, be sure that the appPools allow 32bit NOTE: EF version does not seem to matter
unknown
d7585
train
The real deal in your question is: how can I get a list of the available days so I can join my other tables and produce my output, right? I mean, having a list of days, all you need to is JOIN the other tables. As you have a limited list (days of the year), I'd suggest creating a table with a single column containing the 365 (or 366) days (1, 2, 3, ...) and JOIN it with your other tables. The query would be smtg similar to: SELECT ... -- fields u want FROM YOUR_NEW_TABLE n JOIN DAYS_AVAILABLE D on (n.DAY between D.From and D.To) JOIN ... -- other tables that you need info
unknown
d7586
train
You have a clash between your model and form, which are both named Car. Typically you would fix this by renaming the form CarForm. Note that you shouldn't normally need to create the object with car_obj = Car(...). If you use a model form, you can simplify your code to car_obj = form.save(). You should also move CarForm(request.POST) inside the if request.method == 'POST' check, and include form in the template context. Putting that together, you get something like: def add_user(request): if request.method == 'POST': form = CarForm(request.POST) if form.is_valid(): car_obj = form.save() return HttpResponseRedirect('/inventory/add/') else: form = CarForm() return render(request, 'cars/inventory-add.html', {'form': form}) A: In your views.py file line 2 form = Car(request.POST): change it to form = CarForm(request.POST): Hope it works!
unknown
d7587
train
You can use this to help you out with the proyect http://developer.android.com/training/multiscreen/screensizes.html A: The answer was that the system does use a standard multiplier for each dpi level (1.5x for hdpi for example). In order to get around this I just used the .xdpi and .ydpi values of DisplayMetrics and do my calculations off of those real values. A: Usually when ever we want to do like this we usually use wrap_content. so once try layout_width = "wrap_content",layout_height = "wrap_content". Such that ANdroid SDK will look.
unknown
d7588
train
I suppose you are replaying the recorded plan for 1 user. Most probably your issue is due to not variabilizing (Regexp Post-Processor or CSS/Jquery Post Processor to extract and variable to inject) some dynamic data that is needed for the additionnal users. So when you put 1, it works because IDs correspond to recorded user, but when you put more, at some step you have the second users using the IDs of the first one. Google "correlation with jmeter" to understand and fix your issue. A: In case you have the correct script then check the business of your application. As I have experienced some applications don't allow many users submit the form at the same time. It will lock the form for the first user and the second user cannot submit, the second user will receive the response data with messages like "This form is being used by another user..." or "The data on this form is out of date, please refresh...". In that case, I use a Logic Controller, called "Critical Section Controller". It will handle the users to make sure the transaction will be executed by only one user at a time.
unknown
d7589
train
To completely determine a scene 3D data from a given image, you need to know the perspective projection parameters that formed your image. They are: * *camera intrinsics: focal length (a must!), and distortion parameters (if you want high precision) * *camera extrinsic parameters (rotation/ translation on the three axes) Detailed: Focal length can be obtained from viewing angle, with this formula: fx = imageWidth/(2*tan(alphaX)), and similar for the other dimension. If you have neither fx, nor aperture, you cannot reconstruct your 3D image. Another way to extract them is to calibrate the camera. See http://opencv.itseez.com/modules/calib3d/doc/calib3d.html, but it seems you cannot use it (you said you don't have access to camera.) The vanishing point (VP) is used to determine the angles at which camera was orientated. So, a difference between the image center and the VP gives you the rotation info: yaw = ((camera.center.x (pixels) - VP.x)/image.x )* aperture. pitch = similar. The roll angle cannot be extracted from VP, but from the horizon line. The last parameters you need are the translations. Depending of the application, you can set them all 0, or consider only the height as being relevant. None of them can be usually recovered from the image. Now, having all this data, you can look here Opencv virtually camera rotating/translating for bird's eye view to see how all this measures influence your perspective correction. A: Not a very simple topic, but see the Feb 23 lecture here: https://courses.engr.illinois.edu/cs543/sp2017/ There is not a one-size-fits-all solution, but depending on scene structure, it is often possible to add objects to photos. See also: http://dl.acm.org/citation.cfm?id=2024191
unknown
d7590
train
Please try with this one. WL.Client.init({ onSuccess : function() { WL.Logger.config({ maxFileSize : 100000, // allow persistent storage of up to 100k of log data // level : 'info', // at debug (and above) level capture : true, stringify: true // capture data passed to log API calls into persistent storage }); WL.Analytics.enable().then(function (success) { console.log(success); }).fail(function (errObj) { console.log(errObj); }); setInterval(function() { WL.Logger.send(); WL.Analytics.send(); }, 6000); console.log("Success WL"); }, onFailure : function(err){ console.log("Failed WL"); WL.Logger.error('Caught an exception', err); } });
unknown
d7591
train
To make a long answer short: yes, this is an example of a Dependency Inversion Principle
unknown
d7592
train
I've seen this problem before with other projects. In my experience, xCode often struggles with old projects, especially big ones with other projects / frameworks linked in. The 'official' way; * *try to compile the project. *Navigate to the error by clicking the red exclamation mark in the central console. (upper-middle of the app) *scroll down in the list to the left, find the red exclamation mark. *click the project (blue icon, possible .xcodeproj extension) in the list to the left that's giving the error. *go to 'Build settings' *Find the 'Compiler for C/C++/Objective-C' setting in the 'Build Options' category. *Change the compiler from GCC 4.2 to a supported one. (Now: Apple LLVM or LLVM GCC) This approach might or might not work for you. It might be my limited understanding, but it seems that in some cases, old settings 'linger' without begin accessible through the GUI, but they can still be causing problems. Moreover, if this error appears in a framework rather than a project, you're out of luck since you can't always change the settings for those. In that case: The dirty way; * *Use 'grep' to find the incorrect settings, should be in .pbxproj files. Open a command line of your project, and do: grep -r "GCC_VERSION" * | grep 4.2 *You'll find lines like these: GCC_VERSION = 4.2; *Open the file in your favorite text editor, and change to: GCC_VERSION = com.apple.compilers.llvmgcc42; * *or if you want to experiment with the latest compiler: GCC_VERSION = com.apple.compilers.llvm.clang.1_0; * *Instead of using these values, you can look in the main project file or another project that works, to see which value is used there. If that doesn't help either; After converting projects between too many versions of xCode, eventually it will actually save you time to start with a clean slate, open a new empty xCode project, and manually drag-in all code from your old project. A: Make sure you change the complier settings for the extensions as well. If it still says "Unsupported compiler", you probably forgot to change it in one of the three20 sub projects. Also, check that you have both armv6 and armv7 under the Architectures Can you send a screenshot of the build settings you have? A: I solved this problem removing an old "Build" folder inside the Three20 folder.
unknown
d7593
train
It's possible, this is an example I made using web3:0.20.7: https://github.com/le99/sawtooth-with-metamask-signatures/blob/master/src/App.js The important function is onClick() import './App.css'; import React, { useState } from 'react'; var ethUtil = require('ethereumjs-util') const secp256k1 = require('secp256k1') const CryptoJS = require('crypto-js'); const axios = require('axios').default; const cbor = require('cbor') const Web3 = require('web3'); //https://github.com/ethereum/web3.js/blob/0.20.7/DOCUMENTATION.md // let web3 = new Web3(Web3.givenProvider || "ws://localhost:8545"); let web3; if (typeof window.web3 !== 'undefined') { web3 = new Web3(window.web3.currentProvider); } else { // set the provider you want from Web3.providers web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); } const hash = (x) => CryptoJS.SHA512(x).toString(CryptoJS.enc.Hex) // https://stackoverflow.com/questions/33914764/how-to-read-a-binary-file-with-filereader-in-order-to-hash-it-with-sha-256-in-cr function arrayBufferToWordArray(ab) { var i8a = new Uint8Array(ab); var a = []; for (var i = 0; i < i8a.length; i += 4) { a.push(i8a[i] << 24 | i8a[i + 1] << 16 | i8a[i + 2] << 8 | i8a[i + 3]); } return CryptoJS.lib.WordArray.create(a, i8a.length); } async function onClick(){ const ethereum = window.ethereum; var from = web3.eth.accounts[0] // var msgHash = ethUtil.keccak256(Buffer.from('An amazing message, for use with MetaMask!')) var msgHash = Buffer.from('8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede', 'hex'); console.log(from); let signature1 = await new Promise((resolve, reject)=>{ web3.eth.sign(from, msgHash, function (err, result) { if (err) return reject(err) return resolve(result) }) }); const rpk3 = secp256k1.ecdsaRecover(Uint8Array.from(Buffer.from(signature1.slice(2, -2), 'hex')), parseInt(signature1.slice(-2), 16) - 27, Uint8Array.from(msgHash)); let publicKey = Buffer.from(rpk3, 'hex').toString('hex') console.log(msgHash.toString('hex')); console.log(signature1); console.log(publicKey); console.log(); const INT_KEY_FAMILY = 'intkey' const INT_KEY_NAMESPACE = hash(INT_KEY_FAMILY).substring(0, 6) const address = INT_KEY_NAMESPACE + hash('foo').slice(-64) console.log('address:',address); const payload = { Verb: 'set', Name: 'foo', Value: 41 } console.log('public:', publicKey); const payloadBytes = cbor.encode(payload) const protobuf = require('sawtooth-sdk/protobuf') const transactionHeaderBytes = protobuf.TransactionHeader.encode({ familyName: 'intkey', familyVersion: '1.0', inputs: [address], outputs: [address], signerPublicKey: publicKey, // In this example, we're signing the batch with the same private key, // but the batch can be signed by another party, in which case, the // public key will need to be associated with that key. batcherPublicKey: publicKey, // In this example, there are no dependencies. This list should include // an previous transaction header signatures that must be applied for // this transaction to successfully commit. // For example, // dependencies: ['540a6803971d1880ec73a96cb97815a95d374cbad5d865925e5aa0432fcf1931539afe10310c122c5eaae15df61236079abbf4f258889359c4d175516934484a'], dependencies: [], payloadSha512: CryptoJS.SHA512(arrayBufferToWordArray(payloadBytes)).toString(CryptoJS.enc.Hex), nonce:"hey4" }).finish() let sss=CryptoJS.SHA256(arrayBufferToWordArray(transactionHeaderBytes)).toString(CryptoJS.enc.Hex); let dataHash=Uint8Array.from(Buffer.from(sss, 'hex')); let signature = await new Promise((resolve, reject)=>{ web3.eth.sign(from, dataHash, function (err, result) { if (err) return reject(err) return resolve(result) }) }); signature = signature.slice(2, -2) console.log('sha1:', CryptoJS.SHA512(arrayBufferToWordArray(transactionHeaderBytes)).toString(CryptoJS.enc.Hex)) console.log('signature1:', signature) const transaction = protobuf.Transaction.create({ header: transactionHeaderBytes, headerSignature: signature, payload: payloadBytes }) //-------------------------------------- //Optional //If sending to sign outside const txnListBytes = protobuf.TransactionList.encode({transactions:[ transaction ]}).finish() //const txnBytes2 = transaction.finish() let transactions = protobuf.TransactionList.decode(txnListBytes).transactions; //---------------------------------------- //transactions = [transaction] const batchHeaderBytes = protobuf.BatchHeader.encode({ signerPublicKey: publicKey, transactionIds: transactions.map((txn) => txn.headerSignature), }).finish() // sss=CryptoJS.SHA256(arrayBufferToWordArray(batchHeaderBytes)).toString(CryptoJS.enc.Hex); dataHash=Uint8Array.from(Buffer.from(sss, 'hex')); signature = await new Promise((resolve, reject)=>{ web3.eth.sign(from, dataHash, function (err, result) { if (err) return reject(err) return resolve(result) }) }); signature = signature.slice(2, -2) const batch = protobuf.Batch.create({ header: batchHeaderBytes, headerSignature: signature, transactions: transactions }) const batchListBytes = protobuf.BatchList.encode({ batches: [batch] }).finish() console.log(Buffer.from(batchListBytes).toString('hex')); console.log('batchListBytes has the batch bytes that ca be sent to sawtooth') // axios.post(`${HOST}/batches`, batchListBytes, { // headers: {'Content-Type': 'application/octet-stream'} // }) // .then((response) => { // console.log(response.data); // }) // .catch((err)=>{ // console.log(err); // }); } The example is based on: https://sawtooth.hyperledger.org/docs/core/releases/1.2.6/_autogen/sdk_submit_tutorial_js.html There is a lot of low level stuff, hyperledger and Metamask represent signatures slightly differently. Also most libraries for Metamask automatically wrap the data (https://web3js.readthedocs.io/en/v1.2.11/web3-eth-accounts.html#sign), they then hash it using keccak256, and that hash is what is finnally signed with secp256k1, which is not what you need for Sawtooth. An example where no wraping or intermediaries are used to sign is: https://github.com/danfinlay/js-eth-personal-sign-examples/blob/master/index.js
unknown
d7594
train
I believe what you're trying to do is: for (var x in languages) { if (typeof languages[x] === "string") { console.log(languages[x]); } } The way you've currently coded it will print out all the "keys" in the object since the keys are all "strings". A: In object literal terms, english,french,notALanguage, spanish are property. Properties are strings in JavaScript, although when defining the property name inside an object literal you may omit the string delimiters. When looping through property names using a for...in, the property name is a string like for (x in languages) { alert(typeof x); //-> "string" } You need like this var languages = { english: "Hello!", french: "Bonjour!", notALanguage: 4, spanish: "Hola!" }; // print hello in the 3 different languages for (var x in languages) { //console.log(typeof x); //it will print 4 times because all keys are string if (typeof languages[x] === "string") { console.log(languages[x]) } } Demo http://jsfiddle.net/4hxgvr6q/ A: Thanks I actually found the same exact question I had from user :Leahcim posted with the correct answer from post user: Some Guy JavaScript: using typeof to check if string for (var hello in languages) { var value= languages[hello] if (typeof value === "string") { console.log(value) } };
unknown
d7595
train
How about this: var converters = { 'SIToImperial' : { 'cm' : function(val) { // implementation, return something }, 'kg' : function(val) { // implementation, return something } //, etc. }, 'SIToUS' : { 'cm' : function(val) { // implementation, return something }, 'kg' : function(val) { // implementation, return something } //, etc. }, 'USToSI' : { 'cm' : function(val) { /* ... */ } // etc } // , etc } SIToSomething(value, unit, system) { return converters["SITo" + system][unit](value); } var meterInImperial = SIToSomething(100, 'cm', 'Imperial'); var fiftyKilosInUS = SIToSomething(50, 'kg', 'US'); A: What you can do is have a base unit, and for each target unit, define conversion functions to/from this base unit. Then, to convert from A to B, for example, you'd have this: A -> base -> B This way, you only need two conversion functions per unit (not counting the base unit): var units = { a: { toBase: function(value) { return value * 2; }, fromBase: function(value) { return value / 2; } }, b: { toBase: function(value) { return 1.734 * value + 48; }, fromBase: function(value) { return (value / 1.734) - 48; } } } function convertFromTo(unitA, unitB, value) { return unitB.fromBase(unitA.toBase(value)); } convertFromTo(units.a, units.b, 36489); A: Do all conversions to/from SI. For example if converting Imperial->US, you'd go Imperial->SI->US. This is minimal effort you can put in. It also gets you SI "for free".
unknown
d7596
train
Unfortunately, it is currently not possible to develop for Windows Phone 8 on Windows 7. In the system requirements of Windows Phone 8 SDK it states you need to have Windows 8 to develop Windows Phone 8 apps. Directly from MSDN: Windows Phone SDK 8.0 requires 64-bit Windows 8 Pro or higher. You can't develop Windows Phone 8 apps on Windows 7, on Windows Server 2008, or on Windows Server 2012. The Windows Phone 8 Emulator has special hardware, software, and configuration requirements. For more info, see System requirements for Windows Phone Emulator. This is mainly because of the Hyper-V emulator that is in windows 8. Be sure if you buy Windows 8 you get the Pro (64bits) version because the normal version has no Hyper-V in it also your BIOS has to support virtualization to run the emulator in Hyper-V.
unknown
d7597
train
Thanks to a friend for helping me with the answer: "text": [ { "signal": "tooltip.amount + ' + ' + tooltip.category", "test": "tooltip.amount" }, {"value": ""} ], The issue was when you hover out the tooltip object does not have a value since we are concatenating the values with the ' + ' string. The undefined object is coerced to the 'undefined' string. Updating the string value to an empty string again is what is required.
unknown
d7598
train
The old answers to this question are ok... However, the official documentation suggests a new, more concise solution: First set the day you want to be the lower bound var today = new Date().toISOString().slice(0,10); Then include the range using validRange. Simply omit the end date. validRange: { start: today } A: In FullCalendar v3.0, there is the property selectAllow: selectAllow: function(info) { if (info.start.isBefore(moment())) return false; return true; } A: In fullcalendar 3.9, you might prefer the validRange function parameter : validRange: function(nowDate){ return {start: nowDate} //to prevent anterior dates }, Drawback: this also hides events before that datetime A: You can combine: -hide text by CSS as mentioned in question -disable PREV button on current month -check date on dayClick/eventDrop etc: dayClick: function(date, allDay, jsEvent, view) { var now = new Date(); if (date.setHours(0,0,0,0) < now.setHours(0,0,0,0)){ alert('test'); } else{ //do something } } A: I have done this in my fullcalendar and it's working perfectly. you can add this code in your select function. select: function(start, end, allDay) { var check = $.fullCalendar.formatDate(start,'yyyy-MM-dd'); var today = $.fullCalendar.formatDate(new Date(),'yyyy-MM-dd'); if(check < today) { // Previous Day. show message if you want otherwise do nothing. // So it will be unselectable } else { // Its a right date // Do something } }, I hope it will help you. A: I like this approach: select: function(start, end) { if(start.isBefore(moment())) { $('#calendar').fullCalendar('unselect'); return false; } } It will essentially disable selection on times before "now". Unselect method A: This is what I am currently using Also added the .add() function so the user cannot add an event at the same hour select: function(start, end, jsEvent, view) { if(end.isBefore(moment().add(1,'hour').format())) { $('#calendar').fullCalendar('unselect'); return false; } A: You can use this: var start_date= $.fullCalendar.formatDate(start,'YYYY-MM-DD'); var today_date = moment().format('YYYY-MM-DD'); if(check < today) { alert("Back date event not allowed "); $('#calendar').fullCalendar('unselect'); return false } A: Thanks to this answer, I've found the solution below: $('#full-calendar').fullCalendar({ selectable: true, selectConstraint: { start: $.fullCalendar.moment().subtract(1, 'days'), end: $.fullCalendar.moment().startOf('month').add(1, 'month') } }); A: I have tried this approach, works well. $('#calendar').fullCalendar({ defaultView: 'month', selectable: true, selectAllow: function(select) { return moment().diff(select.start, 'days') <= 0 } }) Enjoy! A: below is the solution i'm using now: select: function(start, end, jsEvent, view) { if (moment().diff(start, 'days') > 0) { $('#calendar').fullCalendar('unselect'); // or display some sort of alert return false; } A: No need for a long program, just try this. checkout.setMinSelectableDate(Calendar.getInstance().getTime()); Calendar.getInstance().getTime() Gives us the current date. A: I have been using validRange option. validRange: { start: Date.now(), end: Date.now() + (7776000) // sets end dynamically to 90 days after now (86400*90) } A: In Fullcalendar i achieved it by dayClick event. I thought it is the simple way to do it. Here is my code.. dayClick: function (date, cell) { var current_date = moment().format('YYYY-MM-DD') // date.format() returns selected date from fullcalendar if(current_date <= date.format()) { //your code } } Hope it helps past and future dates will be unselectable.. A: if any one of answer is not work for you please try this i hope its work for you. select: function(start, end, allDay) { var check = formatDate(start.startStr); var today = formatDate(new Date()); if(check < today) { console.log('past'); } else { console.log('future'); } } and also create function for date format as below function formatDate(date) { var d = new Date(date), month = '' + (d.getMonth() + 1), day = '' + d.getDate(), year = d.getFullYear(); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; return [year, month, day].join('-'); } i have tried all above question but not work for me you can try this if any other answer work for you. thanks A: just add this if statement select(info) { if (moment(info.start).format() > moment().format()) { //your code here } else { toast.error("Please select valid date"); } }, A: For FullCalendar React (Disable past day completely): selectAllow={c => (moment().diff(c.start, 'hours') <= 0)}
unknown
d7599
train
Your approach almost worked. I used Set aswell. You just need one ForEach inside your List so it will work. struct ContentView: View { @State var selectKeeper : Set<AnyHashable>? = Set<AnyHashable>() var set : Set<AnyHashable> init() { self.set = Set<AnyHashable>() self.set.insert(SongModel(id: 23, path: "Test", artist: "Test", title: "Test", genre: "Test", sample_rate: 123, bitrate: 123, duration: 123, cover: "Test", remaining: 123, created_at: "Test", filename: "Test", file_size: 123)) self.set.insert(FolderModel(id: 1232, name: "Test", files_quantity: 2, duration: 2, folder_size: 23, created_at: "2020")) } var body: some View { List(selection: $selectKeeper) { ForEach(Array(self.set), id: \.self) { item in HStack { if (item is SongModel) { //Item is SongModel Text(String((item as! SongModel).id)) } else { //Item is FolderModel, better to check object type again here } } } } } } I am creating a sample Set in the init method with two different objects. They will be added to the Set. You just use one ForEach and then check inside whether it is a object of class SongModel or FolderModel.
unknown
d7600
train
After some digging around I found out why it was failing. Chrome extensions are executed in their own javascript space but with the same DOM as the site they run on. See https://developer.chrome.com/extensions/content_scripts#execution-environment. This causes them to have seperate global variables and thus my script's attempts to change them would only affect itself. For anyone looking at how to get around this limitation all you have to do is add a script tag with your code onto the document from your extension.
unknown