text
stringlengths
64
89.7k
meta
dict
Q: App Shows In-Compatible with Moto E from Google Store We have uploaded screenshots, and following is the different part of manifest file: <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.GET_TASKS" /> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.autofocus" /> <uses-feature android:name="android.hardware.telephony" android:required="false" /> <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="21" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:xlargeScreens="true" /> This is not working on some tablets as well. I can provide more information on this. Any suggestions please. A: 1) Some tablets might not have camera? Try adding android:required="false" to camera & autofocus. 2) Also, another reason might be that Open GL isn't supported by all devices (Specially in case of Moto E). so try changing to android:required="false" in <uses-feature android:glEsVersion="0x00020000" android:required="true" /> Moto E has fixed camera focus & apparently doesn't support OpenGL 2. Ref.: App incompatible with Moto E in Play Store If anyone else has faced similar issues, please share your research!
{ "pile_set_name": "StackExchange" }
Q: omega-alpha limit set and manifold Definition: The $\omega$-limit set $L_{\omega}\left ( x \right )$ of $x \in \mathbb{M}$ >is the set of $y \in \mathbb{M}$ which for each y there exists a strictly increasing unbounded sequence of times $t_{0}<t_{1}<t_{2}<\cdot \cdot \cdot $ such that $\lim_{n\rightarrow \infty}\left \| \Psi_{t_{n}}\left ( x \right )-y \right \|=0$ Definition: Let $S\subseteq \mathbb{M}$ be an invariant set. $W^{s}_{s}\left ( S \right )=\left \{ y \in\mathbb{M}:L_{\omega}\left ( y \right )\subseteq S \right \}$ -inset, stable set, stable manifold and $W^{u}\left ( S \right )=\left \{ y \in \mathbb{M}:L_{\alpha}\left ( y \right )\subseteq S \right \}$ -outset, unstable set, unstable manifold I would like to request for a more contextual explanation of the above definition. Would someone kindly do so? Geometrical intuition would be even helpful. Thanks in advance. A: That is an unusual way of describing stable/unstable manifolds, and actually wrong in general. How about say $x'=-x^2$ that has no stable manifold but that according to this definition has? Simply it is not standard (nor correct). On the other hand, the intuition is clear: stable manifolds of $S$ should more or less be (although in general are not) the set of points that converge to the set $S$.
{ "pile_set_name": "StackExchange" }
Q: How to get lat and long coordinates from address string I have a MKMapView that has a UISearchBar on the top, and I want the user to be able to type a address, and to find that address and drop a pin on it. What I don't know is how to turn the address string into longitude and latitude, so I can make a CLLocation object. Does anyone know how I can do this? A: You may find your answer in this question. iOS - MKMapView place annotation by using address instead of lat / long By User Romes. NSString *location = @"some address, state, and zip"; CLGeocoder *geocoder = [[CLGeocoder alloc] init]; [geocoder geocodeAddressString:location completionHandler:^(NSArray* placemarks, NSError* error){ if (placemarks && placemarks.count > 0) { CLPlacemark *topResult = [placemarks objectAtIndex:0]; MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult]; MKCoordinateRegion region = self.mapView.region; region.center = placemark.region.center; region.span.longitudeDelta /= 8.0; region.span.latitudeDelta /= 8.0; [self.mapView setRegion:region animated:YES]; [self.mapView addAnnotation:placemark]; } } ]; A Very simple solution. But only applicable on iOS5.1 or later. A: I used a similar approach like Vijay, but had to adjust one line of code. region.center = placemark.region.center didn't work for me. Maybe my code helps someone as well: let location: String = "1 Infinite Loop, CA, USA" let geocoder: CLGeocoder = CLGeocoder() geocoder.geocodeAddressString(location,completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in if (placemarks?.count > 0) { let topResult: CLPlacemark = (placemarks?[0])! let placemark: MKPlacemark = MKPlacemark(placemark: topResult) var region: MKCoordinateRegion = self.mapView.region region.center.latitude = (placemark.location?.coordinate.latitude)! region.center.longitude = (placemark.location?.coordinate.longitude)! region.span = MKCoordinateSpanMake(0.5, 0.5) self.mapView.setRegion(region, animated: true) self.mapView.addAnnotation(placemark) } })
{ "pile_set_name": "StackExchange" }
Q: How do I clear notifications from the notifications indicator? When clicking the notifications icon in Wingpanel I see: The clear button is gray and I cannot click it. I would like to clear notifications so that the bell icon doesn't show. I have tried clicking on the notifications and they still don't disappear. A: Even if you have 0 new notifications, this indicator will still appear to provide quick access to the applications that make use of it and the associated actions. The indicator's general presence is not an indication of new notifications. If you are using the default icons, the styling of the icon will change to indicate new notifications. It is unknown whether the icons you have chosen to use make that same distinction.
{ "pile_set_name": "StackExchange" }
Q: Is Django now an outlaw? Are there any witnesses left? From what I understand, since everyone in Candyland is dead, Django could theoretically roam the South without becoming an outlaw. Who would testify against him? EDIT: If there's any confusion, by "who would", I didn't mean who would want to. I meant, do you remember any specific character who knows the identity of the person who wrecked Candyland? All I can think of those three slaves in the cage, but IIRC even they were freed and might be gone by now. A: There were certainly plenty of witnesses to the event. The household help who were allowed to escape still continue to be slaves of the Candies. IMO, both the housekeeper and Candie's mistress, Sheba (?), would, perhaps with a little persuasion, be happy to cooperate with any investigators. And investigation there will be, considering the nature of the incident and the personage involved. Moreover, considering Dr.Schulz's body at Candieland as well as the trail left behind at Greenville, plenty of people are aware of Django's existence. Schulz and Django have also had previous dealings with lawmen during their bounty hunting; Django's name and identification would therefore also be widely available. Whether Django will be branded an outlaw depends on the testimony of the Candieland employees. But he'll certainly be wanted for questioning.
{ "pile_set_name": "StackExchange" }
Q: Syntax Error in FROM clause - SQL Fault I have tried alot of changes from previous posts. Does anyone know what could be cause this? (I know the code shouldn't be used from a security point of view but its a small local based system) Con.Open(); oleDbCmd.Connection = Con; OleDbDataReader rdr = null; OleDbCommand cmd = new OleDbCommand("select * from Customers", Con); rdr = cmd.ExecuteReader(); while (rdr.Read()) { Int32 intChech = Convert.ToInt32(cboCustomerID.Text); if (intChech == (Int32)rdr.GetValue(0)) { txtTitle.Text = (string)rdr.GetValue(1); txtSurname.Text = (string)rdr.GetValue(2); txtForename.Text = (string)rdr.GetValue(3); txtAddress.Text = (string)rdr.GetValue(4); txtTown.Text = (string)rdr.GetValue(5); txtCounty.Text = (string)rdr.GetValue(6); txtPostCode.Text = (string)rdr.GetValue(7); txtTelephone.Text = (string)rdr.GetValue(8); } } //PULL DATABASE INFORMATION FOR CAR INFO string strSearch = Convert.ToString(cboCustomerID.Text); string strSQL = @"select * from Hire if [Customer ID] = '"; OleDbDataAdapter dAdapter1 = new OleDbDataAdapter(strSQL, Con); OleDbCommandBuilder cBuidler1 = new OleDbCommandBuilder(dAdapter1); DataTable dataTable1 = new DataTable(); DataSet ds1 = new DataSet(); dAdapter1.Fill(dataTable1); for (int i = 0; i < dataTable1.Rows.Count; i++) { dgHire1.Rows.Add(dataTable1.Rows[i][0], dataTable1.Rows[i][1], dataTable1.Rows[i][2], dataTable1.Rows[i][3], dataTable1.Rows[i][4]); } } A: You should use this code: //PULL DATABASE INFORMATION FOR CAR INFO string strSQL = @"select * from Hire where [Customer ID] = ?"; OleDbDataAdapter dAdapter1 = new OleDbDataAdapter(strSQL, Con); dAdapter1.SelectCommand.Parameters.Add("[Customer ID]", cboCustomerID.Text); OleDbCommandBuilder cBuidler1 = new OleDbCommandBuilder(dAdapter1); Or if you don't want to use command parameters you can use this: string strSQL = @"select * from Hire where [Customer ID] = '" + cboCustomerID.Text + "'"; OleDbDataAdapter dAdapter1 = new OleDbDataAdapter(strSQL, Con); OleDbCommandBuilder cBuidler1 = new OleDbCommandBuilder(dAdapter1); But this is bad practice.
{ "pile_set_name": "StackExchange" }
Q: http: panic serving 127.0.0.1:48286: EOF Here is my code (it's a simple web server in golang) : package main import ( "fmt" "net/http" "log" "io" "github.com/gorilla/mux" "encoding/json" "strconv" "io/ioutil" "os" ) var ( Trace *log.Logger Info *log.Logger Warning *log.Logger Error *log.Logger Response string ) func Init( traceHandle io.Writer, infoHandle io.Writer, warningHandle io.Writer, errorHandle io.Writer) { Trace = log.New(traceHandle, "TRACE: ", log.Ldate|log.Ltime|log.Lshortfile) Info = log.New(infoHandle, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile) Warning = log.New(warningHandle, "WARNING: ", log.Ldate|log.Ltime|log.Lshortfile) Error = log.New(errorHandle, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile) } type check_geo_send struct { Status int `json:"status"` } func checkGeo(w http.ResponseWriter, r *http.Request) { var ipdata ip decoder := json.NewDecoder(r.Body) err := decoder.Decode(&ipdata) fmt.Println(ipdata.Ip) checkErr(err) var data_send check_geo_send data_send.Status = 1 data_json, _ := json.Marshal(data_send) w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Length", strconv.Itoa(len(data_json))) //len(dec) w.Write(data_json) } func checkErr(err error) { if err != nil { panic(err) } } func main() { Init(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr) r := mux.NewRouter() Info.Println("1") r.HandleFunc("/", checkGeo) http.Handle("/", r) err := http.ListenAndServe(":8000", nil) if err != nil { fmt.Println(err) } } and after I made a local tunnel: lt --port 8000 that give me something like: https://proud-chipmunk-52.localtunnel.me But when I try to open the URL with my browser I have this error: INFO: 2018/04/04 11:19:03 Orchestra.go:85: 1 2018/04/04 11:19:08 http: panic serving 127.0.0.1:48286: EOF goroutine 22 [running]: net/http.(*conn).serve.func1(0xc420128280) /usr/lib/go-1.10/src/net/http/server.go:1726 +0xd0 panic(0x6884a0, 0xc420010070) /usr/lib/go-1.10/src/runtime/panic.go:505 +0x229 main.checkErr(0x719940, 0xc420010070) /home/bussiere/Workspace/Alexa/Orchestra.go:79 +0x4a main.checkGeo(0x71c7a0, 0xc420188000, 0xc42013c600) /home/bussiere/Workspace/Alexa/Orchestra.go:65 +0x175 net/http.HandlerFunc.ServeHTTP(0x6f8458, 0x71c7a0, 0xc420188000, 0xc42013c600) /usr/lib/go-1.10/src/net/http/server.go:1947 +0x44 github.com/gorilla/mux.(*Router).ServeHTTP(0xc42010e000, 0x71c7a0, 0xc420188000, 0xc42013c600) /home/bussiere/go/packages/src/github.com/gorilla/mux/mux.go:159 +0xed net/http.(*ServeMux).ServeHTTP(0x86d720, 0x71c7a0, 0xc420188000, 0xc42013c400) /usr/lib/go-1.10/src/net/http/server.go:2337 +0x130 net/http.serverHandler.ServeHTTP(0xc420082ea0, 0x71c7a0, 0xc420188000, 0xc42013c400) /usr/lib/go-1.10/src/net/http/server.go:2694 +0xbc net/http.(*conn).serve(0xc420128280, 0x71ca20, 0xc42012e540) /usr/lib/go-1.10/src/net/http/server.go:1830 +0x651 created by net/http.(*Server).Serve /usr/lib/go-1.10/src/net/http/server.go:2795 +0x27b Maybe because it's using https but I don't have any clue of what is causing this bug. A: As mentioned in the comments by Volker you are currently panic'ing when you don't receive json according to your spec - it's safe to assume this should not be the case, so do some proper error handling. Nonetheless you're code is currently working, assuming you have something similar to this struct: type ip struct { Ip string `json:"ip"` } You can post content matching this struct: curl -d '{"ip":"128.0.0.1"}' -H "Content-Type: application/json" -X POST http://localhost:8000/ This will return: {"status":1}
{ "pile_set_name": "StackExchange" }
Q: How to set up alerts on Ganglia? How can I set up Ganglia so that I get an email if a machine in the cluster is using, for example, greater than 95% of physical RAM? A: There is Open Source project on googlecode named ganglia-alert. This tool connects the gmetad and gets the data. You can configure the rules based on your requirement for sending the alerts. I am planning to use this tool. http://code.google.com/p/ganglia-alert/
{ "pile_set_name": "StackExchange" }
Q: Will I be able to run my site on PHP 7.0? I've started reading about some performance benchmarks with PHP 7.0 which suggest that it is spectacularly much faster. I've searched all over for information on Drupal support for PHP 7.0, but all that I can find concerns Drupal 8 whereas I am still working for the moment on Drupal 7. I have found this article that concerns Drupal on Windows, which suggests that D7 on PHP7 works, however since I am running on Centos or Ubuntu I would welcome any information anyone might have on this. My concern is particularly strong because I am just getting started on a project with massive data inputs, which will thus be very performance sensitive. A: The canonical Drupal 8 issue is tagged "Needs backport to D7", which indicates the community intends to support Drupal 7 on PHP 7 but it may take a little time.
{ "pile_set_name": "StackExchange" }
Q: Excel: Lookup table name excel for a given variable I have one Workbook with multiple projects. Each project has it's own sheet. In each of these sheets there are columns for order numbers ("OrderNub"). In another sheet called "MasterList" contains all of the order numbers across all project. This list is in column A. I need a function or Macro that will search all of my sheets (bar MasterList) and will display the sheet name in column B. Below is what I have in Excel: Option Explicit Function FindMyOrderNumber(strOrder As String) As String Dim ws As Worksheet Dim rng As Range For Each ws In Worksheets If ws.CodeName <> "MasterList" Then Set rng = Nothing On Error Resume Next FindMyOrderNumber = ws.Name On Error GoTo 0 If Not rng Is Nothing Then FindMyOrderNumber = ws.Range("A1").Value Exit For End If End If Next Set rng = Nothing Set ws = Nothing End Function A: Option Explicit Function FindMyOrderNumber(strOrder As String) As String Dim ws As Worksheet Dim rng As Range For Each ws In Worksheets If ws.CodeName <> "MasterList" Then Set rng = Nothing On Error Resume Next Set rng = ws.Columns(1).Find(strOrder) On Error GoTo 0 If Not rng Is Nothing Then FindMyOrderNumber = ws.Name Exit For End If End If Next Set rng = Nothing Set ws = Nothing End Function Assumptions: Your project sheets us Table objects. If they don't, you need to edit line 11 to point to whatever range contains the OrderNub data. If not tables, then your projects at least use the exact same layout. In that case, you could change line 11 to something like: Set rng = ws.Range("C1").EntireColumn.Find(strOrder) The code name of the master list is MasterList. This is not the same as the worksheet name as seen on the tab. This is the VBA code name. I prefer to use that as it is less likely to be changed and break the check. You can find the codename in the VBA editor. For instance, in this screenshot, the codename for the first worksheet is shtAgingTable and the name - as shown on the tab in Excel - is AgingTable. This is a function, not a subroutine. That means you don't run it once. It's meant to be used like any other built-in function like SUM, IF, whatever. For instance, you can use the following formula in cell B2: =FindMyOrderNumber($A2)
{ "pile_set_name": "StackExchange" }
Q: Datetime in Apps Script var dataInicial = '2012-11-01 00:00:00'; var dataFinal = '2012-11-02 22:00:00'; var strOrders = stmt.executeQuery('SELECT orders_id, date_purchased FROM zen_orders WHERE orders_status IN (3, 48, 49, 53) AND last_modified BETWEEN ' + dataInicial + ' AND ' + dataFinal); 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 '00:00:00 AND 2012-11-02 22:00:00' at line 1 (linha 12) This query work on PHP :( A: For e.g. MS ACCESS SQL dates have # to wrap them. The correct character to use when including a literal date value is the pound character (#). Reference MS Access. It really matters when you do date calculations. Perhaps there are certain characters/prefixes you may need to use for SQL within Google Script. So it's great if could check out on a article that talks about using dates/ parameterized dates/ building the sql string for Google Script.. To narrow down the issue give this a try: var strOrders = stmt.executeQuery('SELECT orders_id, date_purchased FROM zen_orders WHERE orders_status IN (3, 48, 49, 53) AND last_modified BETWEEN last_modified - Interval 7 day AND Now()); If this is working in your script well, then surely it's something to do with the way you parse the date. The format. Assuming you are using GOOGLE BigQuery, just know that BigQuery does not currently have a Date or DateTime datatype. You should store your datestamps in BigQuery as integers in POSIX (UNIX epoch) date format, and can convert them to human readable time using the FORMAT_UTC_USEC function. An alternative would be to store datestamps as strings in the YYYY-MM-DD HH:MM:SS.uuuuuu format, convert them in your ordered query using the PARSE_UTC_USEC() function. Reference BigQuery
{ "pile_set_name": "StackExchange" }
Q: Does anyone Know how to implement this design (in swift)? The profiles get pulled in from a server but I don't know how to implement this. Had been thinking about a dynamic table view, but I don't know if you can draw cells like that. The pictures have to be clickable. A: Add A UICollectionView to your screen. In the collection view cell, place a image view, then use this code to create the blue border and circle image... func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell:UICollectionViewCell = self.collectionView.dequeueReusableCellWithReuseIdentifier("BasicCell", forIndexPath: indexPath) as UICollectionViewCell let imageView = cell.viewWithTag(1) as! UIImageView //border imageView.layer.borderWidth = 2.0 imageView.layer.borderColor = UIColor.blueColor().CGColor //make imageView Circle imageView.layer.cornerRadius = imageView.frame.size.width / 2 imageView.clipsToBounds = true return cell }
{ "pile_set_name": "StackExchange" }
Q: How do I use a JSON file with weka I have a JSON file and want to open the data in weka, but when I do, I get the following error: Looking around on the mailing list, there are a few questions about JSON, but TL;DR except that I noticed talk of JSON in the "format weka expects". Of course, there was no mention of what that format is. About to take a dive in the source, but I hope SO users can help before I spend too much time on this. A: To gain an understanding about the format of the JSON object and its relationship to ARFF. The steps were surprisingly simple. Use the GUI tool to do the following: Select the Explorer Option Select open file on the preprocess tab Load any of the default supplied ARFF files The select save which you can then choose the JSON extension basically every JSON file must have: {header:{ relation: , attributes:[{},{}],data:[{},{}]}}} Hope this helps {"houses":{ "relation":"house", "attributes":{ "houseSize":["NUMERIC"], "lotSize": "bedrooms": "granite": "bathroom": "sellingPrice": }, "data":[ [3529,9191,6,0,0,205000 ], [3247,10061,5,1,1,224900], [4032,10150,5,0,1,197900 ], [2397,14156,4,1,0,189900 ], [2200,9600,4,0,1,195000], [3536,19994,6,1,1,325000 ], [2983,9365,5,0,1,230000] ]}} The attributes can have more information specified to them as follows: {"contact_lenses":{ "relation": "contact-lenses", "attributes" : { "age":["young", "pre-presbyopic", "presbyopic"], "spectacle-prescrip":["myope", "hypermetrope"], "astigmatism":["no", "yes"], "tear-prod-rate":["reduced", "normal"], "contact-lenses":["soft", "hard", "none"] }, "data":[] } }
{ "pile_set_name": "StackExchange" }
Q: Cursor on record table type in Oracle I am having a declaration as shown below type respond_field IS record ( provider_id VARCHAR2(100), provider_name VARCHAR2(100)); type respond_field_group IS TABLE OF respond_field INDEX BY BINARY_INTEGER; I have created an variable for respond_field_group and i have populated values for this virtual table. My prblem is how to i can convert/transfer this virtual table to a cursor. What i have tried is show below respond_values is variable of respond_field_group OPEN v_result_cursor for SELECT provider_id FROM TABLE (Cast(respond_values AS respond_field)); But i am getting invalid datatype Please help me out to find a solution for this problem A: You cannot use pl/sql types like this, only sql types (i.e. types defined at schema level not at package or procedure level). Record and associative array (index by table) are pl/sql types. Instead you have to create appropriate object types and use them in your code, for example: SQL> create type respond_field as object 2 ( 3 provider_id varchar2(100), 4 provider_name varchar2(100) 5 ) 6 / Type created. SQL> create type respond_field_group as table of respond_field 2 / Type created. SQL> create or replace function test_fun return respond_field_group as 2 l_rfgroup respond_field_group := respond_field_group(); 3 begin 4 l_rfgroup.extend(2); 5 l_rfgroup(1) := respond_field('abc', '123'); 6 l_rfgroup(2) := respond_field('def', '456'); 7 return l_rfgroup; 8 end; 9 / Function created. SQL> select * from table(test_fun); PROVIDER_ID PROVIDER_NAME --------------- --------------- abc 123 def 456
{ "pile_set_name": "StackExchange" }
Q: First non empty value in Column of data frame in R I have one data frame which has column header but position of coulmn header is not fixed so can i read non empty value in 1st column to get the index of header to process the file. mydata.txt test 34 45 rt 45 56 tet3 67 56 Col1 Col2 Col3 Col4 Col5 45 45 23 56 12 34 45 67 65 32 45 67 78 90 54 56 43 32 12 45 mydata = read.table("mydata.txt") mydata[,1] #how to find first non blank value in first column? In order simplify the about pblm: df<-c("","","",34,23,45) how to find fiest non blank value in df A: Trying to answer your "simplified" problem: df <- c("", "", "", 34, 23, 45) The purrr package provides such functions with detect() and detect_index(): install.packages("purrr", repos = "https://cloud.r-project.org") library(purrr) detect_index(df, function(x) x != "")
{ "pile_set_name": "StackExchange" }
Q: xsl to get value of attribute based on child node element I have the following skosxl file: <skos:Concept rdf:about="http://aims.fao.org/aos/agrovoc/c_0e0e555b"> <ns0:hasStatus>Published</ns0:hasStatus> <skos:prefLabel xml:lang="es">baldíos</skos:prefLabel> <skos:prefLabel xml:lang="en">unclaimed lands</skos:prefLabel> <skos:prefLabel xml:lang="fr">terres vacantes</skos:prefLabel> <dc:created rdf:datatype="xsd:http://www.w3.org/2001/XMLSchema#dateTime">2015-03-09T14:50:41Z</dc:created> <skos:definition> <rdf:Description rdf:about="http://aims.fao.org/aos/agrovoc/def_9343e456"> <rdf:value xml:lang="en">Unclaimed land is land for which there is no owner or claimant.</rdf:value> </rdf:Description> </skos:definition> ..... <rdf:RDF> I wanted to get the value of rdf:about of skos:Concept which is bases on child node ns0:hasStatus, the following I can't seem to make it work: <xsl:template match="root"> <xsl:for-each select="rdf:RDF"> <xsl:text>STARTHERE</xsl:text> <xsl:text>&#13;&#10;</xsl:text> <xsl:text>=LDR 00000nam 2200000Ia 4500</xsl:text> <xsl:text>&#13;&#10;</xsl:text> <xsl:apply-templates select="rdf:Description/skos:narrowMatch" /> <xsl:text>&#13;&#10;</xsl:text> <xsl:apply-templates select="rdf:Description/skos:exactMatch" /> <xsl:text>&#13;&#10;</xsl:text> <xsl:apply-templates select="skos:Concept/skos:narrower" /> <xsl:text>&#13;&#10;</xsl:text> <xsl:apply-templates select="skos:Concept" /> <xsl:text>&#13;&#10;</xsl:text> </xsl:for-each> </xsl:template> .... <xsl:template match="skos:Concept"> <xsl:if test="child::ns0:hasStatus"> <xsl:text>=300 \\$a</xsl:text><xsl:value-of select="@rdf:about" /> <xsl:text>&#13;&#10;</xsl:text> </xsl:if> </xsl:template> <xsl:template match="skos:Concept"> <xsl:if test="skos:broader"> <xsl:for-each select="skos:prefLabel" /> <xsl:text>=301 \\$a</xsl:text><xsl:value-of select="skos:prefLabel[@xml:lang='en']" /> <xsl:text>&#13;&#10;</xsl:text> </xsl:if> </xsl:template> Thanks in advance! A: You can use XPath skos:Concept[ns0:hasStatus] to match <skos:Concept> element that has child <ns0:hasStatus> : <xsl:template match="skos:Concept[ns0:hasStatus]"> <xsl:text>=300 \\$a</xsl:text><xsl:value-of select="@rdf:about" /> <xsl:text>&#13;&#10;</xsl:text> </xsl:template>
{ "pile_set_name": "StackExchange" }
Q: SQL between higher and lower number I'm trying to return values where a column number is between '2000' and '500'. when i do equals 2000 i get the returned row, however when i do it as between i return no rows... This is my query... SELECT * FROM PRE_ADVICE_LINE WHERE (PRE_ADVICE_LINE.USER_DEF_NUM_1 BETWEEN '2100' AND '500') I'm not sure if i can return rows where the between values goes from higher to lower values. I've also tried the SQL as this too: SELECT * FROM PRE_ADVICE_LINE WHERE (PRE_ADVICE_LINE.USER_DEF_NUM_1 BETWEEN 2100 AND 500) I feel it's an obvious error on my behalf, but i cannot fathom it! A: Values for BETWEEN need to be in order. If you have a number, then don't use single quotes What you want would seem to be: WHERE PRE_ADVICE_LINE.USER_DEF_NUM_1 BETWEEN 500 AND 2100
{ "pile_set_name": "StackExchange" }
Q: Nuxt: Differvence nuxtServerInit vs Mddleware vs Plugin What is the difference between 1) nuxtServerInit 2) Middleware 3) Plugin And when is it processed on server side and when is it process on client side. A: nuxtServerInit If the action nuxtServerInit is defined in the store, Nuxt.js will call it with the context (only from the server-side). It's useful when we have some data on the server we want to give directly to the client-side. Middleware In universal mode, middlewares will be called server-side once (on the first request to the Nuxt app or when page refreshes) and client-side when navigating to further routes. In SPA mode, middlewares will be called client-side on the first request and when navigating to further routes. Plugins Nuxt.js allows you to define JavaScript plugins to be run before instantiating the root Vue.js Application. One interesting thing to remember with plugins that isn't directly mentioned is that they're called once on the server and once on the client (Unless you've configured them otherwise). So now to get down to the differences. NuxtServerInit is the most unique of the 3. It's use case is crystal clear: Filling the Vuex store with data available on the server. This is great for setting up the store with some session specific data. The difference between plugins and middleware really just comes down to 2 things: When they are run. How many times they are run. Middleware is always run between page navigations, and will be called on the server for the first route, and then on the client for every navigation the user makes after that. This makes it ideal for doing things like checking authentication between pages. Plugins are (by default) run on both the server and the client, but it's important to remember that they're only run on the client once (unless you refresh). This makes them great for importing and setting up libraries, which can be added onto the Nuxt instance. Plugins are also run before the Nuxt instance is created, meaning you cannot access Nuxt using this. That should further drive home the point that plugins should generally be used for configuring and loading dependencies. Obviously this is an over simplification and there are exceptions, but this should be a good place to start. As you begin to dive further into Nuxt, you'll see that these differences can become very blurred, and find that each of the 3 can technically do almost everything the others can. Just make sure to think about the problem being solved, and pick the tool that makes the most sense to you.
{ "pile_set_name": "StackExchange" }
Q: Does toString create a new object when we call it on a String? I was discussing String with my friend and came to know that calling toString() on a String creates new object? But even my friend doesn't know the reason. Can someone explain this to me? A: The javadoc states This object (which is already a string!) is itself returned. so, no, it doesn't create a new object. Instead, a reference to the same object is returned. It could be (and is) implemented as public String toString() { return this; } Note that String is immutable so it's a non-issue.
{ "pile_set_name": "StackExchange" }
Q: Storing the generic class T in a variable and reusing it in sub methode Storing the generic class T in a variable and reusing it in sub methode. For a WebService with crud on few object: Foo: Bar: Etc.. SetFoo SetBar SetEtc GetFoo GetBar GetEtc UpdateFoo UpdateBar UpdateEtc DeleteFoo DeleteBar DeleteEtc GetList .. .. GetPending .. .. Processed .. .. I have the following singleton generic wrapper on client side, with methode like: public bool Get<T>(int i, out DloExtention result) // DloExtention is an interface implemented by foo, bar, etc.. { result = null; try { if (typeof(T) == typeof(Foo)) { result = WebserviceClient.GetFoo(i); } else if (typeof(T) == typeof(Bar)) { result = WebserviceClient.GetBar(i); } else if (typeof(T) == typeof(Etc)) { result = WebserviceClient.GetEtc(i); } else { throw new NotSupportedException("Get<T>, T is not a supported type."); } } catch (Exception ex) { Log4N.Logger.Error($"Error in Namespace.ClientSide.Get<{nameof(T)}>(int {i} ). " + ex.Message); return false; } return true; } So I can handle all the type simply with the same generic object: class Processor { HashSet<int> validOperation = new HashSet<int>(); HashSet<int> invalidOperation = new HashSet<int>(); internal void Run<T>() { if (Wrapper.Instance.GetListPending<T>(out int[] newEntityList) && newEntityList.Any()) { ProcessEntities<T>(newEntityList, false); } } private void ProcessEntities<T>(int[] idsEnt, bool singleMode) { foreach (var idEnt in idsEnt) { ProcessEntity<T>(idEnt, false); } CloseValidOperation(); RemoveInvalidOperation(); } internal void ProcessIncident<T>(int idEnt) { if (Wrapper.Instance.Get<T>(idEnt, out LanDataExchangeCore.LanDataExchangeWCF.DloExtention currentEntity)) { if (currentEntity.isValid() && currentEntity.toLocalDB()) { validOperation.Add(idEnt); } else { invalidOperation.Add(idEnt); } } } Only Wrapper.Instance.Get<T> and Wrapper.Instance.GetListPending<T> needs the generic parameter. But every methode in the way need to use it only to be able to deliver <T> to the last methode. Is there a way to save the <T> in the Run<T> call into a private variable so inner methode of the class can use it ? I have try adding a Type myType; but can't find the way to use it in generic call. Exemple for the Wrapper.Instance.Get<T> Type myType; // class property var fooWrapperGet = typeof(Wrapper).GetMethod("Get"); var fooOfMyTypeMethod = fooWrapperGet.MakeGenericMethod(new[] { myType }); //fooOfMyTypeMethod.Invoke(Wrapper.Instance , new object[] { new myType() }); // fooWrapperGet, as my wrapper is a singleton, Wrapper dont exposed Get<T>, but Wrapper.instance will expose it. // new myType() <- do not compile. A: Does this work for you? private Dictionary<Type, Func<int, DloExtention>> gets = new Dictionary<System.Type, Func<int, DloExtention>>() { { typeof(Foo), WebserviceClient.GetFoo }, { typeof(Bar), WebserviceClient.GetBar }, { typeof(Etc), WebserviceClient.GetEtc }, }; public bool Get<T>(int i, out DloExtention result) { result = null; var flag = false; if (gets.ContainsKey(typeof(T))) { result = gets[typeof(T)](i); flag = true; } return flag; } The beauty of this is that you can populate your dictionary at run-time.
{ "pile_set_name": "StackExchange" }
Q: Changing LED color for notifications I am basically just experimenting with Android development, and a couple of days ago I came across this app called "Go SMS Pro", which, among other things, can set up notifications in different colors (blue, green, orange, pink and light blue). So, I have tried to do this myself in my own app, however I cannot change neiher the color nor the blinking internal of the LED. I currently use this code: public class MainActivity extends Activity { static final int NOTIFICATION_ID = 1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(buttonOnClick); } public OnClickListener buttonOnClick = new OnClickListener() { @Override public void onClick(View v) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); Notification notification = new Notification(R.drawable.icon, "Hello", System.currentTimeMillis()); notification.flags = Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_AUTO_CANCEL; notification.ledARGB = Color.BLUE; notification.ledOnMS = 1000; notification.ledOffMS = 300; Context context = getApplicationContext(); CharSequence contentTitle = "My notification"; CharSequence contentText = "Hello World!"; Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); mNotificationManager.notify(NOTIFICATION_ID, notification); } }; } But as I said, it doesn't work the way I want it to; instead it just blinks in regular green with the default delay, and not the one I have set in my code. Can anyone see what is wrong with my code, or know if I have to do something else to achieve this? A: You can use this code: private static final int LED_NOTIFICATION_ID= 0; //arbitrary constant private void RedFlashLight() { NotificationManager nm = (NotificationManager) getSystemService( NOTIFICATION_SERVICE); Notification notif = new Notification(); notif.ledARGB = 0xFFff0000; notif.flags = Notification.FLAG_SHOW_LIGHTS; notif.ledOnMS = 100; notif.ledOffMS = 100; nm.notify(LED_NOTIFICATION_ID, notif); } Instead of using ARGB value as the example show, you can use int property inside android.graphics.Color class to get the color as well (e.g. Color.WHITE) A: Did you try: .setLights(Color.BLUE, 500, 500) ? Works fine on S3, N5, N4, Nexus one too.. A: Leds are a quite non-standard feature in android phones. If you depend in them, you will miss a good chunk of the user base (consider, for example, the SGS phones, which do not even have leds). That said, id the int field ledARGB was not useful, you might need to look into some JNI call from that APK. My guess is that it will have different methods depending on the device in which is running.
{ "pile_set_name": "StackExchange" }
Q: Recipient.Type olCC populates To field on first run I'm in a bit of a conundrum. A piece of code that worked before no longer works as I expect it to without an apparent reason. The particular piece that doesn't work can be simplified down to this: Sub addCC() dim mail as Outlook.MailItem dim recip as Recipient set mail = Application.ActiveInspector.CurrentItem set recip = mail.Recipients.Add("[email protected]") recip.Type = olCC End Sub When I run this on the mail item, on the first run it adds the recipient in the To field not the CC field. On subsequent reruns of the sub on the same mail item, it keeps adding the email address in CC as expected. Only on the first run it adds a TO instead of CC. I was using this piece of code before and it worked as expected. Now it doesn't and I don't know what's going awry. A: I can reproduce the problem. The best course of action is to open a support case with MS (https://support.microsoft.com/en-us/assistedsupportproducts?wa=wsignin1.0) to ensure this problem gets fixed.
{ "pile_set_name": "StackExchange" }
Q: How/Where to put CSS codes in Sharepoint 2013 I'm very new to sharepoint and I saw many customization on sharepoint sites using CSS codes. Where do I need to put those codes? Like, what page do I need to edit on my master pages? Is it the Seattle, V4, Oslo? I don't have any idea, even on their differences, and do I need to place every images to Style Library before applying it to CSS? Give me brief on where to apply CSS and masterpage? A: Ideally, you would start by creating a copy, rather than editing one of the existing master pages. Which one you choose is purely up to your own aesthetics. Once you're familiar with their creation, you can create one from scratch and with the built in design tools (available through the front end, generates web parts and unique content). As to where to put CSS: 1) If you have CSS that is just used on one page, just put it on that page. Calling unneeded CSS creates extra load (data and processing alike). 2) If you have code that is just used on one or more page layouts, you could include it in the page layout, but that makes it harder to compartmentalize changes. Better to add a reference to a purpose built CSS (CustomWiki.html including a reference to CustomWiki.css). 3) CSS shouldn't be included in the master page, even if it's not something that's going to change often. Create a CSS file for each master page and reference it below your corev15.css. Ex: <!--SPM:<SharePoint:CssRegistration Name="Themable/corev15.css" runat="server"/>--> <!--SPM:<SharePoint:CssRegistration Name="/_catalogs/masterpage/_css/CustomSiteMaster.css" After="corev15.css" runat="server"/>--> Ideally you would place all of your assets in a library before using them, but you can create the code ahead of time if you know where it will live and what it will be called, but an image file referenced in the CSS that is missing won't break anything, it just won't load the images.
{ "pile_set_name": "StackExchange" }
Q: extracting overlapping categories through machine learning I have what I think a peculiar problem, I am trying to get attributes of products that may overlap. In my case, given the title, manufacturer, description, I need to know whether the product is a Jeans or something else and further more, whether it’s a or Skinny Jeans or other types of Jeans. Going through the sci-kit exercises it seems I can only predict one category at a time, which doesn’t apply to my case, any suggestion on how to tackle the problem? What I have in mind right now is to have a training data for each category ex: Jeans = ['desc of jeans 1', 'desc of jeans 2'] Skinny Jeans ['desc of skinny jeans 1', 'desc of skinny jeans 2'] with this training data, I would then ask the probability of a given unknown product and expect this kind of answer in return in percentage of matching: Unknown_Product_1 = { 'jeans': 93, 'skinny_jeans': 80, 't-shirt': 5 } Am I way off base? If this is a correct path to take, if so, how do I achieve it? Thank you! A: You are probably describing a task called multi-label learning or multi-label classification. A key difference between this task and the standard classification task is that by learning a relationship between the labels, you can sometimes obtain better performance than if you train many independent standard classifiers.
{ "pile_set_name": "StackExchange" }
Q: Use area of intersection as a variable in PostGIS I have two geojson files - NYCSample and censusTracts. Each census tract contains a population attribute (integer). My objective is to multiply the population attribute by the % area of intersection / total area of tract that NYCSample intersects. For example, we see that the sample layer intersects 6 census tracts. If each of the census tracts contain 100 people, then the output should be 100 * (% of intersection). Using the st_area(st_intersection()) functions in PostGIS, how would one output a table with population adjusted for % of area intersected? So far, I've written this query but am not sure how to create a separate pop_adjusted variable CREATE TABLE test_join AS SELECT t.*, m.* FROM censusTracts AS t , NYCSample AS m WHERE ST_Intersects(t.geom, m.geom) AND ( ST_Area(ST_Intersection(t.geom, m.geom)) /ST_Area(t.geom) ) A: I think you're confusing some stuff. You want all rows in which there is an intersection carried over. That means that only the call to ST_Intersects should be in the join-condition or where-clause. I've modified the table to use explicit joins. CREATE TABLE test_join AS SELECT ST_Area(ST_Intersection(t.geom, m.geom)) / ST_Area(t.geom) * pop AS pop_adjusted t.*, m.*, FROM censusTracts AS t JOIN NYCSample AS m ON ST_Intersects(t.geom, m.geom) It's also somewhat worth nothing that this needn't be a seperate table. You can create a view (see CREATE VIEW) just the same way, and qgis should be able to display it for you.
{ "pile_set_name": "StackExchange" }
Q: Pandas - Error in if function when creating a new column in a dataframe I have a column lastseasontype object (no NULL or NaN) in the df draft. I would like to create a new column Age_retired based on the comparison of the last 2 digits of lastseason to 50. Here is the last season column 0 1993-94 1 1990-91 2 1993-94 3 1997-98 Name: lastseason, dtype: object Extract the last 2 digit and convert to numeric print pd.to_numeric(draft['lastseason'].astype('str').str[-2:],errors='coerce') 0 94 1 91 2 94 3 98 Name: lastseason, dtype: int64 Create column Age_retired if pd.to_numeric(draft['lastseason'].astype('str').str[-2:],errors='coerce') <50: draft['Age_retired'] = 2000 + pd.to_numeric(draft['lastseason'].astype('str').str[-2:],errors='coerce') else: draft['Age_retired'] = 1900 + pd.to_numeric(draft['lastseason'].astype('str').str[-2:],errors='coerce') I got the error with the if line: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I am thinking that my if-else structure is not applied to columns with many values. Really appreciate any help A: Yes, the if-else construct won't be evaluated element-wise. However, this is solved easily using the series .map method which applies a function elementwise. First you define the function, then you map it. You can simply assign the result of the mapping to draft['age_retired'] to create the new column. In [10]: def add_age_retired(x): if x < 50: return 2000 + x else: return 1900 + x In [11]: pd.to_numeric(draft['lastseason'].astype('str').str[-2:],errors='coerce').map(add_age_retired) Out[11]: 0 1994 1 1991 2 1994 3 1998 Name: lastseason, dtype: int64 In [12]: draft['Age_retired'] = pd.to_numeric(draft['lastseason'].astype('str').str[-2:],errors='coerce').map(add_age_retired) In [13]: draft Out[13]: lastseason Age_retired 0 1993-94 1994 1 1990-91 1991 2 1993-94 1994 3 1997-98 1998
{ "pile_set_name": "StackExchange" }
Q: Length of string[] (number of elements in a string) I want to cout my string, everything works as it should, but when the string is shown, it immediately shows me the "example_4578.exe has stopped running" error. I have noticed that the problem is in the i < str[32].length part, because when I change it to i < 3, it works without any problem. How should I solve this? std::string str[32]; cin >> str[1]; cout << "str[1]=" << str[1] << endl; cin >> str[2]; cout << "str[2]=" << str[2] << endl; for (int i = 0; i < str[32].length; i++) { cout << str[i]; } EDIT 1. I've made a huge mistake. I actually want to find the "number" of elements/words in "str". In my example, I have only designed two cins. But I actually want to design a "for" loop later on, so that the user can input as many words as he wants, so if he inputs 4 words, I want that code to return those number of words to me. How should I do this? In other words, how can I find out how many elements are in "str"? A: Couple of things: C++ is 0-indexed. What this means is that std::string str[32] has indices that go from 0 to 31, and str[32] should not be accessed. This will cause a crash. str[31].length() (which is presumably what you wanted) is the length of the last string, not the length of the array. The length of the array is 32, and your loop should read for(int i = 0; i < 32; i++). A: str[32].length is not what you think. I guess you meant somthing like: length of a 32-elements array. Right? What you've written is pointer to funciton length of 33rd element of array. This is because the types are: std::string str[32]; // `str` is 32-element array of `std::strings` str[32]; // `std::string` taken from 33rd position in array `str` (arrays' indexing starts at 0) std::string has a member function named size_t std::string::length(). When referenced by name, you get its address. To achieve what you wanted, you'd need to write: for (int i = 0; i < 32; i++) { cout << str[i]; } Unfortunately, plain arrays don't have length (or anything similar) built in. So, you'd either need to use a constant, or (better) use a container, such as std::vector.
{ "pile_set_name": "StackExchange" }
Q: to be between apartments When somebody says that somebody else is between apartments, what do they mean? Take this sentence as an example: My brother lives in Chicago. At the moment he’s between apartments, so he‘s living with a friend. A: It's a euphemistic way of saying he has no proper home of his own. He has moved out of his old apartment, and expects to someday move into another apartment, but has not moved in yet. "Between" is used in a temporal sense, rather than in a spatial sense. To be "between jobs" is often a euphemism for being unemployed. A: "between girlfriends" is another variant. It makes it more obvious than you can't really be between girlfriends, since you may not ever get the future girlfriend, that is needed to bound the "between". So use of "between" is a statement of belief about the future. Another twist on that indirect statement on the future, is when someone jokingly introduces their wonderful marriage partner as "their first wife". It's a joke about future possibilities and a brag about not needing future possibilities. As well as commentary on the typical rates of divorce. So "between apartments" is a bit of a brag that even though one is homeless, it's no big deal, something good will happen in the future. It's casualness is both a statement of fact about where you live, and your feelings about that fact. "homeless" doesn't convey that optimism, and also implies that the current situation is not as manageable as 'between apartments" is. Specifically, you don't need to offer a friend money, probably.
{ "pile_set_name": "StackExchange" }
Q: what is difference between using and not using call method in redux saga? I just wonder, in redux-saga generator function, what is the difference between yield call(function, ...arg) and yield function(...arg)? Here is a piece of my code, in a generator function: const userRef = yield call(createUserProfileDocument, userAuth); and const userRef = yield createUserProfileDocument(userAuth); What is different? Both lines work as expected. Is it just that yield + call is a standard way to use saga or is there more to it? A: According to official docs the difference is that with call we're not executing the fetch call immediately, instead, call creates a description of the effect. Just as in Redux you use action creators to create a plain object describing the action that will get executed by the Store, call creates a plain object describing the function call. The redux-saga middleware takes care of executing the function call and resuming the generator with the resolved response. This allows us to easily test the Generator outside the Redux environment. Because call is just a function which returns a plain Object. import { call } from 'redux-saga/effects' import Api from '...' const iterator = fetchProducts() // expects a call instruction assert.deepEqual( iterator.next().value, call(Api.fetch, '/products'), "fetchProducts should yield an Effect call(Api.fetch, './products')" ) Now we don't need to mock anything, and a basic equality test will suffice. The advantage of those declarative calls is that we can test all the logic inside a Saga by iterating over the Generator and doing a deepEqual test on the values yielded successively. This is a real benefit, as your complex asynchronous operations are no longer black boxes, and you can test in detail their operational logic no matter how complex it is.
{ "pile_set_name": "StackExchange" }
Q: Socket in Ruby blindly hangs when trying to check an offline server I use the following code to check the server status of a certain game server to see if the game server is online. begin sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) sockaddr = Socket.sockaddr_in(game_server.gameserver_port, game_server.gameserver_hostname) sock.connect(sockaddr) server_status.status = 1 rescue server_status.status = 0 end However it seems that the code blindly hangs up on the line without proceeding anywhere sock.connect(sockaddr) and does not throw an error when there's no services listening on that port. Is there a better way to do this in Ruby? A: Could timeout be a good solution? require 'timeout' begin timeout(5) do # socket stuff... end rescue Timeout::Error puts "Timed out!" end
{ "pile_set_name": "StackExchange" }
Q: jndi pattern and seam 2.3 ear I'm trying to migrate my seam 2.2 application to seam 2.3. I'm using an ear packaged application that consists of several modules. When I try to load a page I get the following error: Caused by: javax.naming.NameNotFoundException: AdmissionDAOImpl -- service jboss.naming.context.java.app.Cosara.AdmissionDAOImpl at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:97) at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:178) at org.jboss.as.naming.InitialContext.lookup(InitialContext.java:123) at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:214) at javax.naming.InitialContext.lookup(InitialContext.java:392) [rt.jar:1.6.0_37] at org.jboss.seam.Component.instantiateSessionBean(Component.java:1407) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.Component.instantiate(Component.java:1370) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.Component.newInstance(Component.java:2186) [jboss-seam.jar:2.3.0.Final] ... 63 more My Jboss AS 7.1.1 server gives me the following jndi patterns to locate the AdmissionDAOImpl. java:global/Cosara/Cosara2IntDAO/AdmissionDAOImpl!be.ugent.cosara2.dao.AdmissionDAO java:app/Cosara2IntDAO/AdmissionDAOImpl!be.ugent.cosara2.dao.AdmissionDAO java:module/AdmissionDAOImpl!be.ugent.cosara2.dao.AdmissionDAO java:global/Cosara/Cosara2IntDAO/AdmissionDAOImpl java:app/Cosara2IntDAO/AdmissionDAOImpl java:module/AdmissionDAOImpl What JNDI pattern should I use with seam to locate the EJB? Here I've used java:app/#{ejbName} Also tried java:app/Cosara.jar/#{ejbName} Is there something to replace Cosara.jar in the pattern above to make it more generic? A: The jndi pattern should be defined for each component as described in https://community.jboss.org/blogs/marek-novotny/2011/07/29/seam-2-booking-example-on-jboss-as-7
{ "pile_set_name": "StackExchange" }
Q: How to judge the quality of academic paper (students pov)? I have a master's degree (in maths) and would like to pursue a PhD in future and have at least a year in hand. So I thought of picking some new research topic by reading articles in journals. The problem is how do I know the material I am reading is of a suitable standard. I often hear (and I don't mean to belittle all researcher) rumours that few researchers publish for the heck of publishing. So I don't want to waste my effort in reading those papers. One of my criteria to shortlist papers is to look for the journal which has high brand value. But this method looks superficial to me. So can you suggest some pointer on how does one goes about finding a new research topic of which he/she has no advance knowledge (although I have the pre-requisite knowledge to pursue that topic). A: First, I think that a paper is a "good" paper if you can learn something from it. It doesn't matter what other, more experienced, people have to say. The reason for that is .... Most serious researchers in various fields, math in particular, write for a certain audience. That audience doesn't include novices. Papers are written for other people at a similar level of sophistication as the writer and who are able to fill in details of argument without it being explicitly provided in all cases. Occasionally this leads to errors as you might guess, but it is the way of it. But, on the other hand, most researchers also include a fairly complete list of references and perhaps an even richer bibliography. This is where the novice, even a beginning doctoral student, has to start. Read a paper that seems interesting or was given to you by an advisor. When (not if, when) you get stuck, go to the references for older papers that contribute to the ideas of the current paper. Start to read and understand them until you get stuck. Then, ... Do this recursively until you reach Euclid if necessary, or until you understand the current paper you are reading and then work forward through the stack (or the tree, actually) until you understand the paper of interest that started you on the quest. Take a lot of notes as you do this. Don't depend on memory, especially short term memory to keep you on track. You may need to do this process a few times until you become more accustomed to the ideas and gain insight into what is going on in that small part of math. The papers contain a lot of detail, but it is the insight, not the detail, per se, that gets you to true understanding. But the notes you take will help guarantee that the whole (painful) process actually leaves you better off at the end. If you actually learn something, you have made a personal advancement. I'll note for completeness that some people in science and math do write for a broader audience. Carl Sagan was noted for this, of course, as is Neil deGrasse Tyson. You can learn quite a lot from such authors, but not to the same depth you get from specialists writing for other specialists.
{ "pile_set_name": "StackExchange" }
Q: Having trouble retrieving integer from .properties I keep getting the java.lang.NumberFormatException: null error when I am trying to use an integer that I set in application.properties. This is my application.properties my.prop.for.func=25 This is how I retrieved the value from the .properties file and converted it to an integer to use in a function later on. @Value("${my.prop.for.func}") private String myPropForFuncStr; private int myPropForFunc = Integer.parseInt(myPropForFuncStr); I tried other ways of converting the property to an integer such as @Value("#{new int ('${my.prop.for.func}')}") but they gave other errors and this seemed like the easiest way. I am probably getting the NumberFormatException: Null error because myPropForFuncStr is null. I have always retrieved values from .properties file like this so why is it messing up right now?. If that isn't the problem, what else could give the NumberFormatException: Null error? A: Firstly Spring framework already handles the autoboxing for you. Which means that you can directly add the annotation to the int variable. @Value("${my.prop.for.func}") private Integer myPropForFunc; // Note that this needs to be an object and not a primitive data type. Now, coming to your issue, you may want to check if your class has been annotated with the @PropertySource annotation. If you are using Spring boot to initialize your application, then it should have automatically read your application.properties file and injected these properties to the fields appropriately. But if you are not, then you will need to annotate your class with @PropertySource annotation. Even if you were using Spring boot, your setup would not have worked since the @Value will be evaluated after the bean has been successfully initialized, but you are initializing the value of the myPropForFunc at the field itself. Here is an example which shows the usage of the annotation. https://www.mkyong.com/spring/spring-propertysources-example/ A: Spring initializes classes with their annotated attributes after instantiation. That means, the call "Integer.parseInt" will be called before spring can load the properties, because the class already has been initialized. You have several options to solve this: Write an void init method with the @PostConstruct annotation. In this method, all spring related informations are already loaded. Write an getter, that always parses to integer on call in runtime I think spring can also handle: @Value("${my.prop.for.func}") private Integer myPropForFuncInt;
{ "pile_set_name": "StackExchange" }
Q: Nothing is displayed on the screen after form submission I've looked and tried many of the solutions here and on other sites but I am still befuddled (still doing the PHP school thing, but something is eluding me). I have a page that a user can select multiple check boxes and it builds the data: <?php $username = $_POST['username']; $filename = "../files/Awards_$username.txt"; $award = $_POST['awardrec']; file_put_contents($filename, print_r($award, true), FILE_APPEND) ?> Simple enough. It writes the data as: Array ( [0] => Value1 [1] => Value2 [2] => Value3 [3] => Value4 [4] => Value5 [5] => Value6 ) But nothing I seem to do results in anything being displayed. No error messages; nothing, just a white page. Ultimately it's just a page that will read the data and display a graphic associated with the value. Where would a good article on this type of operation be? A: I am not sure what exactly you are trying to achieve but this should help at least a bit hopefully in the right direction : <?php // For test // $_POST['username'] = 'some_username'; // $_POST['awardrec'] = array( 'award_one' ,'award_two' ); if( ! isset( $_POST['username'] ) ) { echo 'username is not set'; exit; } $username = trim( $_POST['username'] ); if( $username == '' ) { echo 'username is empty'; exit; } $filename = "../files/Awards_$username.txt"; if( ! isset( $_POST['awardrec'] ) ) { echo 'awardrec is not set'; exit; } $award = $_POST['awardrec']; // Save the contents to file file_put_contents( $filename ,print_r( $award ,true ) ,FILE_APPEND ); // Display contents echo 'Username : ' ,$username ,'<br>'; echo 'Awards :' ,'<br>'; foreach( $award as $value ) { echo $value .'<br>'; }
{ "pile_set_name": "StackExchange" }
Q: Can't block AspiegelBot in htaccess or robots.txt I have issues with AspiegelBot crawling one of the sites on a server, this results in a lot of cores getting used up. I've been trying to block the bot in both in the sites htaccess with no sucess. The bot still constantly appears in my access.log 114.119.165.232 - - [20/Apr/2020:07:38:40 +0200] "GET /tillbehor.html?size=98%2C422%2C423%2C1129%2C1378 HTTP/1.1" 301 296 "-" "Mozilla/5.0 (Linux; Android 7.0;) AppleWebKit/537.36 (KHTML, like Gecko) Mobile Safari/537.36 (compatible; AspiegelBot)" Here is some of what I've tried: htaccess Options +FollowSymLinks RewriteEngine on RewriteCond %{HTTP_USER_AGENT} ^.(Mb2345Browser|AspiegelBot|LieBaoFast|MicroMessenger|zh-CN|Kinza|Mb2345Browser).$ [NC] RewriteRule .* - [F,L] robots.txt User-agent: * Allow: / Disallow: */shopby ####################################### ################ PAGES ################ ####################################### Disallow: /privacy-policy-cookie-restriction-mode/ Disallow: /terms/ ####################################### ############# Block Bots ############## ####################################### User-agent: MJ12bot Disallow: / User-agent: SemrushBot Disallow: / User-agent: SemrushBot-SA Disallow: / User-agent: rogerbot Disallow:/ User-agent: dotbot Disallow:/ User-agent: AhrefsBot Disallow: / User-agent: Alexibot Disallow: / User-agent: SurveyBot Disallow: / User-agent: Xenu's Disallow: / User-agent: Xenu's Link Sleuth 1.1c Disallow: / User-agent: AspiegelBot Disallow: / Am I missing something or writing something incorrectly? Ï'm kinda at a loss here. A: I posted this as a comment but seeing as it's what solved this for me I will add it as an answer. I managed to get the bot blocked by blocking the starting IP sequence in the htaccess file. It might not be optimal way to do it but it worked. Deny from 114.119.0.0/16
{ "pile_set_name": "StackExchange" }
Q: How to do multiclass classification for unlabeled data in python? I have a data with 20 different types (as a column), 10 out of 20 are useful information, I wanted to classify them into 10 different class using logistic regression, as a result I wanted to show the number of records in each class. Data is not labeled. 183820,9.17101300730551E+018,9,7,79,169,2017,10,17,6,3,0,1,1,0,0,0,0,0,0,637126.9861,5399201 183821,9.17101300712351E+018,9,7,72,147,2017,10,8,6,3,6,2,0,1,1,0,0,0,0,639046.3051,5363761. A: try the below reference: 1) A Robust Ensemble Approach to Learn From Positive and Unlabeled Data Using SVM Base Models http://arxiv.org/abs/1402.3144 (published in Neurocomputing) 2) Assessing binary classifiers using only positive and unlabeled data: http://arxiv.org/abs/1504.06837
{ "pile_set_name": "StackExchange" }
Q: Can anyone else use let statements at their Node.js REPL? Is it possible? It doesn't seem to work in my REPL, neither with nor without --harmony. What I'd really like to do is use for..of loops, but let seems a simpler thing to troubleshoot and is likely the same reason. Anyone know anything about the status of these? A: $ node --version v0.10.13 It was a bit cryptic, you'd think just --harmony would work, but you need to add in a use strict somewhere (which you can do at the command line): $ node --harmony --use-strict > var letTest = function () { ... let x = 31; ... if (true) { ..... let x = 71; // different variable ..... console.log(x); // 71 ..... } ... console.log(x); // 31 ... } undefined > letTest() 71 31 undefined > Much happy! However, I tried a simple of comprehension and it didn't work: [ square(x) for (x of [1,2,3,4,5]) ] With no luck. It looks like you may have to go past the current stable release to get all the harmony features.
{ "pile_set_name": "StackExchange" }
Q: Display Loading Icon or Loading Progress Bar using angularjs How to display the loading Icon or loading Progress bar using angularjs. I mean something like this which used in jquery $("body").addClass("loading");, $("body").removeClass("loading");, I saw some links for progress bar which is of like youtube loading bar but i don't want like that I want simple progress bar or loading iage or loading icon or loading bar which show bar moving from module to module, tabs to tabs. Is there any link or function which explain clearly how to use it. A: if you dont want to implement it yourself, below are few links. angular-spinner or angular-sham-spinner also read this BLOG which details how the spinner works with angularjs EDIT as per comments app.directive("spinner", function(){ return: { restrict: 'E', scope: {enable:"="}, template: <div class="spinner" ng-show="enable"><img src="content/spinner.gif"></div> } }); i havent tested the code but directive wont be more complex than this... A: View <div ng-show="loader.loading">Loading</div> Controller $scope.loader.loading = true; // false Add this also on top of your controller $scope.loader = { loading : false , }; Show and hide loading bar
{ "pile_set_name": "StackExchange" }
Q: What's stopping the nested fields_for in this simple_form_for from rendering? I have a model Quote which has_many Employees and Employees belongs_to Quote. I am trying to build a nested simple_form_for form to update both of these models in my new_quote view, despite trying many syntax variations I cannot see what i'm doing wrong. The simple_fields_for content does not even render in the browser, everything else does? Any help on what I'm doing wrong would be greatly apprecited: quotes_controller.rb class QuotesController < ApplicationController before_action :authenticate_user!, only: [ :new, :create, :edit, :update, :destroy ] def new @quote = Quote.new @quote.employees.build respond_to do |format| format.html format.xlsx { response.headers['Content-Disposition'] = 'attachment; filename="empee_data.xlsx"' } end def quote_params params.require(:quote).permit(:gla, :prev_cover, :co_name, :co_number, :postcode, :industry, :lives_overseas, :scheme_start_date, :payment_frequency, :commission_level) end end new.html.erb <div class='container'> <div class='row'> <h1>Complete the below to get a quote</h1> <%= render :partial => "new_quote"%> </div> </div> _new_quote.html.erb <%= simple_form_for @quote do |f| %> <div class='form-group col-md-6'> <%= f.input :gla, as: :boolean, label: "GLA" %> <%= f.input :prev_cover, as: :radio_buttons, collection: [['Yes', true], ['No', false]], readonly: nil, label: "Previous cover" %> <%= f.input :co_name, label: "Company name" %> <%= f.input :co_number, label: "Company number" %> <%= f.input :postcode %> </div> <div class='form-group col-md-6'> <%= f.input :lives_overseas, as: :radio_buttons, collection: [['Yes', true], ['No', false]], readonly: nil %> <%= f.input :industry, collection: Quote.industries.map { |k,v| [ k.humanize, k ] } %> <%= f.input :scheme_start_date %> <%= f.input :payment_frequency, collection: Quote.payment_frequencies.map { |k,v| [ k.humanize, k ] } %> <%= f.input :commission_level %> <% f.simple_fields_for :employees do |builder| %> <%= builder.input :first_name, label: "First name" %> <%= builder.input :last_name, label: "Last name" %> <%= builder.input :email, label: "Email" %> <%= builder.input :gender, collection: Employee.genders.map { |k,v| [ k.humanize, k ] } %> <%= builder.input :date_of_birth %> <%= builder.input :salary %> <% end %> <%= link_to 'Download as .xlsx', new_quote_path(format: :xlsx) %> </div> <%= f.submit "Get quote", class: 'btn btn-primary' %> <% end %> quote.rb class Quote < ApplicationRecord belongs_to :user has_many :employees, inverse_of: :quote accepts_nested_attributes_for :employees end employees.rb class Employee < ApplicationRecord belongs_to :quote end A: I mean that the fields_for element of the form doesn't show up, the rest of the form does, as if the fields_ for block didn't exist at all!? Any ideas? This is because of this line <% f.simple_fields_for :employees do |builder| %> which should be <%= f.simple_fields_for :employees do |builder| %> You are missing =
{ "pile_set_name": "StackExchange" }
Q: How update password with Spring Ldap template? I have a problem with changing password with Spring LDAP template. I don't use Spring security. I created application by example and i tried to write a new method which change a user password. My pojo: @Data @AllArgsConstructor @NoArgsConstructor @ToString(exclude = "uid") public class Person { private String uid; private String fullName; private String lastName; private String password; public Person(String uid, String fullName, String lastName) { super(); this.uid = uid; this.fullName = fullName; this.lastName = lastName; } } Repository with method: @Service public class PersonRepository implements BaseLdapNameAware { @Autowired private LdapTemplate ldapTemplate; private LdapName baseLdapPath; public void setBaseLdapPath(LdapName baseLdapPath) { this.baseLdapPath = baseLdapPath; } public Person findOne(String uid) { Name dn = LdapNameBuilder.newInstance(baseLdapPath).add("ou", "people").add("uid", uid).build(); return ldapTemplate.lookup(dn, new PersonContextMapper()); } public List<Person> findByName(String name) { LdapQuery q = query().where("objectclass").is("person").and("cn").whitespaceWildcardsLike(name); return ldapTemplate.search(q, new PersonContextMapper()); } public void update(Person p) { ldapTemplate.rebind(buildDn(p), null, buildAttributes(p)); } public void updateLastName(Person p) { Attribute attr = new BasicAttribute("sn", p.getLastName()); ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr); ldapTemplate.modifyAttributes(buildDn(p), new ModificationItem[] { item }); } public void updatePassword(Person p) { Attribute attr = new BasicAttribute("password", p.getPassword()); ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr); ldapTemplate.modifyAttributes(buildDn(p), new ModificationItem[] { item }); } private Name buildDn(Person p) { return LdapNameBuilder.newInstance(baseLdapPath).add("ou", "people").add("uid", p.getUid()).build(); } private Attributes buildAttributes(Person p) { Attributes attrs = new BasicAttributes(); BasicAttribute ocAttr = new BasicAttribute("objectclass"); ocAttr.add("top"); ocAttr.add("person"); attrs.put(ocAttr); attrs.put("ou", "people"); attrs.put("uid", p.getUid()); attrs.put("cn", p.getFullName()); attrs.put("sn", p.getLastName()); attrs.put("password", p.getPassword()); return attrs; } private static class PersonContextMapper extends AbstractContextMapper<Person> { public Person doMapFromContext(DirContextOperations context) { Person person = new Person(); person.setFullName(context.getStringAttribute("cn")); person.setLastName(context.getStringAttribute("sn")); person.setUid(context.getStringAttribute("uid")); return person; } } } And after, when i try to update password with method "update" or "updatePassword" i will get a new exception. nested exception is org.springframework.ldap.InvalidAttributeValueException: 'password' has no values.; nested exception is javax.naming.directory.InvalidAttributeValueException: 'password' has no values.; remaining name 'uid=jahn,ou=people,dc=memorynotfound,dc=com' Caused by: javax.naming.directory.InvalidAttributeValueException: 'password' has no values. Please, help me with this method. How update that password? A: I think it's userPassword attrbute
{ "pile_set_name": "StackExchange" }
Q: Knockout class binding not working in a component I have created a knockout component and inside I am trying to bind a span element to a CSS class defined in a viewmodel. I normally used a class binding for this: <span data-bind="class: IconCssClass"></span> But for some reason, it does not work - it does not apply the class at all. However, when I use a css binding or attr binding, both work as expected: <span data-bind="attr: { 'class': IconCssClass }"></span> <span data-bind="css: IconCssClass"></span> Is it a knockout bug or am I missing something? Tried to google this out but it seems no-one else had encountered this issue. Here's a code snippet: // Register a simple component: ko.components.register('my-icon', { viewModel: function(params) { this.IconCssClass = ko.computed(function () { return "fas fa-edit"; // hardcoded to keep the example simple }, this) }, template: 'attr binding: <span data-bind="attr: { \'class\': IconCssClass }"></span> <br /> css binding: <span data-bind="css: IconCssClass"></span> <br /> class binding: <span data-bind="class: IconCssClass"></span>' }); // Apply bindings ko.applyBindings(); <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <body> <p> The component: </p> <my-icon></my-icon> </body> A: I found the reason so will answer my own question. The class binding is new in knockout, it did not appear until knockout 3.5.0-beta. This is unfortunately not mentioned in knockout documentation where css and class bindings are described together with no information that one of them is pretty new: https://knockoutjs.com/documentation/css-binding.html You must look into release notes to find this info: The new class binding supports dynamic class strings. This allows you to use the css and class bindings together to support both methods of setting CSS classes. Full knockout 3.5.0-beta release notes: https://github.com/knockout/knockout/releases/tag/v3.5.0-beta
{ "pile_set_name": "StackExchange" }
Q: SQL Group By Column With Latest Date I Have a table of following column name where we have date multiple bin have multiple date with 30-sec date slot I need to pull data based on last entry respect to bin Suppose 1990025I have 100 entry for today only when I query I need last enter record when I do get find All Entry group by bin am not getting a proper result For base one Single Bin Query select * from battery_data where tcu_date_ist =( SELECT MAX(tcu_date_ist) FROM battery_data WHERE bin='1990051I'); How i get All Bin Group Query And i also Need latitude, longitude Column in it SELECT latitude, longitude, bin,created_date FROM public.battery_data group by latitude, longitude, bin ,created_date ORDER BY created_date DESC Output Am getting like 12.966 77.5841 "1990025I" "2019-11-18 12:53:11.984+05:30" 13.0007 77.6128 "1990074I" "2019-11-18 12:53:11.522+05:30" 12.9567 77.68 "1990088I" "2019-11-18 12:53:10.663+05:30" 12.9714 77.58 "1990123I" "2019-11-18 12:53:10.45+05:30" 0 0 "1980020I" "2019-11-18 12:53:10.151+05:30" 12.966 77.5841 "1990025I" "2019-11-18 12:53:10.001+05:30" 13.0952 77.5949 "M10299171990132I" "2019-11-18 12:53:09.922+05:30" 12.9936 77.7478 "1990006I" "2019-11-18 12:53:08.718+05:30" A: SELECT DISTINCT ON (bin) * FROM public.battery_data ORDER BY bin, created_date DESC
{ "pile_set_name": "StackExchange" }
Q: Using a Break or Return instead of setting a Flag I was reading on this page about setting a flag in a loop and using it later. Most of the answers agreed that it's a code smell. One of the answers suggested refactoring the code by putting the loop into a method and the boolean and break become a return instead. The second answer suggests that using the break means your loop has two possible exit points, and if your code becomes more complex, it might be harder to detect and introduce bugs. Question: By the logic of the second answer isn't using a return statement also a code smell? Using a return you introduce a second way to exit the loop. A: From my point of view, if the method/function is long or complex enough to make an additional exit point confusing, then the smell is probably the length/complexity, not the return itself. Take for instance exceptions: they are (exceptional) exit points as well, but nobody would defer them until later. My personal preference is to exit the routine as soon as it's done and has a final result available. That lets me focus only on "the other path" from that point on. Otherwise, I'd have rather long and deeply nested "elses" just to cover those paths. But then this is very relative. It depends on how readable is the language, the function/method, and even other factors such as cleaning up (as mentioned by CandiedOrange in their reply). I just happen to see as more important the overall method clarity and simplicity over the multiple exit points. A: setting a flag in a loop and using it later ... is called the dirty flag or dirty bit pattern. It is perfectly possible to do this without it being a code smell. Multiple returns are a code smell in languages like c where having one exit point provides one place to clean up used resources. Using break here can help. It's worth considering this even when their are no used resources here because some day I may have to add some and I'd appreciate it if you didn't force me to redo tons of code. However, if you're in a language that has finally blocks you can use more than one return freely because I can easily add a finally block later. Early returns can make the code more readable. A popular style is to deal with special cases 1st and put the more typical case at the end. Baring any other problems dirty flag and multiple return can work and often switching between them is just a micro optimization that wouldn't provide a big O improvement. Choose what makes the code most readable. Code smells are nothing but the start of looking into improving the code. No book or blog post knows your real situation better then you and you team.
{ "pile_set_name": "StackExchange" }
Q: Google Drive SDK iOS9 I'm having trouble building my project against the Drive SDK for iOS9. It has mostly to do with a lot of methods being deprecated and certain header files not being found. Any tips on how to make the SDK work with iOS9? Also, will the SDK be updated for iOS9 anytime soon? A: Okay I seem to have got it working by using https://github.com/google/google-api-objectivec-client via Cocoapods. That solved all the issues I had.
{ "pile_set_name": "StackExchange" }
Q: Screenshot [ctypes.windll CreateDCFromHandle] I am creating a screenshot module using only pure python (ctypes), no big lib like win32, wx, QT, ... It has to manage multi-screens (what PIL and Pillow cannot). Where I am blocking is when calling CreateDCFromHandle, ctypes.windll.gdi32 does not know this function. I looked at win32 source code to being inspired, but useless. As said in comment, this function does not exist in the MSDN, so what changes should I apply to take in consideration other screens? This is the code which works for the primary monitor, but not for others: source code. It is blocking at the line 35. I tried a lot of combinations, looking for answers here and on others websites. But nothing functional for me ... It is just a screenshot! Do you have clues? Thanks in advance :) Edit, I found my mystake! This is the code that works: srcdc = ctypes.windll.user32.GetWindowDC(0) memdc = ctypes.windll.gdi32.CreateCompatibleDC(srcdc) bmp = ctypes.windll.gdi32.CreateCompatibleBitmap(srcdc, width, height) ctypes.windll.gdi32.SelectObject(memdc, bmp) ctypes.windll.gdi32.BitBlt(memdc, 0, 0, width, height, srcdc, left, top, SRCCOPY) bmp_header = pack('LHHHH', calcsize('LHHHH'), width, height, 1, 24) c_bmp_header = c_buffer(bmp_header) c_bits = c_buffer(' ' * (height * ((width * 3 + 3) & -4))) got_bits = ctypes.windll.gdi32.GetDIBits(memdc, bmp, 0, height, c_bits, c_bmp_header, DIB_RGB_COLORS) # Here, got_bits should be equal to height to tell you all goes well. French article with full explanations : Windows : capture d'écran A: Edit, I found my mystake! This is the code that works: srcdc = ctypes.windll.user32.GetWindowDC(0) memdc = ctypes.windll.gdi32.CreateCompatibleDC(srcdc) bmp = ctypes.windll.gdi32.CreateCompatibleBitmap(srcdc, width, height) ctypes.windll.gdi32.SelectObject(memdc, bmp) ctypes.windll.gdi32.BitBlt(memdc, 0, 0, width, height, srcdc, left, top, SRCCOPY) bmp_header = pack('LHHHH', calcsize('LHHHH'), width, height, 1, 24) c_bmp_header = c_buffer(bmp_header) c_bits = c_buffer(' ' * (height * ((width * 3 + 3) & -4))) got_bits = ctypes.windll.gdi32.GetDIBits( memdc, bmp, 0, height, c_bits, c_bmp_header, DIB_RGB_COLORS) # Here, got_bits should be equal to height to tell you all goes well.
{ "pile_set_name": "StackExchange" }
Q: docker-compose build freeze. no error I have docker-compose which has 7 services. here : version: '3' networks: default: external: name: rss-network volumes: shared-xml: services: mysql: image: db hostname: mysql build: context: ./Database dockerfile: Dockerfile container_name: mysql ports: - "3306:3306" - "33060:33060" webui: image: webui build: context: ./ dockerfile: Dockerfile.webui container_name: webui volumes: - shared-xml:/rss environment: - "ConnectionString={$cstring}" message.api: image: message build: context: ./ dockerfile: Dockerfile.message container_name: message volumes: - shared-xml:/rss environment: - "RabbitMq/Host={$host}" - "token={$token}" - "ConnectionString={$cstring}" links: - rabbit depends_on: - rabbit rabbit: image: rabbitmq:3.7.2-management hostname: rabbit container_name: rabbit ports: - "15672:15672" - "5671:5671" - "15671:15671" - "5672:5672" - "4369:4369" tracker: image: tracker build: context: ./ dockerfile: Dockerfile.tracker container_name: tracker environment: - "RabbitMq/Host={$host}" volumes: - shared-xml:/rss links: - rabbit - message.api environment: - "ConnectionString={$cstring}" depends_on: - mysql botCenter: image: botCenter build: context: ./ dockerfile: Dockerfile.botCenter container_name: botCenter environment: - "ConnectionString={cstring}" - "bot-token={$token}" feeding: image: feeder build: context: ./ dockerfile: Dockerfile.feeder container_name: feeder environment: - "RabbitMq/Host={$host}" volumes: - shared-xml:/rss links: - rabbit - message.api after docker-compose --verbose build freeze here ... Removing intermediate container b160ead77128 ---> 6cce30feb98f Successfully built 6cce30feb98f Successfully tagged webui:latest compose.cli.verbose_proxy.proxy_callable: docker close <- () compose.cli.verbose_proxy.proxy_callable: docker close -> None compose.service.build: Building mysql compose.cli.verbose_proxy.proxy_callable: docker build <- (path='C:\\Users\\TYılmaz\\Documents\\GitHub\\tracker\\RSSTracker\\Database', tag='db', rm=True, forcerm=False, pull=False, nocache=False, dockerfile='Dockerfile', cache_from=None, labels=None, buildargs={}, network_mode=None, target=None, shmsize=None, extra_hosts=None, container_limits={'memory': None}) docker.api.build._set_auth_headers: Looking for auth config docker.auth.resolve_authconfig: Using credentials store "wincred" docker.auth._resolve_authconfig_credstore: Looking for auth entry for 'https://index.docker.io/v1/' docker.auth.resolve_authconfig: Using credentials store "wincred" docker.auth._resolve_authconfig_credstore: Looking for auth entry for 'xmlparser.azurecr.io' docker.api.build._set_auth_headers: Sending auth config ('https://index.docker.io/v1/', 'xmlparser.azurecr.io') urllib3.connectionpool._make_request: http://localhost:None "POST /v1.25/build?t=db&q=False&nocache=False&rm=True&forcerm=False&pull=False&dockerfile=Dockerfile HTTP/1.1" 200 None compose.cli.verbose_proxy.proxy_callable: docker build -> <generator object APIClient._stream_helper at 0x000002463460F8E0> Step 1/6 : FROM mysql/mysql-server:latest ---> 02d081b9c73e Step 2/6 : env MYSQL_USER=userid ---> Using cache ---> e0e302b9630d Step 3/6 : env MYSQL_PASSWORD=pw ---> Using cache ---> 2e05dc0f1c59 Step 4/6 : env MYSQL_DATABASE=db ---> Using cache ---> 3184d46769f8 Step 5/6 : env MYSQL_RANDOM_ROOT_PASSWORD="w" ---> Using cache ---> 0aa292e5180f Step 6/6 : ADD my.sql /docker-entrypoint-initdb.d ---> Using cache ---> c7afd14beb7a Successfully built c7afd14beb7a Successfully tagged db:latest compose.cli.verbose_proxy.proxy_callable: docker close <- () compose.cli.verbose_proxy.proxy_callable: docker close -> None compose.service.build: Building botCenter compose.cli.verbose_proxy.proxy_callable: docker build <- (path='C:\\Users\\TYılmaz\\Documents\\GitHub\\tracker\\RSSTracker', tag='botCenter', rm=True, forcerm=False, pull=False, nocache=False, dockerfile='Dockerfile.botCenter', cache_from=None, labels=None, buildargs={}, network_mode=None, target=None, shmsize=None, extra_hosts=None, container_limits={'memory': None}) docker.api.build._set_auth_headers: Looking for auth config docker.auth.resolve_authconfig: Using credentials store "wincred" docker.auth._resolve_authconfig_credstore: Looking for auth entry for 'https://index.docker.io/v1/' docker.auth.resolve_authconfig: Using credentials store "wincred" docker.auth._resolve_authconfig_credstore: Looking for auth entry for 'xmlparser.azurecr.io' docker.api.build._set_auth_headers: Sending auth config ('https://index.docker.io/v1/', 'xmlparser.azurecr.io') docker-compose must continue building but something wrong and i don't understand what is wrong. when I building docker-compose, it freeze botCenter service. others services clearly work. here my botCenter service dockerfile : FROM microsoft/dotnet:2.0.0-sdk WORKDIR /app COPY *.sln ./ COPY ./BusinessLogic/*.csproj ./BusinessLogic/ COPY ./DataAccess/*.csproj ./DataAccess/ COPY ./Microservices/Message/*.csproj ./Microservices/Message/ COPY ./Microservices/Tracker/*.csproj ./Microservices/Tracker/ COPY ./Microservices/BotCenter/*.csproj ./Microservices/BotCenter/ COPY ./Microservices/Feeding/*.csproj ./Microservices/Feeding/ RUN dotnet restore COPY . . RUN dotnet publish -c Release -o out ENTRYPOINT ["dotnet", "Microservices/BotCenter//out/BotCenter.dll"] this docker file is built succesfully when I use this docker command : " docker build -f dockerfile -t test2021 . " help me please. A: Try adding any large files/folders to .dockerignore.
{ "pile_set_name": "StackExchange" }
Q: How to control a QFileDialog using Qt Test? I have 2 questions: How can I access a QFileDialog and write the path of a file in the "File name" field using the Qt Test module? I am asking that because I am developing some GUI tests in Qt and now I need to open a text file. The following code creates the QFileDialog and gets the file path: QString filePath = QFileDialog::getOpenFileName( this, "Open", "", tr("Text Files (*.txt)") ); If I am using a thread (QThread) to load the content in this text file, how can I wait for this thread to finish in my GUI tests? I know I can use the QTest::qSleep( milliseconds ); command, but I don't think it is a good practice in this case. If possible show me an example, please. A: Unfortunately, it's not possible using the Qt Test module. You have several choices: Add test hooks that bypass that dialog: you need to instrument your code to make it testable. You could e.g. set a testFile property on the object that asks for the file to a file path, if the property is set the object can skip asking for the file. const char k_testFile[] = "k_testFile"; MyClass::foo() { ... auto testFile = property(k_testFile); auto filePath = testFile.isNull() ? QFileDialog::getOpenFilePath(...) : testFile.toString(); ... } Use a non-native dialog and then it's a normal widget that you can test using Qt Test. Use platform-specific means of finding the native dialog and interacting with it. You'd need to implement it for every platform you intend to test on. You should be emitting a signal after the file has been loaded. The test can wait for that signal. You don't even need to use an explicit thread to load the file, an idiomatic way of asynchronously loading a file is: QString filePath = ...; QtConcurrent::run(ioPool, [this, filePath]{ auto data = MyLoader::load(filePath); emit haveFileData(data); }); The class where you invoke this code should have a haveFileData signal that some other code connects to and proceeds as desired. The ioPool is the thread pool used for I/O bound operations, it could be QThredPool::globalInstance() if you want the global pool to be the I/O pool. The CPU- and I/O-bound thread pools should be separate.
{ "pile_set_name": "StackExchange" }
Q: MySQL Syntax Error ASP.NET Good day! I'm trying to figure out what error I'm having. This is the error: And here is my code: protected void accountGridView_RowEditing(object sender, GridViewEditEventArgs e) { accountGridView.EditIndex = e.NewEditIndex; BindData(); } protected void accountGridView_RowUpdating(object sender, GridViewUpdateEventArgs e) { int user_id = int.Parse(accountGridView.DataKeys[e.RowIndex].Value.ToString()); TextBox txtUsername = (TextBox)accountGridView.Rows[e.RowIndex].FindControl("txtUsername"); UpdateUser(user_id, txtUsername.Text); accountGridView.EditIndex = -1; BindData(); } private void UpdateUser(int user_id, string username) { GlobalVars cn = new GlobalVars(); MySqlConnection connection = cn.connectDB(); connection.Open(); string query = "UPDATE user SET username = '" + username + " WHERE user_id = " + user_id + ""; MySqlCommand com = new MySqlCommand(query, connection); com.ExecuteNonQuery(); connection.Close(); } I can't get it to work. Am I missing something here? Any help would be much appreciated. A: The error message says that you have syntax errors in your query, so the other parts(connection) are working well as expected. Now consider the query:- if you debug the program and watch the query you can see that it may look like: UPDATE user SET username = 'asd WHERE user_id= usr_123 So what is wrong here is, You ware missed a ' after asd, need to give a pair of ' to specify the user_id(if it is a string), so the query may look like this: string query = "UPDATE user SET username = '" + username + "' WHERE user_id = '" + user_id + "'"; But i strongly recommend you to use Parameterized queries instead for this to avoid injection. The parameterised query will looks like : string query = "UPDATE user SET username = @username WHERE user_id = @user_id"; MySqlCommand com = new MySqlCommand(query, connection); com.Parameters.Add("@username", MySqlDbType.VarChar).Value = username; com.Parameters.Add("@user_id", MySqlDbType.VarChar).Value = user_id; // execute query here
{ "pile_set_name": "StackExchange" }
Q: Deploy APNS and GCM Services on Amazon AWS I have requirement to migrate all website content, web-services, database and push notification services (Apple and Google) to Amazon AWS. I am very much new with this, right now i have hosted all services on "GoDaddy" server - I have checked Amazon document for configuration - still I have few query regarding Push Notification. Question: We have developed Apple and Google Push Notification services (in php), now we are planning to migrate to Amazon AWS and my query is Do we need to use Amazon SNS service to add push notification support? Is Amazon SNS use is mandatory? Can we just deploy current push notification services (developed in php) to Amazon AWS server and send push notification? Any pointer or help on this would be greatly appreciated. Thank You. A: Given that you already have the majority of your app's core functionality running fine, you can move that to AWS EC2 directly. I guess there would be direct calls to the Apple & Google Push API calls. You can do this in the interest of the faster migration process. But however you can modify your existing logic to use Amazon-SNS and leverage your app for say further expansion like Windows Push, Andorid Push with Baidu etc. with very less impact on your code / app. Also by making Amazon-SNS do the push messages on your behalf, you are making your app a non-monolithic and going forward it would be helping you to be in the direct of scaling out more instances as well.
{ "pile_set_name": "StackExchange" }
Q: Storing Just the Time in Date Field I have a date field in my table for which I just want to store a time, so I'm doing the following: insert into mytable (timefield) values to_date("13:01:00", "hh24:mi:ss") However, when I query the table later on, I get the data showing up as "2013-08-01 13:01:00" How can I get rid of the "2013-08-01" portion? Thanks A: It depends how you want to represent a time. The trouble is that you're always going to have a date portion on the value. You could: to_char(my_not_really_a_date_column, 'hh24:mi:ss') Or you could extract the hours, minutes, and seconds individually as integers. extract (hour from my_not_really_a_date_column) Arguably a better method would have been to store the time as an interval: http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements001.htm#autoId18
{ "pile_set_name": "StackExchange" }
Q: Jedis filtering values in hmset I have some values in redis with this key structure key:1:abc -> votes -> 0 -> name -> John key:1:xyz -> votes -> 0 -> name -> Mary key:1:def -> votes -> 1 -> name -> Larry key:2:ijk -> votes -> 0 -> name -> apple Thats how my keyspace looks like. I am using hmset to store the stuff in redis. The "key:1" is a placeholder for identifying different users in a particular space and the part after "key:1" is a unique differentiator for each record in "key:1". I want to write some code for filtering out the data from redis for getting all the records who have number of votes set to 0. So the output of the jedis code should be something like key:1:abc -> votes -> 0 -> name -> John key:1:xyz -> votes -> 0 -> name -> Mary And Larry gets filtered out. I was looking into hmscan for solving this problem but am not sure what the command would look like. Any clue on what I can do to get that output? Also what do you think will be the time complexity to get this time? A: There's a couple of solutions for this, but the first that comes to mind is using an auxiliar structure. Every time you add a item to the HASH, you also add the name of the person to a SET: > SADD zerocount "Larry" (integer) 1 > SADD zerocount "Mary" (integer) 1 Whenever you want the list of names with zero count you can do an SSCAN (gives you pagination): > sscan zerocount 0 1) "0" 2) 1) "Mary" 2) "Larry" At the point where you would increment the value of Larry for example, you would remove that value from the set: > srem zerocount "Larry" 1 SADD is O(N) for each member added, in this case O(1). SSCAN is O(1) for each call, and SREM is O(1) for our scenario, in general O(N) where N is the number of members to be removed.
{ "pile_set_name": "StackExchange" }
Q: How to pass css for mobile device only In my web-application i want to pass difference css for mobile and computer. How can I do this? For example: If someone goto my site in computer then pass "screen.css" and when someone goto my site in mobile then pass difference css "screen1.css" How can I do this? Please Help me Thanks In Advance A: Figure out the mediaqueries. That's one possibility: http://css-tricks.com/css-media-queries/
{ "pile_set_name": "StackExchange" }
Q: What happens to temperature when pressure is constant in a cylindrical piston of saturated liquid ammonia? Let's say I have a cylindrical piston containing saturated liquid ammonia that is fitted with an electrical heater and a paddle wheel for stirring at an initial pressure and an initial temperature. When the gas expands, some of it evaporates to form a two phase, liquid-vapor solution inside the system. By the way, this process occurs at a constant pressure. My real question is, what happens to the temperature as the pressure is constant and the volume increases, also causing the specific volume to increase. I would assume the temperature increases, but when I look at the steam table, there is only one temperature corresponding to the pressure. For example, if the initial temperature is 20C, the initial pressure is 8.57bar. If that pressure is constant so the final pressure is 8.57bar, the steam table still says the temperature is 20C. Why is this? Because I was just looking at the ideal gas equation and it essentially says temperature increases as volume increases. But can I use this intuition with the ideal gas law when the system is 2 phase? A: If you only heat the cylinder, the ammonia boils, during which time The whole apparatus remains at saturation temperature, The vapor phase expands simply because more ammonia is being added to it, and Some of the heat-energy goes into pushing up the piston to accommodate more gas. After all the liquid has boiled off, the vapor heats up and expands as suggested by the ideal gas law. If you pull on the piston, the pressure drops and more liquid boils to restore the vapor pressure. But this takes energy out of the system and lowers its temperature, which makes a new equilibrium pressure and temperature lower than what you started with. If you pull on the piston after all the liquid has boiled, the vapor cools down further.
{ "pile_set_name": "StackExchange" }
Q: How to apply LabelEncoder to a Dask DataFrame to Encode the Categorical Values I have a Dask Data Frame which is made up of categorical data and numerical (float and int) data. When I try LabelEncode the categorical columns using the code below, I get error. from dask_ml.preprocessing import LabelEncoder, Categorizer encoder = LabelEncoder() encoded = encoder.fit_transform(train_X.values) The error as follows: ValueError: bad input shape (36862367, 15) Furthermore, I have tried a different approach to this: from sklearn.externals.joblib import parallel_backend with parallel_backend('dask'): from sklearn.pipeline import make_pipeline pipe = make_pipeline( Categorizer(), LabelEncoder()) pipe.fit(train_X) pipe.transform(train_X) And this give me a new error: TypeError: fit() takes 2 positional arguments but 3 were given Can any one please advise me on the right way to apply encoding to categorical data in Dask DataFrame. Thanks in advance. A: In scikit-learn / dask-ml, LabelEncoder transforms a 1-D input. So you would use it on a pandas / dask Series, not a DataFrame. >>> import dask.dataframe as dd >>> import pandas as pd >>> data = dd.from_pandas(pd.Series(['a', 'a', 'b'], dtype='category'), ... npartitions=2) >>> le.fit_transform(data) dask.array<values, shape=(nan,), dtype=int8, chunksize=(nan,)> >>> le.fit_transform(data).compute() array([0, 0, 1], dtype=int8) https://ml.dask.org/modules/api.html#dask_ml.preprocessing.LabelEncoder
{ "pile_set_name": "StackExchange" }
Q: Multiple search with Hpricot Had RTFM'ed, but still puzzled. I need to get objects which satisfy at least one of the property condition list. E.g. divs, where class == "marked" OR class = "data" OR class = "comments" For now emulated it manually, but is it possible with Hpricot standard abilities? A: doc = Hpricot.parse(..your data...) divs = doc.search("//div[@class='marked' or @class='data' or @class='comments']") The search takes an xpath expression, and xpath allows logical and and or operators. See this great answer about a similar question: XPATH Multiple Element Filters.
{ "pile_set_name": "StackExchange" }
Q: Live USB distros won't stay connected to internet After booting an Ubuntu 14.04 Live from USB I connect to the internet everything works great for a few seconds, then the internet stops working. It doesn't say it's disconnected or anything like that, but webpages won't load, sudo apt-get update can't connect. My internet access is fine, I am able to stream music on my tablet while using the Live USB. The installed OS on my laptop is Windows 10 and I have no problem accessing the internet from there. I tried this with both Live Ubuntu and Linux Mint ISO images loaded from an USB stick. For the initial couple seconds that the internet works after connecting to my WiFi, pages load quickly. If I connect to a second network, it works again for a few seconds, but then stops as before. EDIT: I've tried pinging my router's IP from the command line immediately after connecting, and the packages are received as expected for a short while, but then suddenly stop. The output of lspci -nn | grep Network: 0d:00.0 Network controller [0280]: Realtek Semiconductor Co., Ltd. RTL8188EE Wireless Network Adapter [10ec:8179] (rev 01) A: Your chipset from Realtek is badly supported, a quick Google search shows lots of similar problems under linux. A driver for your chipset is available on Github. You would need to download it and compile it yourself. Install build-essentials , download the zip archive and compile the driver in the rtl8188ee folder with the classic ./configure, make and sudo make install.
{ "pile_set_name": "StackExchange" }
Q: CALayer drawInContext vs addSublayer How can I use both of these in the same UIView correctly? I have one custom subclassed CALayer in which I draw a pattern within drawInContext I have a another in which I set an overlay PNG image as the contents. I have a third which is just a background. How do I overlay all 3 of these items? [self.layer addSublayer:bottomLayer]; // this line is the problem [squaresLayer drawInContext:viewContext]; [self.layer addSublayer:imgLayer]; The other 2 by themselves draw correctly if I do them in that order. No matter where I try and put bottomLayer, it always prevents squaresLayer from drawing. The reason I need 3 layers is I intend to animate the colors in the background and custom layers. The top layer is just a graphical overlay. A: Might as well paste the code in in case anyone is trying to animate stacked CALayers that have their own internal draw routines - (void)drawRect:(CGRect)rect { [imgLayer removeFromSuperlayer]; CGFloat w = [self.blockViewDelegate w]; CGFloat h = [self.blockViewDelegate h]; CGFloat wb = w/4; CGFloat hb = h/4; CGContextRef viewContext = UIGraphicsGetCurrentContext(); // Layers [bottomLayer sizes:wb :hb :1]; bottomLayer.frame = CGRectMake(0, 0, w, h); bottomLayer.opaque = NO; [topLayer sizes:wb :hb :0]; topLayer.frame = CGRectMake(0, 0, w, h); topLayer.opaque = NO; // Overlay imgLayer.frame = CGRectMake(0, 0, w, h); imgLayer.opaque = NO; imgLayer.opacity = 1.0f; UIImage *overlay = [self.blockViewDelegate image]; CGImageRef img = overlay.CGImage; imgLayer.contents = (id)img; // Add layers [bottomLayer drawInContext:viewContext]; [topLayer drawInContext:viewContext]; [self.layer addSublayer:imgLayer]; } blockViewDelegate is where I am storing width, height, and image information, it is the controller for this UIView. topLayer and bottomLayer are of a custom UIView subclass which draw some shapes in the view with variable color information. Later on in my animation I just run "setNeedsDisplay" repeatedly with a timer and this routine repeats, the layers re-draw using updated parameters.
{ "pile_set_name": "StackExchange" }
Q: Confusion with Japanese particle と in its multiple uses I have read about the different uses of the different particles in Japanese but often become confused as to how it should be translated in different sentences. In other words the actual intent of the particle sometimes looks ambigious to me. Now the particle と has atleast these four uses: 1) Quotation particle. It could be quoting a thought or speach. 2) Conditional particle. It expresses natural cause and effect statements only. 3) List of things. It can be used to express the word "and" for an exhaustive list of things. 4) With. Expressing relationship between two things, translated as "with" in English. Now often I get confused which way the particle is being used when we have sentence before and also after the particle. If I have just one sentence ending verb after the particle like 書く、思う、話す、言う、then I know we are quoting something. If we have list of nouns seperated by と then we know that here we have an exhaustive list of things. The problem is that while this is true, the particle is used in more complex situations as well with in paragraphs and then sometimes I cannot make out how to translate it. Could you elaborate on how to know for sure which way the particle is being used? A: You're 90% there. Let's take your list in order, shall we? 1. Quotation Particle As you noted, if you see it followed by a verb indicating expression (思う、言う、話す, etc.) then it's being used in this manner. 2. Conditional Particle The following sentence is the way I was taught to use this one: 秋になると、葉が落ちる。 "When autumn comes, the leaves fall." In other words, it's used to join two sentences and follows the dictionary form of the verb. What happens in the second sentence must be a direct consequence of what happened in the first. 3. List of Things A more exhaustive answer for this one can be found here, but the short of it is like you said, if you see several nouns grouped together by と then this is the most likely usage. Also, the last item in the group usually takes the same particle that a single item would have taken, on behalf of the group. So, for example: 八百屋【やおや】で林檎【りんご】とニンジンとピーマンを買【か】うつもり。 ピーマン takes を because if we were buying just one item we would have used を. と is then used between everything else on the list. 4. With Often with this usage one item is expressed independently using は, after which other people or items are added to the group. For example: 私は武【たけし】と東京へ行った。 "I went to Tokyo with Takeshi." I'm using と in this sentence to add Takeshi to the group. Additional people can also be included using XとYと..., but beyond two it can start sounding a bit ridiculous.
{ "pile_set_name": "StackExchange" }
Q: how to fetch data from firebase based on particular value in a node i have firebase data base as below projectmasternode | -DS | ----6125675 | | | ----department:"xyz" | --projectname:"sad" | -----72671273 | | | --department:"das" | --projectname:"iuh" | -----7863873 | --projectname:"sad" department :"xyz" now how to get departments data where department= "xyz". A: Your answer is right in the FB docs. Check here : https://www.firebase.com/docs/web/guide/retrieving-data.html#section-queries and take a look at orderByChild combined with another filter, like endAt. Something like var ref = new Firebase("myfirebase"); ref.orderByChild("department").endAt("xyz").on("child_added", function(snapshot) { console.log(snapshot.key()); }); Should do it.
{ "pile_set_name": "StackExchange" }
Q: Could we go to the meta sites more quickly? Currently when wanting to see the current questions in a meta site of a specific community (without using the URL because that would involve extra work), this means I have to: click in the site switcher item and after click on Meta (Total: 2 clicks); or go to my user profile, from there click on "Meta user" and then can click on home or questions (Total: 3 clicks) Not sure if I'm the only one but when it comes to switching the site I never/rarely use site switcher. Even if I would, that would still take 2 clicks. Could we have in nav-links one item with Meta/Non-meta? That would reduce Total clicks to 1 and give more incentive to go there. A: The left side bar is very underutilised and could easily have a link to Meta. This could be gated behind rep if there's a concern that new users will go there before they can post, or it could be a user preference to turn it on/off. A: As pointed out by curiousdannii, The left side bar is very underutilised and could easily have a link to Meta. Samuel Liew, nonetheless, was a couple of steps ahead and built a userscript named SearchbarNavImprovements that can do this as he says in the comments of this question adds links to child meta sites from the main in the left sidebar, and vice-versa from meta sites, among other features including advanced and saved search, and ability to search main, child metas, and MSE from the topbar. View the source code Install (Notice that Userscripts require Tampermonkey to be installed on your browser.) Ideally we wouldn't need such script and would be there by default.
{ "pile_set_name": "StackExchange" }
Q: Impact of adding 'nofollow' in relation to my own website I have a website that have links to companies, something like a community directory. Today I receive a complain of a company asking me to add rel="nofollow" to their URL. I don't have any advantage to give backlinks to these companies, but I never thought about adding rel="nofollow". Apparently this company made some SEO audit and they want some backlinks removed. Should I add rel="nofollow" to all companies websites in my platform? Could this affect my own SEO? It's my only concern. A: Using rel="nofollow" on external links will not increase or decrease your own rankings. It may however increase theirs or decrease. Generally when SEO link audits take place they look to remove low quality links. Low quality links generally consist of low quality page content or pages with many outbound links may also been seen as undesirable. Them requesting you to nofollow will likely be one of dozens or hundreds of sites with similar requests. Personally I would just remove the link entirely.
{ "pile_set_name": "StackExchange" }
Q: In iOS keychain app what does common name means? This is my first time creating a certificate. While creating the .CSR file I found the field common name but have no idea what this means. A: Here I got the common name in detail
{ "pile_set_name": "StackExchange" }
Q: Secure upload script I am creating a social network that let's users upload a profile picture. I just want to know if this is a secure way of doing it. Thanks. <?php include 'includes/header.php'; include 'includes/form_handlers/settings_handler.php'; //$userPic = ''; $date_time = date('Y-m-d_H-i-s'); if(!empty($userLoggedIn)) { if (isset($_FILES['fileToUpload'])) { $errors= array(); $file_name = $_FILES['fileToUpload']['name']; $file_size = $_FILES['fileToUpload']['size']; $width = 1500; $height = 1500; $file_tmp = $_FILES['fileToUpload']['tmp_name']; $file_type = $_FILES['fileToUpload']['type']; $tmp = explode('.',$_FILES['fileToUpload']['name']); $file_ext=strtolower (end ($tmp)); $extensions = array( "jpeg", "jpg", "png", "gif"); if(in_array($file_ext,$extensions)=== false){ $errors[]="extension not allowed, please choose a JPEG or PNG file."; } if ($file_size > 8097152) { $errors[] = 'File size must be 2 MB'; } if ($width > 1500 || $height > 1500) { echo"File is to large"; } if(!$errors) { $userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name; $profilePic = move_uploaded_file($file_tmp,"assets/images/profile_pics/" . $userPic); $file_path = "assets/images/profile_pics/" . $userPic; $stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?"); $stmt->bind_param('ss', $file_path, $username); $stmt->execute(); $stmt->close(); header('Location: settings.php'); exit(); } } } else { echo "Invalid Username"; } ?> A: This is my personal opinion, but I'd say the following: The code should be formatted, I'd personally look at PSR-12 as this standard should be followed when possible. move_uploaded_file doesn't protect against directory traversal. You should use basename on $_FILES['fileToUpload']['tmp_name'] and some other forms of validation Checking the file extension with if(in_array($file_ext,$extensions)=== false) doesn't prevent a user from uploading a malicious file they could for instance use a magic byte to trick the server into thinking it's a certain type of file. You should take a look at finfo and the first example on file upload You're create an array of errors, currently that's being checked in an if statement and is then thrown away. If you aren't planning on using it you might be better just returning out of the function early rather than continuing execution. Depending on how unique the filename should be you might want to use something like uniqid(mt_rand(), true) move_uploaded_file will replace a file if it already exists, you might want to check that this exists before you overwrite an existing file. Depending on your naming solution it's very unlikely to occur but under high load for long periods of time this could happen more often than you think. You're using UPDATE users SET profile_pic = ? WHERE username = ? I'd assume that this value exists in the database as the user needs to be logged in. However, if you aren't sure if the field exists or not (I haven't seen the database) I'd personally use: INSERT INTO users (profile_pic, username) VALUES (?,?) ON DUPLICATE KEY UPDATE profile_pic=?, username=? this will insert into the table if the row doesn't exist but will update it if it does. You've set a local variable called width and height and are comparing them to the same value. I assume this was meant to check the actual file dimensions? I hope this helps in some way :)
{ "pile_set_name": "StackExchange" }
Q: XML Text Formatting for XSL Transformation I hope my title does justice for the question. Please consider the following block of XML and sample block of XSL. <root> <level_one> My first line of text on level_one <level_two> My only line of text on level_two </level_two> My second line of text on level_one </level_one> </root> <xsl:template match="level_one"> <xsl:value-of select="text()"/> <br/> <xsl:apply-templates select="level_two"/> </xsl:template> <xsl:template match="level_two"> <xsl:value-of select="text()"/> <br/> </xsl:template> As it stands, the output (modified here for reading) when executing the above is My first line of text on level_one <br/> My only line of text on level_two <br/> I'm missing the second line of text on level_one. So I'm wondering two things. Is the XML valid? From what I know, the answwer is yes, but am I wrong? How can I modify the XSL in order to get the second line (or even more lines in my case than I've shown)? Thanks A: Is the XML valid? From what I know, the answwer is yes, but am I wrong? Yes your XML is valid. Also, contrary to a comment above, there is nothing wrong with having mixed content (text and elements mixed together) in XML. It all depends on context and how the XML is used. For example, it would be almost impossible to author technical manuals without mixed content. (A good example is reference elements mixed with text in paragraph elements.) How can I modify the XSL in order to get the second line (or even more lines in my case than I've shown)? I'm not sure exactly what you're trying to accomplish, but the reason you're not seeing the second line of text is because you're only matching the first line with the first <xsl:value-of select="text()"/>. I'm not sure if this would work on your full set of XML data, but you could replace both level_one and level_two templates with one template that matches all text(): <xsl:template match="text()"> <xsl:value-of select="."/> <br/> </xsl:template> This produces the following output: My first line of text on level_one <br/> My only line of text on level_two <br/> My second line of text on level_one <br/> You could also narrow the match down by specifying the level_one and level_two parents: <xsl:template match="level_one/text()|level_two/text()"> <xsl:value-of select="."/> <br/> </xsl:template> This produces the exact same output, but leaves any other text open for matching in other templates. Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: OneNote 2010 code cannot be properly pasted back into XAML Does anyone else experience this? If I want to paste code from OneNote2010 it does simply not work. Reproduction: Create any WPF app, copy the XAML into OneNote2010, copy it back -> Whitespace issues. Or use this sample: <Popup Placement="Center" IsOpen="{Binding Error, Converter={StaticResource StringBoolConverter}}" PopupAnimation="Slide"> <userControls:ErrorMessageControl></userControls:ErrorMessageControl> </Popup> After putting it into OneNote and copying it back it gets broken. I can't even paste it here as it never gets displayed. Pasting it in XAML creates messages like Error 1 " " is not valid in a name. MainWindow.xaml 94 Error 2 White space is missing. MainWindow.xaml 94 Seems like many whitespaces are odd for the editor. I've compared the pasted code in Notepad++ and displayed non printable characters and I do not to see any issues with the whitespaces. A: Set paste option to "Text Only" when pasting into OneNote. When pasting, open the menu and select "Text Only"; then open the menu again and set it as default paste. If the menu is not shown when pasting, go to File -> Options -> Advanced, then in "Editing" group make sure that "Show Paste Options button when content is pasted" is checked.
{ "pile_set_name": "StackExchange" }
Q: Creating a checkerboard using Ruby and "\n" not disappearing I feel as if I am close to a solution and have been tinkering around with this as a newb for some time. Why, for some reason, are my "\n"'s not disappearing when outputted for "next line" and the output has unneeded white space? Task: Write a function which takes one parameter representing the dimensions of a checkered board. The board will always be square, so 5 means you will need a 5x5 board. The dark squares will be represented by a unicode white square, while the light squares will be represented by a unicode black square (the opposite colors ensure the board doesn't look reversed on code wars' dark background). It should return a string of the board with a space in between each square and taking into account new lines. An even number should return a board that begins with a dark square. An odd number should return a board that begins with a light square. The input is expected to be a whole number that's at least two, and returns false otherwise (Nothing in Haskell). I am close, and here is what I have so far: def checkered_board(dimension) black = "\u25A1 " white = "\u25A0 " checkboard = nil checker_array = [] if dimension < 2 or dimension.is_a? String return false else count = dimension while count <= dimension && count > 0 if count % 2 == 0 checkboard = ("\u25A1 \u25A0" + "\n") checker_array << checkboard count -= 1 else checkboard = ("\u25A0 \u25A1" + "\n") checker_array << checkboard count -= 1 end end end checkboard = checker_array.join(" ") p checkboard end Here is the TDD specs: Test.assert_equals(checkered_board(0), false) Test.assert_equals(checkered_board(2), "\u25A1 \u25A0\n\u25A0 \u25A1") Note: Hidden specs demonstrate that it should respond with false if dimension is not an integer. .is_a? String and .is_a? Integer is not working for me too. Output appears like so, and is not appearing even: □ ■ ■ □ Thanks for any and all help :). A: Try changing: if dimension < 2 or dimension.is_a? String to if !dimension.is_a?(Integer) || dimension < 2 The left most test will be done first. At the moment, if dimension is a String, it is first compared with 2 - which will raise an error - before it is tested as to whether it is a String. You need to check the type of object before you compare it with another object. Also, I think the check should be whether dimension is not an Integer, rather than whether it is a String. For example, in your original code, what would happen if dimension was an Array?
{ "pile_set_name": "StackExchange" }
Q: $|f|^{\alpha}$ harmonic for $\alpha > 0$ Wikipedia claims that given a holomorphic function $f$ then $\log(|f(z)|)$ being subharmonic implies that the function $\varphi_{\alpha}(z) := |f(z)|^{\alpha}$ is subharmonic for every $\alpha > 0$. Why is this true? A: This is a special case of the following, applied to $|f(z)|^\alpha = \exp(\alpha \log (|f(z)|))$: If $v: D \to \Bbb R \cup \{ -\infty \}$ is subharmonic in the domain $D$ and $h: \Bbb R \to \Bbb R$ is increasing and convex, then $V = h \circ v$ is subharmonic in $D$. Remark: If $v(z_0) = -\infty$ then $V(z_0)$ is defined as $V(z_0) = \lim_{t \to -\infty} h(t) = \inf \{ h(t) \mid t \in \Bbb R \}$. Proof: This follows easily from Jensen's inequality for integrals: If $v(z_0) > -\infty$ and $\overline {B_r(z_0)} \subset D$ then $$ V(z_0) = h(v(z_0)) \le h \left(\frac{1}{2\pi r}\int_0^{2\pi} v(z_0 + re^{it}) \, dt \right) \\ \le \frac{1}{2\pi r}\int_0^{2\pi} h(v(z_0 + re^{it})) \, dt = \frac{1}{2\pi r}\int_0^{2\pi} V(z_0 + re^{it}) \, dt \, . $$ If $v(z_0) = -\infty$ then $V(z_0) \le V(z_0 + re^{it})$ and the integral inequality holds obviously.
{ "pile_set_name": "StackExchange" }
Q: Is AC compressor faulty if I can get cold air on lower temperature setting but not on higher setting (e.g. 20 and 23 celsius)? I'm having 2013 Ford Fiesta and I've noticed that when I set my AC to 23 C it doesn't blow cool air much, but when I lower the setting to 20/19 C then the cold air continually flows. Six months ago I serviced a car and they told me it's my thermostat but I didn't have time to leave the car for change so I postponed to another service. On last week's service (in the different service center) I asked the guys to check AC again and see what needs to be changed and they told me this time it's my compressor failing and I need to replace it. What I was able to read from internet, if AC compressor is failing I wouldn't be able to get cool air at any setting inside the car so I'm confused now as to what would be an actual problem. Could AC compressor work only partially and explanation from last week in the service center be plausible or would it really be just a thermostat problem? A: No, it's not faulty. If your system blows plenty of cold air then the compressor works. If it isn't coming on when unless the temperature is set low then something else is wrong, the thermostat is a likely culprit, but not the only possible one.
{ "pile_set_name": "StackExchange" }
Q: Rails 3 Observer -- looking to learn how to implement an Observer for multiple models I have the following Observer: class NewsFeedObserver < ActiveRecord::Observer observe :photo, :comment def after_create(record) end end What'd I'd like to learn how to do is add a SWITCH/IF statement in the after_create, so I know which model was created Something like: after_create(record) switch model_type case "photo" do some stuff case "comment" do some other stuff end Or easier to visualize: if record == 'Photo' How can I take record, and determine the model name? A: In a comment, I notice you found this works using record.class.name but that's not very idiomatic Ruby. The Ruby case statement uses === for comparison which will work perfectly for you if you implement it properly. class NewsFeedObserver < ActiveRecord::Observer observe :photo, :comment def after_create(record) case record when Photo # do photo stuff when Comment # do comment stuff else # do default stuff end end end This essentially converts to: if Photo === record # do photo stuff elsif Comment === record # do comment stuff else # do default stuff end I advise you to note the following: class Sample end s = Sample.new Foo === s # true uses Class#=== s === Foo # false uses Object#=== === is implemented differently in Class and Object
{ "pile_set_name": "StackExchange" }
Q: Finding Hamiltonian cycles in cubic planar graphs I have relatively small (40-80 nodes) cubic (3-regular) planar graphs, and I have to decide their Hamiltonicity. I am aware of the fact that this task is NP-complete, but I hope for asymptotically exponential time algorithms that are nevertheless very fast for the graph size I am interested in. A: 40 nodes seems doable. You're choosing 40 of 60 edges to include. Let's try a depth-first search. To start, pick a vertex V. You will need to exclude exactly one of its 3 incident edges. Try these 3 possibilities one at a time. When you choose an edge to exclude, you are forcing the inclusion of 4 edges. After this, we'll call the vertices of the excluded edge "used". If you could repeat this process 10 times, you would have chosen all 40 edges, searching only 3^10 (59049) possibilities. Of course, you'll run out of "isolated" vertices after enough edges have been determined. But, we now have an idea for an algorithm. At each step, try picking a vertex with the fewest "used" neighbors. Actually, picking a vertex with 2 used neighbors is best, since the used edge is forced. I'm not sure if picking a vertex with 1 or 0 used neighbors is the next best. Try both ways! (And 3 used neighbors indicates a failed search) When we're done picking edges, check if they form a single cycle. Do you have a few sample graphs? I might try a simple implementation.
{ "pile_set_name": "StackExchange" }
Q: RED HAT BRMS installation error on EAP7 While installing 'jboss-brms-6.3.0.GA-installer.jar' on my EAP 7.0 ('jboss-eap-7.0.0-installer.jar') I am getting error in BRMS installation wizard as below. The provided EAP installation is missing the following required files: \standalone\configuration\standalone-osgi.xml 'standalone-osgi.xml' didn't come along with EAP 7 installation. Can anyone please help me? A: From the Red Hat BRMS 6 supported configurations : Application Containers Version JBoss EAP 6.4.(7+) I understand 6.4.(7+) as any server of the 6.4.X branch, starting from the 6.4.7. To my understanding, this does exclude EAP 7. There is a chance BRMS can be installed on EAP 7, but probably with the manual ZIP install, not with the automatic installer. Moreover, if you are trying to install BRMS, you probably have enterprise support from Red Hat. Running BRMS 6.3 on EAP 7 may exclude your support.
{ "pile_set_name": "StackExchange" }
Q: Using table information inside a WHERE clause So some background for this question. I have created a query that looks checks SCCM for every piece of software given single machine. So I have my statement: SELECT Programs.DisplayName, Programs.Publisher etc.. FROM my_db WHERE machine_Name = @computername Above is just an example of what I do. The point is that this query returns a list of software that is in SCCM for that single machine. Now my issue is that I have been given a massive list of machines to find software for. What I want to do is to somehow make a single query that will take in a list of machines and return results for every name in that list (which is like 300 lines). I am trying to see if it is possible to make a table with the list of machine names and use that table in my WHERE clause. Is this something that cannot be done in SQL alone or is this possible? I know you can use comma delimited arrays in WHERE clauses but there are so many names that I am not sure that will work. A: Storing the list of machines in a separate table is a good idea. While it is doable to build a long list of values that you can use on the right side of the IN operator, using a reference table is more scalable (lists are limited to a few thousands elements), and easier to maintain. Once you have this table created and filled, you can just join it with your table. Assuming that your reference table is called machines and has a column named machine, this would look like: SELECT p.* FROM programs p INNER JOIN machines m ON m.machine_name = p.machine_name
{ "pile_set_name": "StackExchange" }
Q: Creating a trigger on Oracle 11g I need to create a trigger that updates another table whenever the trigger table has an insert into command, or an after insert trigger. I need to pull the id that's being inserted into the table in order to update the other table, how do I go about doing so? In case that's confusing, another attempt at my question: Table 1 has an after insert trigger. Said trigger updates table 2 based on one of the id values being inserted into table 1. How do I pull said id value from table 1 in the trigger? A: You can use :new in your trigger to reference the values being inserted, for example create or replace trigger <trigger_name> after insert on <table_name> for each row declare l_id number; begin select :new.id into l_id from dual; -- now l_id contains the id of the inserted row, do what you want with it end; Don't take the example to literally; you don't have to first select :new.id into a variable, you can use it directly in SQL inside the trigger. I did it here just for illustration. Take a look at the Oracle docs: Coding Triggers However, you might also want to take a look at some arguments why you should think twice if you really need to put your logic into triggers: The Trouble with Triggers
{ "pile_set_name": "StackExchange" }
Q: How to print out value of a variable during debugging in Netbeans? In xcode during debugging, it is possible to print out the value of a variable at that particular stage. I was just wondering if there is a similar function in Netbeans? If not, what Java IDE does? A: Have you tried the following methods: Put a breakpoint on the line where you want to see the value. Run the debugger on that file and switch to the 'Variables' tab (Window > Debugger > Variables). This will display the values of your variables at that breakpoint. These rows might also have children rows - eg. If there was an array named myArray, you can click on the + symbol next to it to see each elements value. You can also evaluate conditionals by going 'Debug' > 'Evaluate Expression'. For example, in the iterating loop over 'myArray', you could enter myArray[2] == 5 and click the green -> arrow to evaluate this. If the value of that element was 5, this would indicate the expression, type (boolean in this example), and output of that test. OR Insert your breakpoint wherever you'd like to monitor the variable. Right-click the breakpoint and select 'Breakpoint > Properties'. Set the suspend to "No thread (continue)". Then just fill in the corresponding field with the format of {=<variable name>}. So, for example entering: "myVar value @ L30 is: {=myVar}" will output "myVar value @ L30 is: 1" to the debugger console. You shouldn't need to recompile. Just run under the debugger and switch to the console output.
{ "pile_set_name": "StackExchange" }
Q: Jquery mobile 1.2 landscape issue jumpy/resize before page transistion Could someone help me please. I'm developing a webapp with jquery mobile (1.2) and everything looks okay in portrait mode (iphone/ipad) also page transitions. But when I turn to landscape, just before the page transition from one to the other the font size gets bigger and the view resizes. A: Try adding "initial-scale=1" in the viewport meta tag. <meta name="viewport" content="width=device-width,initial-scale=1"> I had exact the same issue and it solved my case.
{ "pile_set_name": "StackExchange" }
Q: Ruby return in yield block called from a method with ensure def foo puts "in foo" s = yield puts "s = #{s}" return 2 ensure puts "in ensure" return 1 end def bar foo do puts "in bar block" return 3 end return 4 end [36] pry(main)> r = bar in foo in bar block in ensure => 4 I'd expect r = 3 but it turns out it is r = 4. If I remove the ensure code, r = 3 is expected. Why is it? def foo puts "in foo" s = yield puts "s = #{s}" return 2 end r = bar in foo in bar block => 3 A: It's a Ruby's feature of "unwinding the stack" from blocks. How your return works step by step: You return 3 from bar block. return_value = 3 and Ruby marks that it is a return value from block, so it should unwind the stack and return 3 from parent function. It would not return to foo at all if there was no ensure section. It is very important difference between returning from functions and from blocks. But Ruby always executes ensure, and there is one more return in ensure section of foo. After return 1 in ensure section of foo, return_value is 1. It is not a value from block, so Ruby "forgets" about previous return 3 and forgets to return it from bar. It returns 1 from foo and 4 from bar. Moreover, if you write next 3 instead of return 3 in the block - it will return to foo after yield and execute puts "s = #{s}"; return 2 even without the ensure block. This is a magical Ruby feature for iterators and enumerators.
{ "pile_set_name": "StackExchange" }
Q: CSS animation with JQuery addClass. Run only once using true or false I have a CSS animation that I want to run when the page is in view on the browser. I am doing this using a true or false function to get the position (called "posish"). I can run it once when the page comes into view, or when posish is true (13900), but I also want to run it again once when posish becomes false. My problem is, if I set it up so true & false both run the animation, the animation runs continuously as you scroll, whereas I only want it to run once for each instance until the instance changes to the opposite. Also, I have two classes running the same animation, so I can add and remove. I hope this makes sense! Here is my code: if (posish(13900)) { $('.shadow').removeClass('shrink-2'); $('.shadow').addClass('shrink-1'); } else { $('.shadow').removeClass('shrink-1'); $('.shadow').addClass('shrink-2'); } Here is the code for the posish function function posish(pos) { pos-=19; if (scrolled-viewport/4 < pos) { return false; } else if (scrolled > pos+viewport/2) { return true; } else { return (scrolled-viewport/4-pos)/(viewport/4); } } Please let me know if you need anymore information. Thanks for any help! A: Ok, here's a Fiddle I made to demo some code: http://jsfiddle.net/3XbTG/ If you run it and look at the console, you'll see that it successfully tests the two posish values. I think what you want to do is see if the "pos" is greater than 1/4 of the total viewport height (the height + the scroll position - 19) The first problem is you want to get the values of viewport and scrolled each time you run the function. The second problem is you should only run a single test, and return the value from that. Your function was returning booleans or numbers, which is confusing. function posish(pos) { var viewport = $(window).height(); var scrolled = $('body').scrollTop(); var totalHeight = scrolled + viewport - 19; return (totalHeight / 4 < pos); }
{ "pile_set_name": "StackExchange" }
Q: How to set R.string.resource_name in this case I have a code like this if(POS>=5){ Toast.makeText(SubActivity.this,R.string.last,Toast.LENGTH_SHORT).show(); }else { POS += 1; fillDetails(POS); } I want to get this "5" in if(POS>=5) from strings.xml In strings.xml I have <string name="lastarticle">5</string> I have tried these if(POS>=R.string.lastaricle) if(POS>=getString(R.string.lastaricle)) if(POS>=getResources().getString(R.string.mess_1)) if(POS>=this.getString(R.string.resource_name)) if(POS>=@string/lastarticle) but none of them worked. I think I miss something but I don't know what it is? A: You should convert that string to int and then compare it with POS: if(POS >= Integer.parseInt(getString(R.string.lastaricle))){ Toast.makeText(SubActivity.this, R.string.last, Toast.LENGTH_SHORT).show(); } else { POS += 1; fillDetails(POS); }
{ "pile_set_name": "StackExchange" }
Q: Highlighting current selected textfield - best approach I am trying to achieve an effect like this on mobile (ios + android): http://i.imgur.com/6zaTdRd.png Where the currently selected textfield has a blue tinted icon + underlining So my framework lacks any support for grey scaling a bitmap image of any sort so I need to swap between two images to achieve this effect. My current implementation looks like this: Please note this for the Titanium Alloy MVC framework but I'm guessing the basic logic should be similar. I listen for blur/focus events to toggle current image $.firstNameField.addEventListener('focus', function(e){ swapImages($.firstNameField.getParent()); }); $.lastNameField.addEventListener('focus', function(e){ swapImages($.lastNameField.getParent()); }); and then I swap images like so: /** * Swaps between the images (..._0 and ..._1) of an ImageView nested in a TableRow * ..._0 Greyscale image * ..._0 Colour image * @param e current TableViewRow */ function swapImages(e){ var imagePathSplit = (e.children[0].image).split('_'); var newImagePath = null; if(imagePathSplit[1] == "0.png") newImagePath = imagePathSplit[0] + "_1.png"; else newImagePath = imagePathSplit[0] + "_0.png"; e.children[0].image = newImagePath; return; } This doesn't look that great especially since I need a lot more fields with this functionality, I also want to implement tabbing (using Return key = NEXT) between the fields which will further balloon to increase 1 more event listener per field. How would something like this be done ideally? I can think of one way of just creating the fields in code in array form which should help simplify matters (no more looking too far for Parent/Children, but that would still end up using quite a bit of listeners for switching right? EDIT: Forgot to add how I have the textFields setup: <TableView id="paypalTable"> <TableViewSection> <TableViewRow id="firstNameView" class="tableRow"> <ImageView id="firstNameIcon" class="textFieldIcon"/> <TextField id="firstNameField" class="textField"/> </TableViewRow> A: I tried something similar in one of my projects. Although I had an Alloy project I had to use a classic approach to get my desired behaviour. In my controller: var textFields = []; var yourTextFieldsArray = []; for (var i = 0; i < yourTextFieldsArray; i++) { //Set the selected state to false initially. Maybe you need another command for it. textFieldIsSelected[i] = false; //create your new view textFields[i] = Ti.UI.createView({ top : topValues[i], width : Titanium.UI.FILL, height : height, id : i + 1, touchEnabled : true }); textFields[i].addEventListener('click', function(e) { //Check the source id if (e.source.id - 1 > -1) { //use your function swapImages(e.source.id). Notice the slightly different parameter since you do not need the complete event. swapImages(e.source.id); } } function swapImages(id){ //Check the the path variable as you did var imagePathSplit = (textFields[i-1].image).split('_'); var newImagePath = null; if(imagePathSplit[1] == "0.png") newImagePath = imagePathSplit[0] + "_1.png"; else newImagePath = imagePathSplit[0] + "_0.png"; textFields[i-1].image = newImagePath; } This approach lets you use the same event listener for every property. Please notice that my ids start at 1 and not at 0. This is because I had to implement such a behaviour for images and ImageViews do not accept id=0. My guess is that TextViews don't do it either so you should stick with it. Further notice that you need to decrement the id to get the corresponding object in the textFields Array. Otherwise you would get an out of bounds error. You should create one more event listener for your NEXT event. Implement it in the same way as the first eventListener. Maybe the code is not perfect because I wrote it from my memory. If there are any questions left feel free to ask in the comments.
{ "pile_set_name": "StackExchange" }
Q: How to extract information from Google Click ID (gclid)? There is some way to get campaign information like source, name, medium, keyword, etc from the given gclid parameter that came in the query string? A: Take a look at CLICK_PERFORMANCE_REPORT, it has plenty of information about a click, referenced by ClickId. The easiest way to access report data is via AdWords scripts. A: Probably not. It contains a timestamp, and two other integers. However we couldn't match those other integers to any campaign, adword, or keyword ID that we found in the Adwords backend. We've written about how gclids are encoded (and how you can go about decoding them for yourself).
{ "pile_set_name": "StackExchange" }
Q: Array literals in VHDL We have defined a vector as A: in std_logic_vector(7 downto 0); when assigning a literal to this vector such as A <= {'1', '0', '0', '1'}; will this expession populate the vector positions of 7,6,5 & 4 or positions of 3,2,1 & 0 The idea is a vector of bits which we can sign extend to an 8 bit integer but it will only currently work if the latter is true. A: Invalid syntax here. If you want to keep the various bits as a list you can make the assignment: A(3 downto 0) <= (3 => '1', 2=> '0', 1=> '0', 0=> '1') ; Bonus sign extension: A <= (2=> '0', 1=> '0', 0=> '1', others => '1') ;
{ "pile_set_name": "StackExchange" }
Q: Get the consecutive months for a given date range In my table I have dates as follows 08/08/2011 29/08/2011 30/08/2011 31/08/2011 12/09/2011 13/09/2011 23/10/2011 24/10/2011 25/10/2011 26/10/2011 Now I need the records to be displayed based on a given date range eg: if from date is 8/08/2011 and to date is 20/10/2011 then the data should come as below 29/08/2011 Aug 30/08/2011 Aug 31/08/2011 Aug 12/09/2011 Sept 13/09/2011 Sept A: BAsed on the data you provided CREATE TABLE notes (`datecreated` varchar(10)) ; INSERT INTO notes (`datecreated`) VALUES ('08/08/2011'), ('29/08/2011'), ('30/08/2011'), ('31/08/2011'), ('12/09/2011'), ('13/09/2011'), ('23/10/2011'), ('24/10/2011'), ('25/10/2011'), ('26/10/2011') ; You can use Select STR_TO_DATE(datecreated, '%d/%c/%Y') datecreated , DATE_FORMAT(STR_TO_DATE(datecreated, '%d/%c/%Y'),'%b') monthname From notes WHERE STR_TO_DATE(datecreated, '%d/%c/%Y') BETWEEN '2011-08-29' AND '2011-09-13'; the result is datecreated monthname 2011-08-29 Aug 2011-08-30 Aug 2011-08-31 Aug 2011-09-12 Sep 2011-09-13 Sep The biggest Problem is that your date is not in a Format that mysql can import. But with STR_TO_DATE you can solve this. the date Problems as you can see keeps bugging mysql. The WHERE clause uses BETWEEN to select the wanted date frame this has to be in the right date format. Of course you have to adept it to your tablebane and columnname DBfiddle Example
{ "pile_set_name": "StackExchange" }
Q: Predicate Logic - Is my answer correct? Construct a predicate logic proof equivalent to the following natural language argument. “No athletes are bookworms. Carol is a bookworm. Therefore Carol is not an athlete.” Could someone please help with my symbols? Ans. Let $A(x)$ mean that $x$ is an athlete. Let $B(x)$ mean that $x$ is a bookworm. Let Constant $C$ denote Carol $\forall x, A(x) \implies \neg B(x), B(C), \neg A(C)$. Is this correct? I know we will have to apply rules down after this—but is my beginning even correct? I sometimes feel that my starting statement should be $\forall x, A(x) \implies \neg B(x), B(C), \iff \neg A(C)$. Is this correct? Thanks so much!!! A: The task here, it seems to me, is to construct a proof, that validates the argument you are given in natural language. So you need premises, and you need a desired conclusion. So your premises are $$\begin{align} & (1)\quad\forall x, A(x) \Rightarrow \lnot B(x) \\ \\ & (2) \quad B(C)\end{align}$$ Then, from these premises, you need to construct a proof which leads you to the conclusion: $$\therefore \lnot A(C)$$ For example, you'd need to use universal instantiation on premise $(1)$ to infer $$(3) \quad A(C) \Rightarrow \lnot B(C)$$ Now you can simply use $(3)$ and premise $(2)$ to conclude, by modus tollens, that therefore, $(4)\quad \lnot A(C)$, though you might want to add a fourth step, double negation on premise $(2)$ to get $\lnot \lnot B(C)$, and then employ modus tollens to arrive at the conclusion. This argument form, as given in natural language, is called a syllogism, which has the form:$$\begin{align} \quad & \text{No A is a B}\\ \\ \quad & \text{C is a B}\\ & \hline \\ \\ \therefore & \text{C is not an A}\end{align}$$
{ "pile_set_name": "StackExchange" }
Q: grunt watch not compiling all sass files despite being "watched" Basically at the moment I have 2 issues that I can't seem to find answers to. When I save my main styles.scss, sass compiles ok, though when I save either _globals.scss or any other scss file, grunt watch seems to detect the change, but it doesn't compile! What would I need to do to rectify this? My 2nd issue is when I have got a scss file in a directory within the scss folder for example: pages/_gallery.scss (which is being imported in the main styles.scss), grunt watch doesn't see it, I understand this is because of probably because of my cwd path, though how do I make this more generic? Here is my Gruntfile.js: module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { scripts: { files: ['public/resources/site/js/*.js'], tasks: ['newer:jshint', 'newer:uglify:dist'], options: { spawn: false, livereload: true, }, }, sass: { files: ['public/resources/site/scss/*.scss'], tasks: ['newer:sass:app'], options: { livereload: true } }, php:{ files: ['public/index.php'], options: { livereload: true } } }, sass: { app: { files: [{ expand: true, cwd: 'public/resources/site/scss/', src: ['*.scss'], dest: 'public/resources/site/css/', ext: '.css' }] }, options: { sourceMap: true, outputStyle: 'compressed' } }, uglify: { dist: { options: { sourceMap: true, mangle: true }, files: [{ expand: true, cwd: 'public/resources/site/js/', src: ['*.js'], dest: 'public/resources/site/js/', ext: '.min.js' }] } }, jshint: { options: { force: true }, files: [ 'public/resources/site/js/*.js', '!public/resources/site/js/*.min.js' ] }, notify: { watch: { options: { title: 'Tasks Complete', message: 'Files Processed & Compiled', } } } }); // Load tasks grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-imagemin'); grunt.loadNpmTasks('grunt-newer'); grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-notify'); // Default task(s). grunt.registerTask('default', []); grunt.task.run('notify_hooks'); }; A: To make subdirectories work you need a globbing pattern; 'public/resources/site/scss/**/*.scss' I think that your watch task is flawed due to newer. Watch detects a change to _globals, but the sass task knows only to compile the main styles.scss. However, newer sees that this file has not changed, so it does not run the step. Try removing newer from the watch task list.
{ "pile_set_name": "StackExchange" }
Q: What type of code do I use to let unlimited inputs? #include <iostream> int main { cin>>i; cout<<i; } How do I change the cin part so that it lets in any amount of inputs separated by a space? A: try this: int num; cout << "Enter numbers separated by a space" << endl; do { cin >> num; /* process num or use array or std::vector to store num for later use */ }while (true); This might answer your query.
{ "pile_set_name": "StackExchange" }
Q: how to create a facebook look alike gallery with css and jquery? i want to add to my website a photo gallery in a restricted width ( the height does not matter ) . I tried a lot of types of galleries, but all of them were depending on the width or height of the photo. Then i thought "why not use a same patern like facebook?", but my problem is that i do not know how. I do not need such a complex gallery like facebook, but i need the autoresize clickable photos ( the little thumbnails which appear to present a photo in a album ) and when you click them to expand to their normal size , with left and right arrows. Can you help me succed my goal? If something is not clear, ask me in the comment section, i do not speak very well english. PS: all my site is based on html, jquery and css. A: You can use the below CSS property to re-scale an image although as stated above, this won't do your loading times any favours and a server side script would be a more preferable option if you're willing to delve into PHP. If not, feel free to create a div with a set width and height along with the below property and a background image and that should work. The downside is that you may not be able to link the div without use of onClick/JavaScript. background-size: 100%; As for jQuery, you can use the http://fancybox.net lightbox plugin to allow your users to click on a 'thumbnail', view the full-sized image and use the arrow keys to switch between images.
{ "pile_set_name": "StackExchange" }
Q: Selection in NavigationLink is not working I have the following code for my iPad app: struct ContentView: View { @State var selectionIndex: Int? = nil var body: some View { NavigationView { VStack { ForEach(0..<5) { tag in NavigationLink("Link \(tag)", destination: DetailView(name: "View \(tag)"), tag: tag, selection: self.$selectionIndex) .foregroundColor((self.selectionIndex ?? 0) == tag ? Color.red : Color.black) } } } } } struct DetailView: View { var name: String var body: some View { Text(self.name) } } Pressing the links works perfectly and also it changes the DetailView. I try to highlight the selected button, therefore I save the selectionIndex. Unfortunately the selectionIndex sometimes resets to 0. What am I doing wrong? EDIT Wrapping the NavigationLink into a List shows the problematic better, as the List has it's own selection (this selection stays, but my own var selectionIndex resets). NavigationView { List { ForEach(0..<5) { tag in NavigationLink("Link \(tag)", destination: DetailView(name: "View \(tag)"), tag: tag, selection: self.$selectionIndex) .foregroundColor((self.selectionIndex ?? 0) == tag ? Color.red : Color.black) } } } See this screen: A: Well, this of course looks like a bug, but they do what they documented - show destination of selected tag, no more. Anyway, probably worth submitting feedback. Here is a working workaround. Tested with Xcode 11.4. @State var selectionIndex: Int? = nil @State var highlighted: Int? = nil // << explicit !! var body: some View { NavigationView { VStack { ForEach(0..<5) { tag in NavigationLink("Link \(tag)", destination: PadDetailView(name: "View \(tag)").onAppear { self.highlighted = tag }, tag: tag, selection: self.$selectionIndex) .foregroundColor(self.highlighted == tag ? Color.red : Color.black) } } } }
{ "pile_set_name": "StackExchange" }
Q: How can I justify a gnome samurai in Faerûn? A new player wants to join a game I'm running. The campaign is set in Thesk in Faerûn, and the player wants to play a gnome samurai. I'd like to find a way to make this work, but I keep running into problems: Samurai must belong to a lord or else they aren't samurai. Gnomes in Kara-Tur are often bureaucrats and rarely end up as warriors. Nonhuman samurai are rare. A lord might retain a gnomish samurai for the sake of political grandstanding, but such a character would rarely be sent to represent the lord's interests alone. A samurai lord in Kara-Tur would have little reason to send agents to Thesk. The Golden Way runs through that region, but I don't see how to leverage that. How can the samurai keep in contact with his lord? Scrolls of the spell sending would work, but would take a big chunk out of the funds for a low-level character. I have a few solutions of my own, but they're mostly along the lines of "a wizard did it," unsatisfying, and create new problems: A polymorph any object spell could have turned a human samurai into a gnome samurai, but the lord's resources should be able to remove the effect. A portal could extend the lord's claimed territory into new regions, but such a portal would be a drain on the court's resources. My group is pretty good at finding unusual solutions, and I feel like this character's backstory could be an endless source of unusual problems if done well, so I don't want to just tell the player to pick something else. The rest of the party is comprised of level 1–3 characters with more mundane backstories. With these problems—and the problems raised by the solutions to these problems—in mind, how can I fit this new player's gnome samurai into my campaign? While 3.5 material is acceptable, original Third Edition material is preferred. A: With limits, allow exceptional player-characters Based on the question, it sounds like you're reluctant to have the PC and elements of the PC's background be exceptional. This DM gently recommends allowing PCs and their backgrounds to be exceptional, especially if doing so A) means the PC receives no mechanical benefit, and B) makes the campaign more interesting. Let me address the points the question raises in order: "Samurai must belong to a lord, or they aren't samurai." Beyond a really basic plot hook like the lord simply saying, "I will send emissaries to the far corners of the world for I am powerful and curious yet forced to occupy the throne. You, my favored and amusing gnome samurai, wander in that direction for 10 years then return to me," there are a variety of accidents—magical and mundane—that could strand the PC so that he's guided by his lord's ideals rather than his lord's presence. Sure, neither is 100% bushido, but they're accommodations for a particular PC. "Gnomes in Kara-Tur are often bureaucrats and rarely end up in warrior roles." Certainly, it's rare, but it's fortunate that the PC was born into one of two heretofore unknown small (yeah, small) clans of gnome samurai. (Of course there're two such clans: they're bitter rivals so the DM can create Gnomeo and Juliet scenarios. Feel free to add a secret third clan of outcast gnome ronin and ninja.) "A samurai would rarely be sent to represent the lord's interests alone." Indeed, but maybe this one was. Maybe, like the Texas Rangers, because there was just one issue to handle, oversee, or investigate in Thesk, the lord—who has, not incidentally, vastly overestimated the gnome samurai's abilities—only sent one samurai. Alternatively, the lord sent an entire delegation there—including the gnome samurai—to establish an embassy or further a trade relationship and they're still there. You could go so far as to give Thesk a Kara-Tur enclave in which the embassy sits. "The Golden Way runs through that region, but I don't see how to leverage that." Fortunately, right now, you don't have to. The lord is setting up shop or sending emissaries to where the Way begins in an effort to outdo his rivals, corner a market, control trade, or whatever. To what precise end? Maybe the lord doesn't even know yet, but as the campaign progresses, you'll find a reason then so will the lord. "How can the samurai keep in contact with his lord?" If none of his superiors are present in Thesk, the Golden Way provides an obvious solution. The PC sends daily, weekly, or monthly letters reporting what he thinks is important to his lord and receives replies at the DM's leisure. "A polymorph spell could explain the unusual race, but the resources of a court should be able to remove the effect." You're correct that court resources should be able to dispel a polymorph any object spell that has a permanent duration, for example. However, a reincarnate spell is much harder to reverse, and a unique magical effect is impossible to reverse except under circumstances that only adventure can reveal. "A portal could extend the lord's claimed territory into new regions, but such a portal would be a drain on the court's resources." A one-way portal isn't as expensive, and a one-way 1/day (or 1/week or 1/year) portal while still not inexpensive is affordable, and a captured or discovered portal is nominally free. However, a portal between Shou Lung and Thesk essentially eliminates the Golden Way, a source of profit for many. The campaign implications are tremendous. That's a great plot. With all that this DM would still have two fears: The player's suggested a goofball PC yet the DM's accidentally taking the suggestion seriously. Confirm that the player's serious about his gnome samurai and inform him that his vision can be realized without going the whole Don Quixote route. See that the player doesn't distance himself from the suggestion once he realizes that this will happen and that the player'll have his gnome samurai… and all the baggage that comes with that. An intricate background is developed for the gnome samurai, but during the first adventure the gnome samurai is killed by an orc with a spear. This DM suggests trying to keep the gnome samurai's background light on details until the PC's of a high enough level to matter. (This DM likes level 6.) Until that point—like at levels 1 through 5—, in a traditional campaign death by bad die rolls can totally just happen, and it's usually economically unsound—for the remaining PCs and the players on a meta level—to devote at those levels resources toward bringing back the dead; players usually just make new PCs. Keep in mind, though, that, above all, the DM needs to enjoy the campaign that the players are helping create with their unique PCs. A campaign really does need to satisfy the DM, too. The DM must enjoy managing that shared narrative, and if a PC's background requires so much accommodation that the narrative won't be enjoyable for you to manage, be firm and tell the player that his PC just doesn't fit and to pitch another idea. Note: The Oriental Adventures samurai is an acceptable character class in campaigns in which the fighter is an acceptable character class, but the 3.5 revision of the samurai class is almost universally considered so terrible as to be nearly unplayable… in most cases about equal to or a little worse than the NPC class expert. (Also see this question). Unless other PCs are a similar power level as the samurai, this DM recommends that a player interested in a PC samurai have his PC follow a samurai-like code and fight in a samurai-like fashion but pick a class that's more versatile and interesting than either the OA or 3.5 samurai, like, for example, crusader or warblade. A: Historically accurate samurai are much different than what the American and Hollywood stereotype would have you believe. Samurai was a conferred title and a set of commitments represented by a binding oath of loyalty, not a set of training, martial arts, tools, weapons, or skills. It could be granted and revoked. One of the most common distinctions of the title was that it was the equivalent of a license to carry weapons in public and a license to use weapons legally and lethally upon social classes lower than oneself with few to no legal repercussions. What this means in D&D terms is that both versions of the samurai class are completely inaccurate and worthless, insofar as representing what a samurai actually was. The question then becomes is the player desirous of playing one of those classes for some reason, or is the desire to play a samurai concept? If it is the former, then HeyICanChan's answer has you well covered, but if it is the latter, then I have a few additional comments in addition to the excellent ones already given. Real historically verified samurai cover a vast range of behaviors and archetypes. There are samurai who are famous for sneaking into a castle and burning the place down, or assassinating key figures. There are samurai who are famous for their horseback riding skills and those who lacked. There are those who were famous for archery skills, others for swordsmanship, and yet others famous for marksmanship (yes, guns). There were some that were politically and socially strong, yet weak in martial prowess. There were those who were experts at torture, those that performed acts of rape and murder, who plundered and pillaged enough to make a pirate blush, and those who sought to better the lives of their peasants and were just (even by Western views). Some were artisans, and others were known for cunning or wisdom. There are documented cases of a samurai testing a new blade upon a nearby peasant, and if it didn't cleanly cut the person in two, attacking the blade smith or refusing to pay. There are even a few stories of some who would actually swallow stones in the hope of breaking the samurai's blade. What then is a samurai? The key component of "being a samurai" was the oath of loyalty. This oath was an oath of absolute loyalty to a lord, to a degree that most Westerners would find uncomfortable. This oath basically placed the lord at the level of a God, and the samurai swore to obey each and every command, up to and including any morally or ethically repugnant whim the lord may take into their head, not excepting the death of loved ones or of self. Hesitation in executing any command was often interpreted as disloyalty. In fact, this was one of the main conflicts between the versions of Christianity that arrived in early Japan and the lords of those eras - loyalty to a God was supplanting loyalty to the lords, so they saw it as a threat, and massacred thousands in an attempt to genocide any and all Christians in Japan. This was not entirely one sided as the specific sects that were trying to convert the Japanese used many morally and ethically dubious methods that were frankly against Christian teachings. Yet it was not entirely black and white. There were ways for a samurai to remove his oath from a lord in publicly acknowledged ways, though death was often the result, unless the samurai could escape, or the lord let them go for some reason. In fact the were many occasions where spies who were deliberately sent into the camps of enemy lords, pretended loyalty until the opportune moment. The histories also have records of great betrayals or loyalty upheld in the face of overwhelming odds. Japan's famous ninja were all originally samurai, some of whom declined seppuku after losing a battle (often interpreted as failing to complete a lord's order which might result in the lord ordering the death of the entire family as well as the samurai). Even to this day, among the three families that claim direct descent from the ninja clans, it is indicated that among the traditional martial arts taught by ninja, a number were originally specific to samurai. Having given this very brief and incomplete overview of samurai in history, the conclusion I would like to emphasize is that almost any base class or prestige could be used to represent the skillset of a samurai, as they were very flexible and diverse in reality. The key factor would be the binding oath, which should ideally be role played, rather than merely represented by rules mechanics. No mention of samurai can be made without mentioning honor. The codes of honor common to the Asian regions are foriegn to western ways of thinking and distinctly do not align with traditional concepts of chivalry. For example, there's the very important matter of face, which is challenging for those not raised with the concept, and a source of many conflicts and misunderstandings between East and West. Face is a combination of reputation, status, honor, manners and courtesy both outgoing and incoming, and a few other more difficult concepts. Also, an important point of note are the Ronin, wanderers without a lord. Some were because the lord had died, some because they had betrayed their lord for reasons possibly just or possibly selfish, while others had yet to find a master and were searching for a lord worthy of their loyalty. Some were considered without honor, while others were glorified due to their honorable choices. As such, it is important to develop the characters personal code of honor and rules of face. It doesn't have to be true to the traditional Asian interpretation of honor and face. Something the player will have fun with and perhaps feel challenged with is good enough. This code determines what the character is and isn't willing to do, and what sort of lord they are looking for. Thus, the pre-lord Ronin version of a samurai concept might fit best for your player's character: a masterless samurai searching for a lord worthy of his or her blade and skills. This could also explain why he or she is so far off the beaten path. Disclaimer: I have lived in Japan, speak Japanese, have studied Japanese history with an emphasis on samurai and ninja, and I've even become a student of ninjutsu under two authorized teachers. So while I will not claim to be an authority figure or source I do have a better idea than most of what I'm talking about. ^^
{ "pile_set_name": "StackExchange" }
Q: how to segue from 2nd button on MKannotation? I have added a left button to my MKAnnotation. I want it to show this as well as the right button and images I have set below. This code below is showing both buttons but only recognizing the right button click to my segue for NewEntry. How can specify the calloutAccessoryControl to recognize the left button tapped, as well as the right button tapped, and add the additional segue from the left button to 'left detail' for my LeftButtonDetailViewController? Here is my code: //MARK: - MKMapview Delegate extension MapViewController: MKMapViewDelegate { func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { guard let subtitle = annotation.subtitle! else { return nil } if (annotation is SpecimenAnnotation) { if let annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(subtitle) { return annotationView } else { let currentAnnotation = annotation as! SpecimenAnnotation let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: subtitle) switch subtitle { case "Uncategorized": annotationView.image = UIImage(named: "IconUncategorized") case "Documentaries": annotationView.image = UIImage(named: "IconDocumentaries") default: annotationView.image = UIImage(named: "IconUncategorized") } annotationView.enabled = true annotationView.canShowCallout = true let detailDisclosure1 = UIButton(type: UIButtonType.DetailDisclosure) let detailDisclosure2 = UIButton(type: UIButtonType.InfoDark) annotationView.rightCalloutAccessoryView = detailDisclosure1 annotationView.leftCalloutAccessoryView = detailDisclosure2 if currentAnnotation.title == "Empty" { annotationView.draggable = true } return annotationView } } return nil } func mapView(mapView: MKMapView, didAddAnnotationViews views: [MKAnnotationView]) { for annotationView in views { if (annotationView.annotation is SpecimenAnnotation) { annotationView.transform = CGAffineTransformMakeTranslation(0, -500) UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveLinear, animations: { annotationView.transform = CGAffineTransformMakeTranslation(0, 0) }, completion: nil) } } } func mapView(mapView: MKMapView, annotationView: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if let specimenAnnotation = annotationView.annotation as? SpecimenAnnotation { performSegueWithIdentifier("NewEntry", sender: specimenAnnotation) } } func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, didChangeDragState newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) { if newState == .Ending { view.dragState = .None } } } A: You can compare the accessory to the left and right accessories, to see which was selected: func mapView(mapView: MKMapView, annotationView: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if let specimenAnnotation = annotationView.annotation as? SpecimenAnnotation { if control == annotationView.leftCalloutAccessoryView { // left } else if control == annotationView.rightCalloutAccessoryView { // right } else { fatalError("Unknown accessory") } } }
{ "pile_set_name": "StackExchange" }
Q: Adding a row to Abstract JTable model I am trying to add a row to my JTable, I am using an abstract method which is shown below. I am currently taking data from a List to setValueAt my JTable. Does anyone have any idea on how to add a row to this without changing the types of columnNames and data? Using a method called addRows that is. I have looked around but no other questions on here solved my problem. class MyTableModel extends AbstractTableModel { public String[] columnNames = {"A","B","C","D","E"}; public Object[][] data = { {"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)}, {"John", "Doe", "Rowing", new Integer(3), new Boolean(true)}, {"Sue", "Black", "Knitting", new Integer(2), new Boolean(false)}, {"Jane", "White", "Speed reading", new Integer(20), new Boolean(true)}, {"Joe", "Brown", "Pool", new Integer(10), new Boolean(false)} }; public void removeRow(int row) { Object [][]newData=new Object[data.length+1][data[0].length]; for(int i=0;i<newData.length;i++){ for(int j=0;j<data[0].length;j++){ newData[i][j]=data[i+1][j]; } } data=new Object[newData.length][columnNames.length]; data=newData; fireTableRowsDeleted(row, row); } public int getColumnCount() { return columnNames.length; } public int getRowCount() { return data.length; } public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { return data[row][col]; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public boolean isCellEditable(int row, int col) { return col > 2; } public void setValueAt(Object value, int row, int col) { data[row][col] = value; fireTableCellUpdated(row, col); } } A: The following method adds a row at the end: public void addRow(Object[] newRow) { data = Arrays.copyOf(data, data.length+1); data[data.length-1] = newRow; fireTableRowsInserted(data.length-1, data.length-1); } Use it like this: model.addRow(new Object[]{"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)} );
{ "pile_set_name": "StackExchange" }
Q: how to add custom taxonomies value from fronted I am building a template of fronted post. i want add custom taxonomies value from fronted in adding post from fronted how can i do that A: You can add taxonomy term (value) using following WordPress function: <?php wp_insert_term( $term, $taxonomy, $args = array() ); ?> For more info on function and its parameters https://codex.wordpress.org/Function_Reference/wp_insert_term
{ "pile_set_name": "StackExchange" }
Q: Clever ways to update LU factorization for ridge regression Ridge regression can be posed as minimizing the following objective function (over $x$): $$\frac{1}{2} \lVert Ax - b \lVert_2^2 ~+ \frac{\lambda}{2} \lVert x \lVert_2^2 $$ Which has a closed form solution: $$x = (A^TA + \lambda I)^{-1} A^T b $$ Let's say we want to solve this problem for several different values of $b$. Then its a good idea to cache the LU decomposition of $A^TA + \lambda I$. In MATLAB I think this translates to: [L,U] = factor(A'*A + lambda*I) x1 = L \ U \ A'*b1 x2 = L \ U \ A'*b2 % etc... Here's my question: if $\lambda$ is updated after several solves, is there a simple/efficient way of updating $L$ and $U$? Or do I have to completely redo the LU factorization? A: What is the size of your $A$ matrix? Is $A$ sparse? Does $A$ have some other special structure? How many values of $\lambda$ do you want to try? Normally, you'd use the Cholesky factorization of $A^{T}A+\lambda I$ rather than the LU factorization since $A^{T}A+\lambda I$ is symmetric and positive definite. However, updating the Cholesky or LU factorization of a matrix after a full rank diagonal update is not easy in practice (low rank updates are a different matter.) One alternative is to do the computation of the regularized solutions using the SVD of $A$. There's a simple formula for the Tikhonov regularized solution in terms of the SVD so that you only have to compute the SVD of $A$ once. This is a reasonable way to go for small sized problems (e.g. $A$ has no more than a few thousand rows/columns.) You could also use the eigenvalue decomposition of $A^{T}A$ to do this instead of the SVD of $A$. For large problems, especially where $A$ is sparse, iterative methods are typically used. You can solve the problem with explicit regularization as a linear least squares problem (hint: work from largest to smallest values of the parameter $\lambda$ and use the previous solution as the starting point for each new value of $\lambda$.) A more common approach is to use an iteration such as the Landweber iteration or CGLS that will give you an implicitly regularized solution when you stop the iterations before full convergence.
{ "pile_set_name": "StackExchange" }
Q: Swagger models Option[Int] to Object while Option[String] is modelled correctly as string I have the following case class @ApiModel("StationResponse") case class StationResponse (id: Option[String], @ApiModelProperty(dataType = "double", required = false) longitude: Option[Double]) The longitude field is modelled as "Object" instead of "double" I tried to override the dataType with @ApiModelProperty but no luck. Thanks for your comments. I am using Swagger 1.3.12 with Scala 2.11.6 A: I solved the issue by adding @field annotation along with ApiModelProperty like below: @ApiModel("StationResponse") case class StationResponse (id: Option[String], @(ApiModelProperty@field)(dataType = "double", required = false) longitude: Option[Double])
{ "pile_set_name": "StackExchange" }
Q: C# .NET preventing an object to dispose what it shouldn't I work on a big project and a problem occurred: Let's say I have a database loaded to memory, which stores widely-used data. But I must manage if the data is NOT loaded to memory, so I have to download it, then dispose it when I'm done. But I can make a mistake very easily: I can dispose the database as I had loaded it manually. I want to prevent myself from disposing the database even if I call the Dispose() method on the DB. I came up with the idea of tracking who can dispose the DB. Of course the only one allowed to do this is the one who created the database instance. Example of the problem, documented: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DisposePrevention { /// <summary> /// A bottle containing alcoholics /// </summary> class Bottle:IDisposable { private static int Id = 0; private int localId; public Bottle() { this.localId = Bottle.Id++; } public void Dispose() { //do the trick. } public override string ToString() { return "Bottle - " + this.localId.ToString(); } } /// <summary> /// A shelf storing bottles /// </summary> class Shelf : IDisposable { public List<Bottle> Content; public void Fill() { if (this.Content == null) { this.Content = new List<Bottle>(); } for (int i = 0; i < 5; i++) { this.Content.Add(new Bottle()); } } public void Dispose() { if (this.Content == null) { return; } foreach (Bottle b in this.Content) { b.Dispose(); } } } /// <summary> /// A bartender serving drinks /// </summary> class Bartender : IDisposable // very simplified. { public List<Shelf> Shelves; public Bartender() { this.Shelves = new List<Shelf>(); for (int i = 0; i < 3; i++) { Shelf s = new Shelf(); s.Fill(); this.Shelves.Add(s); } } public void Dispose() { if (this.Shelves != null) { foreach (Shelf actualShelf in this.Shelves) { if ((actualShelf == null) || actualShelf.Content == null) { continue; } foreach (Bottle bottleItem in actualShelf.Content) { bottleItem.Dispose(); // We can call this, because Content is public, but we shouldn't. } actualShelf.Dispose(); } this.Shelves.Clear(); } } /// <summary> /// What can we drink, Sir? /// </summary> public void Print() { Console.WriteLine("------------------"); if (this.Shelves != null) { foreach (Shelf actualShelf in this.Shelves) { if ((actualShelf == null) || actualShelf.Content == null) { continue; } foreach (Bottle bottleItem in actualShelf.Content) { Console.WriteLine(bottleItem.ToString()); } } } Console.WriteLine("------------------"); } /// <summary> /// Two bartenders can use the same source of drinks. /// </summary> /// <param name="list"></param> internal void AttachShelves(List<Shelf> list) { this.Shelves = list; } /// <summary> /// The boss can fire him, so he no longer gets access to the drinks. /// </summary> internal void DetachShelves() { this.Shelves = null; } } class Program { static void Main(string[] args) { Bartender john = new Bartender(); Bartender steven = new Bartender(); steven.AttachShelves(john.Shelves); Console.WriteLine("John:"); john.Print(); Console.WriteLine("Steven"); steven.Print(); Console.WriteLine(""); Console.WriteLine("Calling Dispose."); Console.WriteLine(""); john.Dispose(); // we kick John. But at this point, we should've called "john.DetachShelves();" Console.WriteLine("John"); john.Print(); Console.WriteLine("Steven"); steven.Print(); // Steven is sad. We should not allow John to dispose the alcoholics. Console.ReadLine(); } } } Results: John: ------------------ Bottle - 0 Bottle - 1 Bottle - 2 Bottle - 3 Bottle - 4 Bottle - 5 Bottle - 6 Bottle - 7 Bottle - 8 Bottle - 9 Bottle - 10 Bottle - 11 Bottle - 12 Bottle - 13 Bottle - 14 ------------------ Steven ------------------ Bottle - 0 Bottle - 1 Bottle - 2 Bottle - 3 Bottle - 4 Bottle - 5 Bottle - 6 Bottle - 7 Bottle - 8 Bottle - 9 Bottle - 10 Bottle - 11 Bottle - 12 Bottle - 13 Bottle - 14 ------------------ Calling Dispose. John ------------------ ------------------ Steven ------------------ ------------------ I can't use pinned GCHandle-s, to prevent leaks (reference is kept to the object which prevents GC to collect) Generally, I can't count on the Garbage Collector. I must dispose everything I create and GC only collects rarely. The solution with the least modification is the best. I can't use unsafe code... (it's a WPF and Silverlight project) Idea: I may write a wrapper, but the referencing problem still occurs. Question: I want to prevent John from being able to call Dispose() on the Shelves. Is there a "best practice" to do this? Thanks in advance! Edit: wrapper /// <summary> /// A shelf storing bottles /// </summary> class ShelfWrapped : IDisposable { public List<Bottle> Content; public void Fill() { if (this.Content == null) { this.Content = new List<Bottle>(); } for (int i = 0; i < 5; i++) { this.Content.Add(new Bottle()); } } public void Dispose() { if (this.Content == null) { return; } foreach (Bottle b in this.Content) { b.Dispose(); } } } /// <summary> /// Wrapper for a shelf storing bottles /// </summary> class Shelf:IDisposable { private ShelfWrapped InnerShelf = null; public Shelf() { this.InnerShelf = new ShelfWrapped(); } public void Fill() { if (this.InnerShelf == null) { this.InnerShelf = new ShelfWrapped(); } this.InnerShelf.Fill(); } public ShelfWrapped GetShelf() { return this.InnerShelf; } private List<Bartender> AllowedToDispose = new List<Bartender>(); public void Dispose(object disposer) { if (this.AllowedToDispose.Contains(disposer)) { if (InnerShelf != null) { this.InnerShelf.Dispose(); } } } public void Dispose() { // And again, John can dispose the shelf... } } A: In general, disposable objects should have clear owners, and objects should only dispose things they own. Sometimes it may be necessary to have a field which is owned by some instances of a type but not others; in those cases, one should combine the field with another that indicates whether it owns the instance in question. If a class FunStream inherits from Stream and wraps a Stream, for example, an instance should call Dispose the underlying stream when it is disposed if the code which created it won't be using the underlying stream anymore, but should not dispose it if the code which created it will want to keep using the Stream after the FunStream is disposed. Since the code creating the FunStream will know which pattern it expects, the FunStream constructors or factory methods should offer a parameter to indicate whether the FunStream should assume ownership of the stream. The only situation which poses major difficulties occurs when an object is effectively immutable but nonetheless encapsulates resources. Immutable objects are generally freely-shareable and are thus often shared. Although a resource should be released when nobody needs it anymore, predicting which immutable object will be the last one to use a resource is often difficult. The best approach to handling that situation is probably to have a LifetimeManager class which would use some ConditionalWeakTable objects to associate with each class a list of weak references to objects that are still using it, and which would offer a DisposeIfNotNeeded(IDisposable resource, Object owner); which would remove owner from the list of objects that still need the resource and dispose the resource when no more owners remain. I don't know of any existing implementations, however, and the design of such a thing would probably be a bit tricky. Still, using such a class would probably be the cleanest way to ensure properly-timed disposal of shared objects which encapsulate resources.
{ "pile_set_name": "StackExchange" }
Q: Impossible to access an attribute on a string variable In my controller i just pass some users on my twig view. Here is my function : public function viewAction($id) { $em = $this->getDoctrine()->getManager(); $planningRepo = $em->getRepository('SimonPediBundle:Planning'); $userRepo = $em->getRepository('SimonUserBundle:User'); $user = $this->getUser(); $planningId = $user->getPlanning()->getId(); $planning = $planningRepo->find($planningId); $users = $userRepo->findByPlanning($planningId); if (null === $planning) { throw new NotFoundHttpException("Le planning d'id ".$id. "n'existe pas."); } return $this->render('planningAction/planning.html.twig', array('planning' => $planning, 'users' => $users,)); } And this is my twig view where i want to display some information on a html table : <tbody> <tr> <th scope="row">Responsable</th> {% for i in 1..5 %} {% set assigned_user = ' ' %} {% for user in users if user.planningday == i%} {% set assigned_user = user %} {% endfor %} <td>{{assigned_user.name}} {{assigned_user.lastname}}</td> {% endfor %} </tr> <tr> <th scope="row">Description</th> {% for i in 1..5 %} {% set assigned_user = ' ' %} {% for user in users if user.planningday == i%} {% set assigned_user = user %} {% endfor %} <td>{{assigned_user.planningcontent}}</td> {% endfor %} </tr> </tbody> And i got this error : Impossible to access an attribute ("name") on a string variable (" "). for this line : <td>{{assigned_user.name}} {{assigned_user.lastname}}</td> Thanks for help! And here is my User Entity /** * User * * @ORM\Table(name="user") * @ORM\Entity(repositoryClass="Simon\UserBundle\Repository\UserRepository") */ class User extends BaseUser { /** * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) * @Assert\NotBlank(message="Merci d'entrer votre prénom.", groups={"Registration", "Profile"}) * @Assert\Length( * min=3, * max=50, * minMessage="Prénom trop court", * maxMessage="Prénom trop long", * groups={"Registration", "Profile"} * ) */ protected $name; /** * @var string * * @ORM\Column(name="lastname", type="string", length=255) * @Assert\NotBlank(message="Merci d'entrer votre nom.", groups={"Registration", "Profile"}) * @Assert\Length( * min=3, * max=50, * minMessage="Nom trop court", * maxMessage="Nom trop long", * groups={"Registration", "Profile"} * ) */ protected $lastname; /** * @var string * * @ORM\Column(name="phone", type="string", length=12) * @Assert\NotBlank(message="Merci d'entrer un numéro de téléphone.", groups={"Registration", "Profile"})) * @Assert\Length( * min=10, * max=10, * minMessage="Entrez un numéro de téléphone valide", * maxMessage="Entrez un numéro de téléphone valide", * groups={"Registration", "Profile"} * ) */ protected $phone; /** * @var boolean * *@ORM\Column(name="hasAdvert", type="boolean", nullable=true) */ protected $hasAdvert; /** * @var boolean * * @ORM\Column(name="isAdmin", type="boolean", nullable=true) */ protected $isAdmin; /** * * @ORM\ManyToOne(targetEntity="Simon\PediBundle\Entity\Planning", cascade={"persist"}) * */ protected $planning; /** * @var int * * @ORM\Column(name="planningday", type="smallint", nullable= true) */ protected $planningday; /** * @var text * * @ORM\Column(name="planningcontent", type="text", nullable= true) */ protected $planningcontent; /** *@ var string * @ORM\Column(name="address", type="string", length=255) */ protected $address; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return User */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set lastname * * @param string $lastname * * @return User */ public function setLastname($lastname) { $this->lastname = $lastname; return $this; } /** * Get lastname * * @return string */ public function getLastname() { return $this->lastname; } /** * Set phone * * @param string $phone * * @return User */ public function setPhone($phone) { $this->phone = $phone; return $this; } /** * Get phone * * @return string */ public function getPhone() { return $this->phone; } /** * Set hasAdvert * * @param boolean $hasAdvert * * @return User */ public function setHasAdvert($hasAdvert) { $this->hasAdvert = $hasAdvert; return $this; } /** * Get hasAdvert * * @return boolean */ public function getHasAdvert() { return $this->hasAdvert; } /** * Set isAdmin * * @param boolean $isAdmin * * @return User */ public function setIsAdmin($isAdmin) { $this->isAdmin = $isAdmin; return $this; } /** * Get isAdmin * * @return boolean */ public function getIsAdmin() { return $this->isAdmin; } /** * Set planningday * * @param integer $planningday * * @return User */ public function setPlanningday($planningday) { $this->planningday = $planningday; return $this; } /** * Get planningday * * @return integer */ public function getPlanningday() { return $this->planningday; } /** * Set planningcontent * * @param string $planningcontent * * @return User */ public function setPlanningcontent($planningcontent) { $this->planningcontent = $planningcontent; return $this; } /** * Get planningcontent * * @return string */ public function getPlanningcontent() { return $this->planningcontent; } /** * Set address * * @param string $address * * @return User */ public function setAddress($address) { $this->address = $address; return $this; } /** * Get address * * @return string */ public function getAddress() { return $this->address; } /** * Set planning * * @param \Simon\PediBundle\Entity\Planning $planning * * @return User */ public function setPlanning(\Simon\PediBundle\Entity\Planning $planning = null) { $this->planning = $planning; return $this; } /** * Get planning * * @return \Simon\PediBundle\Entity\Planning */ public function getPlanning() { return $this->planning; } } A: If you are using objects there is no need to set default value to string. Set it to null and check wether an user was found <tbody> <tr> <th scope="row">Responsable</th> {% for i in 1..5 %} {% set assigned_user = null %} {% for user in users if user.planningday == i%} {% set assigned_user = user %} {% endfor %} <td> {% if not assigned_user is null %} {{assigned_user.name}} {{assigned_user.lastname}} {% endif %} </td> {% endfor %} </tr> <tr> <th scope="row">Description</th> {% for i in 1..5 %} {% set assigned_user = null %} {% for user in users if user.planningday == i%} {% set assigned_user = user %} {% endfor %} <td> {% if not assigned_user is null %} {{assigned_user.planningcontent }} {% endif %} </td> {% endfor %} </tr> </tbody>
{ "pile_set_name": "StackExchange" }
Q: Ошибка при запуске приложения с MapActivity [Закрыт] Подскажите что и как исправить если выдаёт ошибку: INSTALL_FAILED_MISSING_SHARED_LIBRARY, а в LogCat: Package requires unavailable shared library com.google.android.maps failing Столько информации перерыла, ничего вразумительного. Помогите, плиз! A: Здравствуйте. Попробуйте сделать все эти действия: Правый клик по проекту -> Android tools -> Fix Project Properties. В верху, в Эклип выбираем пункт меню Project->Clean, ставим галочку на Clean projects selected below, выбираем свой проект и нажимаем "Ок". Проверьте ещё раз или проект создан для Google APIs, правой кнопкой по проекту ->Properties->Android. Можете попробовать выбрать Google APIs для другой версии Android. Так же проверьте эмулятор, правильно ли он создан! Ну и последнее что я могу посоветовать, это проверьте свои ключи которые вы получали для работы с Google Maps, может вы их где то не правильно ввели или не правильно получили. П.С. ссылки для работы с Google Maps: link1, link2 - в конце поста есть много полезных ссылок на рус. статьи, link3, link4
{ "pile_set_name": "StackExchange" }
Q: "install" new config file Hello I am a relatively new user and hope this is the right place to ask this question. I am trying to get a Huawei 3g dongle to work. I think I found the answer but I don't know how to implement these steps: #Install into /etc/usb_modeswitch.d #HuaweiE3531s-2 TargetVendor=0x12d1 TargetProduct=0x15ce "MessageContent="55534243123456780000000000000011062000000100000000000000000000" How exactly do I get this config file into the directory usb_modeswitch.d? Thanks for a helping a new but happy user of Ubuntu! A: On my installations the directory /etc/usb_modeswitch.d does not exist by default, so it must be created first: sudo mkdir /etc/usb_modeswitch.d To create the file, you could use the simple text editor nano to achieve this, using the following command: sudo nano /etc/usb_modeswitch.d/HuaweiE3531s-2.conf This will open the editor, where you can type in those required lines. TargetVendor=0x12d1 TargetProduct=0x15ce MessageContent="55534243123456780000000000000011062000000100000000000000000000" When you're finished carefully typing those lines, press Ctrl+X followed by Y, then Enter to write and save the file. One word of warning however, the 'MessageContent' line should not have a double quote before it, as shown in your question, though the double quotes around the number string are correct. A: Create a file HuaweiE3531s-2.conf in /etc/usb_modeswitch.d with this content: TargetVendor=0x12d1 TargetProduct=0x15ce MessageContent="55534243123456780000000000000011062000000100000000000000000000"
{ "pile_set_name": "StackExchange" }
Q: Kendo tooltip empty with LoadContentFrom When using LoadContentFrom in my Kendo.Tooltip, the tooltip is always empty, all I see is a grey box the size I specified. It does go to the controller to get the data (verified with breakpoint), but after that, nothing. If I use ContentTemplateId instead, it shows the template, but I really need to get some dynamic data from the server. What am I missing to fix this? Thanks <%:Html.Kendo().Tooltip() .For("#alertPanel") .LoadContentFrom("AlertsDetails", "Home") .Width(320).Height(320) %> Controller: public ActionResult AlertsDetails() { List<object> list = new List<object>(); //fill list with data ... ViewBag.title = "New alerts"; return PartialView(list); } A: Answer: You can't return data the way I was doing. You need to format the data server-side in an HTML string and set the result in the ViewBag. public ActionResult AlertsDetails() { ViewBag.Title = "<a href='#'>A link</a>"; return PartialView(); } and <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %> <%= ViewBag.Title%> That's it...
{ "pile_set_name": "StackExchange" }
Q: What points I should keep in mind while integrating google tag (GTM) in chrome extension? I would like to use Google tag manager in my chrome extension. What points should I keep in mind while integrating google tag (GTM) in chrome extension? A: Since google chrome extension works in context of the current opened website. The content script is injected in to the DOM of current website and. Therefore we can not use the body tag of the website. So I have to inject an iframe here. I have created a chrome extension page and used it as src of the injected iFrame. Now I have the dedicated html page with the body tag that I can use to put gtm code. But its not over yet. Since the chrome "content_security_policy" won't allow to execute inline javascript code the GTM code must be in a .js file. gtm.js: (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-XXXXXX'); One more change to do here is to prefix https: with //www.googletagmanager.com Html code: <body > <script src="js/gtn.js"></script> Please see this url for a quick installation guide. https://support.google.com/tagmanager/answer/6103696?vid=1-635768734723363100-1900843843 Posting this answer so this may be may helpful for others. Regards.
{ "pile_set_name": "StackExchange" }
Q: Differintegral using Fourier Transforms in multivariate functions. So I know that the Fourier Transform of a function $f(t)$, denoted $\mathcal{F}[f(t)]$ can be used to compute derivatives (and integrals) of $f(t)$, including of non-integer order like so: $$ \frac{d^n f(t)}{dt^n} = \mathcal{F}^{-1}\{(i\omega)^n \mathcal{F}[f(t)]\} $$ where $\omega$ is the frequency variable. This is known from the properties of the fourier transform, however, I was thinking about how to generalize this for higher-dimensions. Higher dimensional functions $f(\vec r)$ have more interesting differential operators like gradients $\nabla f(\vec r)$ and Laplacians $\nabla^2 f(\vec r)$ and I was wondering how to use the principle stated in the equation above to compute these quantities. A: See this blog post of Terry Tao, Remark 2.
{ "pile_set_name": "StackExchange" }