_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
21
37k
language
stringclasses
1 value
title
stringclasses
1 value
d17385
val
AngularJS $scopes prototypically inherit from each other. Quoting the wiki: In AngularJS, a child scope normally prototypically inherits from its parent scope. One exception to this rule is a directive that uses scope: { ... } -- this creates an "isolate" scope that does not prototypically inherit.(and directive with transclusion) This construct is often used when creating a "reusable component" directive. In directives, the parent scope is used directly by default, which means that whatever you change in your directive that comes from the parent scope will also change in the parent scope. If you set scope:true (instead of scope: { ... }), then prototypical inheritance will be used for that directive. This means that assuming you did not pass scope: { ... } you can access properties on the parent's scope directly. So for example if the parent scope has a x: 5 property - you can simply access it with $scope.x.
unknown
d17387
val
You can set ascending or descending in the last argument of your query. In your case, your getData() method can return your string with the KEY_SCORE column in descending order by changing the query line to this: Cursor c = ourDbase.query(MyTABLE, columns , null, null, null, null, KEY_SCORE + " DESC"); Good Luck!
unknown
d17389
val
I would do update statement to do all in once like this : UPDATE OrderTable INNER JOIN table_to_fill ON OrderTable.refkey = table_to_fill.refkey SET OrderTable.value = table_to_fill.value A: Eloquent is very powerfull to manage complicated relationship, joins, eager loaded models etc... But this abstraction has a performance cost. Each model have to be created, filled and saved, it is packed with tons of features you don't need for this precise use case. When editing thousand or even millions of records, it is highly inefficient to use Eloquent models. Instead you can either use the laravel Query builder or a raw SQL statement. I would recommend this approach: $table = Db::table('orders'); foreach ($xml as $row) { $table->where('reference_key', $reference_key) ->update('new_value', (float)$row->new_value); } But you can also do something like this: foreach ($xml as $row) { DB::statement('UPDATE orders SET new_value=? WHERE reference_key=?', [(float)$row->new_value, $reference_key]); } It will cut down your execution time significantly but the loop over millions of XML lines will still take a long time.
unknown
d17391
val
parseKeyFromFile is a convenience function that reads a file and parses the contents. You don't have a file, you have an asset that you are already doing the work of reading into a string. Having read the file, it just parses it - and that's what you need. This should work: final publicPem = await rootBundle.loadString('assets/public_key.pem'); final publicKey = RSAKeyParser().parse(publicPem) as RSAPublicKey; and similar for the private key.
unknown
d17393
val
IIUC, I think you want something like this: df['Avg Qty'] = (df.groupby([pd.Grouper(freq='180D', key='Date'),'A','B'])['Qty'] .transform('mean')) Output: Date A B Qty Cost Avg Qty 0 2017-12-11 Cancer Golf 1 100 1.5 1 2017-11-11 Cancer Golf 2 200 1.5 2 2017-11-11 Cardio Golf 2 300 2.0 3 2017-10-11 Cardio Baseball 3 600 3.0 4 2017-04-11 Cancer Golf 4 150 4.0 5 2016-01-01 Cancer Football 5 200 5.0 Edit: df = df.set_index('Date') df.groupby(['A','B']).apply(lambda x: x.sort_index().rolling('180D')['Qty'].mean()).reset_index()\ .merge(df.reset_index(), on=['Date','A','B'], suffixes=('_avg','')) Output: A B Date Qty_avg Qty Cost 0 Cancer Football 2016-01-01 5.0 5 200 1 Cancer Golf 2017-04-11 4.0 4 150 2 Cancer Golf 2017-11-11 2.0 2 200 3 Cancer Golf 2017-12-11 1.5 1 100 4 Cardio Baseball 2017-10-11 3.0 3 600 5 Cardio Golf 2017-11-11 2.0 2 300
unknown
d17395
val
This question already has answers. Copy and pasted from here: Coinbase API v2 Getting Historic Price for Multiple Days Any reason you aren't using coinbase pro? The new api is very easy to use. Simply add the get command you want followed by the parameters separated with a question mark. Here is the new historic rates api documentation: https://docs.pro.coinbase.com/#get-historic-rates The get command with the new api most similar to prices is "candles". It requires three parameters to be identified, start and stop time in iso format and granularity which is in seconds. Here is an example: https://api.pro.coinbase.com/products/BTC-USD/candles?start=2018-07-10T12:00:00&stop=2018-07-15T12:00:00&granularity=900 EDIT: also, note the time zone is not for your time zone, I believe its GMT.
unknown
d17399
val
It's because let is only restricted keyword when in strict mode MDN source: let = new Array(); console.log(let); VS "use strict"; let = new Array(); console.log(let); A: Let is the name of variable. Example here: let = new Array foo = new Array bar = new Array console.log(let, foo, bar)
unknown
d17405
val
First element Second Element Well its true that you are getting similar elements for that given xpath but you also have to go through their siblings/parents etc for different scenarios. Here is the xpath I tried that identified the individual elements that you were looking for, are depicted above. //div[@class='iradio_square-green']/input[@id='trip_0_date_0_flight_0_fare_0']/following-sibling::ins For others radio buttons you just have to change the flight number. Hope this helps... :)
unknown
d17411
val
I think you need to provide the destination folder as a key and value, something like this(below) var upload = multer({ dest: 'uploads/' }) You can check out the full multer documentations here https://expressjs.com/en/resources/middleware/multer.html
unknown
d17419
val
You can access the grid reference in useEffect block when all it's content is rendered: useEffect(()=> { const grid = ref.current.wrapper.current; //--> grid reference const header = grid.querySelector(".gridjs-head"); //--> grid header const itemContainer = document.createElement("div"); //--> new item container header.appendChild(itemContainer); ReactDOM.render(<Input />, itemContainer); //--> render new item inside header }, []); You will need to use css to get the desired position inside the element. Working example: https://stackblitz.com/edit/react-r5gsvw A: Or just use a CSS solution for that component you want. e.g. <div style={{ position: 'relative'}}> <Grid .... /> <MySearchComponent style={{ position: 'absolute', top: 0, right: 0 }} /> </div>
unknown
d17423
val
actionListener="#{bean[confMethod(param1, param2)]}" This syntax is indeed invalid. You're basically expecting that the confMethod is a static function which returns the name of the dynamic method based on the given two arguments. The correct syntax is as below: actionListener="#{bean[confMethod](param1, param2)}"
unknown
d17425
val
Thanks @jordanm for answering in the comments. I'm expanding into a more detailed answer. The client documentation contains a section called "Service Resource" that I had not noticed before. Highlighted the service resource in the table of contents: Clicking this heading shows me the methods and properties of an EC2 resource instance. A: Hope this answer is useful to some even though its late. Use these two links accordingly Consider the 1st one as the Main reference. This is the link provided in the other answer https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#service-resource Main reference The 2nd one provides a more detailed view on the methods and attributes available for a particular resource like instance,image,VPC etc https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html ^this is almost the same link -- all options below the service-resource provide detailed info on that particular resource such as instance,image etc., common resources
unknown
d17429
val
In order to you get the fair estimation of your trained model on the validation dataset you need to set the test_itr and test_batch_size in a meaningful manner. So, test_itr should be set to: Val_data / test_batch_Size Where, Val_data is the size of your validation dataset and test_batch_Size is validation batch size value set in batch_size for the Validation phase.
unknown
d17433
val
I guess you need to select promo price if it's available otherwise you need normal price. So you should select columns using IF statement after LEFT JOIN. this query may help : SELECT if(td_prom.ID, td_prom.ID, td_norm.ID) as ID, th.doc_num, if(td_prom.price, td_prom.price, td_norm.price) as price, if(td_prom.item, td_prom.item, td_norm.item) as item, th.promo FROM t_header th LEFT JOIN t_detail as td_norm ON th.doc_num = td_norm.doc_num AND th.promo = 0 LEFT JOIN t_detail as td_prom ON th.doc_num = td_prom.doc_num AND th.promo = 1 GROUP BY item A: As I can see in you desired result, you don't want items to be shown twice. Next to this I assume you have an items table in your database. Then I came up with this query. First part is to extract items in promo. Second part add only those items which are not in promo, but exclude items that have a promo on them. SELECT d.id, d.doc_num, d.item, d.price, h.promo FROM items AS i INNER JOIN detail AS d ON i.id = d.id INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 1 UNION ALL SELECT nopromo.* FROM (SELECT d.id, d.doc_num, d.item, d.price, h.promo FROM items AS i INNER JOIN detail AS d ON i.id = d.id INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 0) AS nopromo LEFT OUTER JOIN (SELECT d.id, d.doc_num, d.item, d.price, h.promo FROM item AS i INNER JOIN detail AS d ON i.id = d.id INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 1) AS ipromo ON nopromo.item = ipromo.item WHERE ipromo.id IS NULL ORDER BY item Result +---+--------+-----+------+------+ |id |doc_num |item |price |promo | +---+--------+-----+------+------+ |1 |0001 |2 |100 |0 | |5 |0002 |3 |120 |1 | |6 |0002 |4 |99 |1 | |4 |0001 |5 |105 |0 | |7 |0002 |7 |165 |1 | +---+--------+-----+------+------+
unknown
d17447
val
importPackage is originally from Rhino. Even Nashorn supports it when Rhino/Mozilla compatibility is requested explicitly using load("nashorn:mozilla_compat.js"); only, see Rhino Migration Guide in the documentation of Nashorn. Graal.js has Nashorn compatibility mode and it supports load("nashorn:mozilla_compat.js"); in this mode. So, you can use something like System.setProperty("polyglot.js.nashorn-compat", "true"); ScriptEngine engine = new ScriptEngineManager().getEngineByName("graal.js"); System.out.println(engine.eval("load('nashorn:mozilla_compat.js'); importPackage('java.awt'); new Point();")); (it prints java.awt.Point[x=0,y=0] which shows that the package java.awt was imported successfully).
unknown
d17449
val
It looks like you want the set difference (that is, IPs in A that are not also in B), soooooo: SELECT a.ip FROM tableA a WHERE tableA.ip NOT IN (SELECT b.ip FROM tableB) A: Use NOT IN: SELECT ip FROM TableA WHERE TableA.ip NOT IN (SELECT ip FROM TableB) A: You can combine two result sets with UNION. select ip from tableA union select ip from tableB; http://dev.mysql.com/doc/refman/5.0/en/union.html The default behavior is to remove duplicate rows. If you want duplicate rows use UNION ALL. A: select a.id from a minus select b.id from b or select a.id from a where a.id not in (select b.id from b) A: SELECT col1, col2, .. , Ip from TableA UNION SELECT col, col2, ...., Ip from TableB To get the differences you can use the MINUS Operator instead of UNION
unknown
d17451
val
Your forgot the changes keyword. The correct syntax is when transform $Body changes do ( print "moved" ) A: An already key-framed node will not trigger this handler it is not being driven by the user, but by the system. This will not trigger when you press play in the trackbar. Without knowing exactly what you intend to do it's difficult to recommend an alternative. If you wish to report the position or transform information of a specific node when the trackbar/currentTime changes, you could use registerTimeCallback and unRegisterTimeCallback . fn reportObject = ( print $Box001.pos ) registerTimeCallback reportObject This will trigger when the play button is used, or when you scrub the time bar. Read the documentation regarding timecallbacks as they have specific rules. Hopefully this helps.
unknown
d17457
val
See What is the most efficient way to get this kind of matrix from a 1D numpy array? and Copy flat list of upper triangle entries to full matrix? Roughly the approach is result = np.zeros(...) ind = np.triu_indices(...) result[ind] = values Details depend on the size of the target array, and the layout of your values in the target. In [680]: ind = np.triu_indices(4) In [681]: values = np.arange(16).reshape(4,4)[ind] In [682]: result = np.zeros((4,4),int) In [683]: result[ind]=values In [684]: values Out[684]: array([ 0, 1, 2, 3, 5, 6, 7, 10, 11, 15]) In [685]: result Out[685]: array([[ 0, 1, 2, 3], [ 0, 5, 6, 7], [ 0, 0, 10, 11], [ 0, 0, 0, 15]])
unknown
d17459
val
Try this code: #!/usr/bin/env python import gi gi.require_version ('Gtk', '3.0') from gi.repository import Gtk, GdkPixbuf, Gdk, GLib import os, sys, time class GUI: def __init__(self): window = Gtk.Window() self.switch = Gtk.Switch() window.add(self.switch) window.show_all() self.switch.connect('state-set', self.switch_activate) window.connect('destroy', self.on_window_destroy ) def on_window_destroy(self, window): Gtk.main_quit() def switch_activate (self, switch, boolean): if switch.get_active() == True: GLib.timeout_add(200, self.switch_loop) def switch_loop(self): print time.time() return self.switch.get_active() #return True to loop; False to stop def main(): app = GUI() Gtk.main() if __name__ == "__main__": sys.exit(main())
unknown
d17463
val
string MyConString = "Data Source='mysql7.000webhost.com';" + "Port=3306;" + "Database='a455555_test';" + "UID='a455555_me';" + "PWD='something';"; A: Here is an example: MySqlConnection con = new MySqlConnection( "Server=ServerName;Database=DataBaseName;UID=username;Password=password"); MySqlCommand cmd = new MySqlCommand( " INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+ OSGconv.deciLon+"')", con); con.Open(); cmd.ExecuteNonQuery(); con.Close(); A: try creating connection string this way: MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder(); conn_string.Server = "mysql7.000webhost.com"; conn_string.UserID = "a455555_test"; conn_string.Password = "a455555_me"; conn_string.Database = "xxxxxxxx"; using (MySqlConnection conn = new MySqlConnection(conn_string.ToString())) using (MySqlCommand cmd = conn.CreateCommand()) { //watch out for this SQL injection vulnerability below cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})", OSGconv.deciLat, OSGconv.deciLon); conn.Open(); cmd.ExecuteNonQuery(); }
unknown
d17467
val
You can find demo code at OCRScannerDemo for old api, for new api new api demo About api javadoc you can generate it with maven. To get source code : git clone http://git.code.sf.net/p/javaocr/source javaocr-source
unknown
d17469
val
The regex issue can be answered with a simple negative assertion: preg_replace('/(<(?!img)\w+[^>]+)(style="[^"]+")([^>]*)(>)/', '${1}${3}${4}', $article->text) And a simpler approach might be using querypath (rather than fiddly DOMDocument): FORACH htmlqp($html)->find("*")->not("img") EACH $el->removeAttr("style"); A: This does as you've asked $string = '<img attribut="value" style="myCustom" attribut=\'value\' style=\'myCustom\' /> <input attribut="value" style="myCustom" attribut=\'value\' style=\'myCustom\'> <span attribut="value" style="myCustom" attribut=\'value\' style=\'myCustom\'> style= </span>'; preg_match_all('/\<img.+?\/>/', $string, $images); foreach ($images[0] as $i => $image) { $string = str_replace($image,'--image'.$i.'--', $string); } $string = preg_replace(array('/style=[\'\"].+?[\'\"]/','/style=/'), '', $string); foreach ($images[0] as $i => $image) { $string = str_replace('--image'.$i.'--',$image, $string); } OUTPUTS <img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" attribut='value' > <span attribut="value" attribut='value' > </span> A: A very simple regular expression to get rid of them, without going too much into it would be preg_replace( '/style="(.*)"/', 'REPLACEMENT' ) Very simple, effective enough though
unknown
d17471
val
As said in the doc, the main differences are in how you are going to get an instance through Dependency Injection. With Named Client you need to inject the factory and then get the client by a string. var client = _clientFactory.CreateClient("github"); With Typed Client you can inject the client needed as a type. //GitHubService encapsulate an HTTP client public TypedClientModel(GitHubService gitHubService) { _gitHubService = gitHubService; } Both of them give the solution to your problem. The selection is more in how comfortable you are with the dependency injection method of each one. I personally prefer the Typed client.
unknown
d17477
val
Usually, such things happen when you didn't require vendor/autoload.php, or autoload wasn't generated. IDE may show you that everything is OK just because it parsed your composer.json. Try to: * *composer update *get sure you required vendor/autoload.php in your script
unknown
d17479
val
Your first example is correct and absolutely should work: var contacts = db.vMyView.OrderBy(c => c.LastName).ThenBy(c => c.FirstName); // not sure why you need to reorder. Which could distort previous sorting contacts = contacts.OrderBy(orderExpressions[sortExpression]).ThenBy(orderExpressions["FirstName"]); Something looks off in your second example. OrderBy and ThenBy are already ascending there's no need for the additional parameter. There are alternatives for descending which are suffixed appropriately: OrderByDescending and ThenByDescending.
unknown
d17481
val
I think you may just be looking for var varType *os.File tpe := reflect.TypeOf(varType).Elem() fmt.Println(tpe == reflect.TypeOf(somevar).Elem())
unknown
d17489
val
Welcome to SO. Although this is definitely not efficient for a small tuple, for a large one this will speed up the process greatly (from an O(n^2) solution to an O(n)). I hope this helps. x = (2, 3, 4, 5) y = ((2, 3), (3.5, 4.5), (6, 9), (4, 7)) for a, b in enumerate(y): if b[0] <= x[a] <= b[1]: print(f'{x[a]} is in between {b}.') else: print(f'{x[a]} is not in between {b}') For boolean values: interval = lambda t, i: [b[0] <= t[a] <= b[1] for a, b in enumerate(i)] x = (2, 3, 4, 5) y = ((2, 3), (3.5, 4.5), (6, 9), (4, 7)) print(interval(x, y)) All within linear (O(n)) time! Thanks for reading and have a great day. A: You can achieve this in linear time using one loop. You only have to iterate once on both of the tuples, something like this: x = (2, 3, 4, 5) y = ((2,3), (3.5, 4.5), (6, 9), (4, 7)) for index, number in enumerate(x): if number > y[index][1] or number < y[index][0]: print(f'{number} is NOT in {y[index}') else: print(f'{number} is in {y[index]}') the output is: 2 is in the interval (2, 3) 3 is NOT in the interval (3.5, 4.5) 4 is NOT in the interval (6, 9) 5 is in the interval (4, 7) As i said, this solution will take O(n), instead of O(n^2) A: What about something like this >>> x = (2, 3, 4, 5) >>> y = ((2,3), (3.5, 4.5), (6, 9), (4, 7)) >>> def f(e): ... p, (q, r) = e ... return q <= p <= r >>> list(map(f, zip(x,y))) [True, False, False, True]
unknown
d17491
val
Indeed the expm's package does use exponentiation by squaring. In pure r, this can be done rather efficiently like so, "%^%" <- function(mat,power){ base = mat out = diag(nrow(mat)) while(power > 1){ if(power %% 2 == 1){ out = out %*% base } base = base %*% base power = power %/% 2 } out %*% base } Timing this, m0 <- diag(1, nrow=3,ncol=3) system.time(replicate(10000, m0%^%4000))#expm's %^% function user system elapsed 0.31 0.00 0.31 system.time(replicate(10000, m0%^%4000))# my %^% function user system elapsed 0.28 0.00 0.28 So, as expected, they are the same speed because they use the same algorithm. It looks like the overhead of the looping r code does not make a significant difference. So, if you don't want to use expm, and need that performance, then you can just use this, if you don't mind looking at imperative code. A: A shorter solution with eigenvalue decomposition: "%^%" <- function(S, power) with(eigen(S), vectors %*% (values^power * t(vectors))) A: If A is diagonizable, you could use eigenvalue decomposition: matrix.power <- function(A, n) { # only works for diagonalizable matrices e <- eigen(A) M <- e$vectors # matrix for changing basis d <- e$values # eigen values return(M %*% diag(d^n) %*% solve(M)) } When A is not diagonalizable, the matrix M (matrix of eigenvectors) is singular. Thus, using it with A = matrix(c(0,1,0,0),2,2) would give Error in solve.default(M) : system is computationally singular. A: The expm package has an %^% operator: library("sos") findFn("{matrix power}") install.packages("expm") library("expm") ?matpow set.seed(10);t(matrix(rnorm(16),ncol=4,nrow=4))->a a%^%8 A: Although Reduce is more elegant, a for-loop solution is faster and seems to be as fast as expm::%^% m1 <- matrix(1:9, 3) m2 <- matrix(1:9, 3) m3 <- matrix(1:9, 3) system.time(replicate(1000, Reduce("%*%" , list(m1,m1,m1) ) ) ) # user system elapsed # 0.026 0.000 0.037 mlist <- list(m1,m2,m3) m0 <- diag(1, nrow=3,ncol=3) system.time(replicate(1000, for (i in 1:3 ) {m0 <- m0 %*% m1 } ) ) # user system elapsed # 0.013 0.000 0.014 library(expm) # and I think this may be imported with pkg:Matrix system.time(replicate(1000, m0%^%3)) # user system elapsed #0.011 0.000 0.017 On the other hand the matrix.power solution is much, much slower: system.time(replicate(1000, matrix.power(m1, 4)) ) user system elapsed 0.677 0.013 1.037 @BenBolker is correct (yet again). The for-loop appears linear in time as the exponent rises whereas the expm::%^% function appears to be even better than log(exponent). > m0 <- diag(1, nrow=3,ncol=3) > system.time(replicate(1000, for (i in 1:400 ) {m0 <- m0 %*% m1 } ) ) user system elapsed 0.678 0.037 0.708 > system.time(replicate(1000, m0%^%400)) user system elapsed 0.006 0.000 0.006 A: Simple solution `%^%` <- function(A, n) { A1 <- A for(i in seq_len(n-1)){ A <- A %*% A1 } return(A) }
unknown
d17493
val
If i get it correct, your situation is as follows: You have, for example, one application (EXE) which uses a shared library (DLL). From both, the EXE and the DLL, you want to be able to log. Last time i checked out the logog library i run in problems with the situation described above. Maybe now it is corrected? Under windows (only!), the logog library doesn't export any symbols - it is simply not ready to be used as DLL. This forces you to build and use logog as static library - which leads to problems with static variables inside the logog library which should exist only once, but in reality are existing as many times as the static library was linked to a module (EXE or DLL). The solution would be to build and use the logog library as DLL. Maybe this covers your problem and you may take the effort to export the symbols of the logog library. Or you could get in contact with the library writer.
unknown
d17497
val
Scala's "f interpolator" is useful for this: x.foreach { case (text, price, amount) => println(f"$amount x $text%-40s $$${price*amount}") } // prints: 1 x (Burger and chips,4.99) $4.99 2 x (Pasta & Chicken with Salad,8.99) $17.98 2 x (Rice & Chicken with Chips,8.99) $17.98
unknown
d17499
val
A naive approach would truncate the creation timestamp to date, then compare: where date(m.create_dtm) = current_date - interval 1 day But it is far more efficient to use half-open interval directly against the timestamp: where m.create_dtm >= current_date - interval 1 day and m.create_dtm < current_date A: You can try next queries: SELECT m.meeting_id, m.member_id, m.org_id, m.title, m.create_dtm FROM meeting m -- here we convert datetime to date for each row -- it can be expensive for big table WHERE date(create_dtm) = DATE_SUB(CURDATE(), INTERVAL 1 DAY); SELECT m.meeting_id, m.member_id, m.org_id, m.title, m.create_dtm FROM meeting m -- here we calculate border values once and use them WHERE create_dtm BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND DATE_SUB(CURDATE(), INTERVAL 1 SECOND); Here live fiddle: SQLize.online
unknown
d17501
val
You can use filters. Here's an example of how to use filters: http://viralpatel.net/blogs/2009/01/tutorial-java-servlet-filter-example-using-eclipse-apache-tomcat.html Basically you define the url's where you want the filters to apply, the filter authorizes the user and then calls chain.doFilter(request, response); to call the requested method after authorization. You can also take a look at this jax-rs rest webservice authentication and authorization Personally, I use tokens for authorization. A: It all depends on how is your web service implemented/or its going to be. If you still have a choice I would recommend going with REST approach, authenticate the user with some kind of login functionality and then maintain users session.
unknown
d17507
val
What's likely happening is that npx react-native init MyProject is sub-shelling into Bash where you do not have rbenv configured. When it tries to run ruby from Bash it looks in $PATH and finds the default macOS version of Ruby -- 2.6.10 -- and errors out. This is discussed thoroughly in the react-native repo where there are many solutions, but what it boils down to is react-native init is not finding the right version of Ruby, for whatever reason. You can bypass that by completing the failing part of the init process yourself with: cd MyProject bundle install cd ios && bundle exec pod install The longer version of the solution is to configure rbenv for Bash as well, but this isn't necessary as you can likely use just the workaround above: echo 'eval "$(~/.rbenv/bin/rbenv init - bash)"' >> ~/.bash_profile
unknown
d17511
val
Looks like the OAuth library is being built against 3.0 frameworks. If you want to target 2.2.1, it'll need to be built against those frameworks.
unknown
d17513
val
Assuming that LinkedBag refers to the LinkedList data structure, then yes you are correct in that Set would be a third section, with SortedSet inheriting from it. However, I would not define it as an "interface". Interfaces are a type of class which is generally used as a blueprint for inheriting classes to follow, and does not implement their own class functions. Instead, they declare functions which their derivative classes will implement. For additional information, Abstract Classes are similar, except that they can implement their class functions. Neither Interfaces nor Abstract classes can (usually) be initialized as an object. This becomes a lot more blurry in Python which uses the general "Python Abstract Base Classes" and doesn't do Interfaces directly, but can be mocked through the abstract classes. However, as a term for general programming, the distinctions between normal classes, interfaces, and abstract classes can be important, especially since interfaces and abstract classes (usually) are not/ can not be initialized as objects. The exact rules of inheritance regarding Interfaces and Abstract Classes can differ between languages, for example in Java you can't inherit from more than one abstract class, so I won't directly address it here. Since a Set is a data structure on its own that can, and usually should, have functionality separate from a sorted set, you would not make the set an interface, but rather a normal class. You can still inherit from normal classes, which is what you would do with SortedSet inheriting from Set. A: A sorted set according to the narrative is a set, but with some variations in some behavior: A sorted set behaves just like a set, but allows the user to visit its items in ascending order with a for loop, and supports a logarithmic search for an item. This means that SortedSet would inherit from Set, just like SortedArrayBag inherits from ArrayBag. Inheritance should by the way shown in UML with a big hollow array head (small arrows like in your diagram mean a navigable association, which has nothing to do with inheritance). A set is however not a bag. A set contains an item at maximum once, whereas a bag may contain multiple times the same item. This could lead to a completely different interface (e.g. membership on an item is a boolean for a set, whereas it could be an integer for a bag). The safe approach would therefore be to insert an AbstractSet inheriting from AbstractCollection: A shortcut could be to deal with the set like a bag, and return a count of 1 for any item belonging to the set, ignoring multiple inserts. This would not be compliant with the Liskov Substitution Principle, since it would not respect all the invariants and weaken post-conditions. But if you'd nevertheless go this way, you should insert Set as extending AbstractBag, and SortedSet as a specialization of Set. In this case, your set (and sorted set) would also realise the BagInterface (even if it'd twist it). Shorn's answer analyses this situation very well.
unknown
d17515
val
One possibility is to use the usage command, which displays both the amount of RAM currently being used, as well as the User and the System time used by the tool since when it was started (thus, usage should be called both before and after each operation which you want to profile). An example execution: NuSMV > usage Runtime Statistics ------------------ Machine name: ***** User time 0.005 seconds System time 0.005 seconds Average resident text size = 0K Average resident data+stack size = 0K Maximum resident size = 6932K Virtual text size = 8139K Virtual data size = 34089K data size initialized = 3424K data size uninitialized = 178K data size sbrk = 30487K Virtual memory limit = -2147483648K (-2147483648K) Major page faults = 0 Minor page faults = 2607 Swaps = 0 Input blocks = 0 Output blocks = 0 Context switch (voluntary) = 9 Context switch (involuntary) = 0 NuSMV > reset; read_model -i nusmvLab.2018.06.07.smv ; go ; check_property ; usage -- specification (L6 != pc U cc = len) IN mm is true -- specification F (min = 2 & max = 9) IN mm is true -- specification G !((((max > arr[0] & max > arr[1]) & max > arr[2]) & max > arr[3]) & max > arr[4]) IN mm is true -- invariant max >= min IN mm is true Runtime Statistics ------------------ Machine name: ***** User time 47.214 seconds System time 0.284 seconds Average resident text size = 0K Average resident data+stack size = 0K Maximum resident size = 270714K Virtual text size = 8139K Virtual data size = 435321K data size initialized = 3424K data size uninitialized = 178K data size sbrk = 431719K Virtual memory limit = -2147483648K (-2147483648K) Major page faults = 1 Minor page faults = 189666 Swaps = 0 Input blocks = 48 Output blocks = 0 Context switch (voluntary) = 12 Context switch (involuntary) = 145
unknown
d17517
val
The issue here is probably that you have an akka-actor.jar in your scala distributuion that is Akka 2.1.x and you're trying to use Akka 2.2.x. You'll have to run your code by running the java command and add the scala-library.jar and the correct akka-actor.jar and typesafe-config.jar to the classpath. A: Are you using Scala 2.10? This is the Scala version you need for Akka 2.2. What does the following yield? scala -version It should show something like $ scala -version Scala code runner version 2.10.3 -- Copyright 2002-2013, LAMP/EPFL
unknown
d17521
val
yes, It is also working for me check public class SerializationIssue { private static final String fileName = "testFile"; public static void main(String[] args) { TestObject object1= new TestObject(); TestObject object2=new TestObject(); object1.setName("object1"); object2.setName("object2"); List<TestObject> list=new ArrayList<TestObject>(); list.add(object1); list.add(object2); serializeList(list); ArrayList<TestObject> deserializedList=desializeDemo(); System.out.println(deserializedList.get(0).getName()); } private static ArrayList desializeDemo() { ArrayList<TestObject> deserializedList; try { FileInputStream fileIn = new FileInputStream(fileName); ObjectInputStream in = new ObjectInputStream(fileIn); deserializedList= (ArrayList<TestObject>) in.readObject(); in.close(); fileIn.close(); }catch(IOException i) { i.printStackTrace(); return null; }catch(ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return null; } return deserializedList; } private static void serializeList(List<TestObject> list) { // TODO Auto-generated method stub try { FileOutputStream fos = new FileOutputStream(fileName); ObjectOutputStream os = new ObjectOutputStream ( fos ); os.writeObject ( list ); fos.close (); os.close (); } catch ( Exception ex ) { ex.printStackTrace (); } } } TestObject bean public class TestObject implements Serializable{ /** * serial version. */ private static final long serialVersionUID = 1L; String name; public TestObject(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Output:object1
unknown
d17523
val
If it's a yearly investment, you should add it every year: yearly = float(input("Enter the yearly investment: ")) apr = float(input("Enter the annual interest rate: ")) years = int(input("Enter the number of years: ")) total = 0 for i in range(years): total += yearly total *= 1 + apr print("The value in 12 years is: ", total) With your inputs, this outputs ('The value in 12 years is: ', 3576.427533818945) Update: Responding to your questions from the comments, to clarify what's going on: 1) You can use int() for yearly and get the same answer, which is fine if you always invest a whole number of currency. Using a float works just as well but also allows the amount to be 199.99, for example. 2) += and *= are convenient shorthand: total += yearly means total = total + yearly. It's a little easier to type, but more important, it more clearly expresses the meaning. I read it like this for i in range(years): # For each year total += yearly # Grow the total by adding the yearly investment to it total *= 1 + apr # Grow the total by multiplying it by (1 + apr) The longer form just isn't as clear: for i in range(years): # For each year total = total + yearly # Add total and yearly and assign that to total total = total * (1 + apr) # Multiply total by (1 + apr) and assign that to total A: It can be done analytically: """ pmt = investment per period r = interest rate per period n = number of periods v0 = initial value """ fv = lambda pmt, r, n, v0=0: pmt * ((1.0+r)**n-1)/r + v0*(1+r)**n fv(200, 0.09, 10, 2000) Similarly, if you are trying to figure out the amount you need to invest so you get to a certain number, you can do: pmt = lambda fv, r, n, v0=0: (fv - v0*(1+r)**n) * r/((1.0+r)**n-1) pmt(1000000, 0.09, 20, 0) A: As suggested in the comments, you shouldn't use eval() here. (More info on eval can be found in the Python Docs). -- Instead, change your code to use float() or int() where applicable, as shown below. Also, your print() statement printed out the parenthesis and comma, which I expect you didn't want. I cleaned it up in the code below, but if what you wanted is what you had feel free to put it back. principal = float(input("Enter the yearly investment: ")) apr = float(input("Enter the annual interest rate: ")) # Note that years has to be int() because of range() years = int(input("Enter the number of years: ")) for i in range(years): principal = principal * (1+apr) print "The value in 12 years is: %f" % principal
unknown
d17525
val
2nd. Because you will only open your BD connection one time to insert your data and close. :)
unknown
d17527
val
There's no "restore" feature on the iPad. But in all probability there's nothing to worry about. There's nothing about your code that would delete multiple files. It would delete just that file from the Documents directory that you supplied the name of as fileName. If you didn't call deleteFileFromDisk: multiple times, you didn't delete multiple files. Perhaps at some point you deleted the app. That would delete its entire sandbox and thus would take with it anything in the Documents directory. That sort of thing is perfectly normal during repeated testing.
unknown
d17531
val
Without knowing your markup, I'd suspect that your .yell-box-txt is in the same block as your .yell-button. So for markup like this: <div> <a class="yell-button">text button</a> <span class="yell-box-txt">text</a> </div> you'd want to use something like this: $('.yell-button').hover(function() { $(this).closest('div').find('.yell-box-txt').remove(); }); A: Classes are, by definition, accessors for, potentially, multiple elements. If you want to access this element on its own, consider using an id and accessing it via $('#idname') A: $('.yell-button:first').hover(function(){ $('.yell-box-txt').remove(); }) Of course it'd be better to make sure to only use this class once. It would be even better to use an ID instead, which is supposed to be unique (of course it's up to you and you have to check your code for inconsistencies such as multiple elements with the same id) A: Example of using id and class JS $('.yell-button').hover(function(){ $('#box2.yell-box-txt').remove() }) HTML <div id ="box1" class="yell-box-txt">Text in box 1</div> <div id ="box2" class="yell-box-txt">Text in box 2</div> <div id ="box3" class="yell-box-txt">Text in box 3</div> A: As others said, without an idea of your markup it's difficult to help you, however here are some ways to do it, depending on your markup: Ideally, you would be able to assign each button and associated text-box a unique identifier like yell-button-1 and make it remove the associated yell-box-txt-1 on hover. However, this method might be "difficult" to implement because you need to retrieve the ID # from the button. The second way to do this is to make use of jQuery traversing. Find where the text box is in relation to the button and navigate from the button to the text box using methods such as parent(), siblings(), etc. To make sure you only receive one element, append :first to your .yell-box-txt class. More info about jQuery Traversing. Hope this helps!
unknown
d17535
val
I'm guessing you have enabled the "Import Maven projects automatically" option. To disable it, go to Preferences... > Build, Execution, Deployment > Build Tools > Maven > Importing, then uncheck the option from there, like so: After doing so, it will be up to you to run the imports when you're ready. To import manually, right-click your project in the Project view, then click Maven > Reimport:
unknown
d17537
val
This is not a bug, it's the intended behavior. I updated the Hibernate User Guide to make it more obvious. The @Filter does not apply when you load the entity directly: Account account1 = entityManager.find( Account.class, 1L ); Account account2 = entityManager.find( Account.class, 2L ); assertNotNull( account1 ); assertNotNull( account2 ); While it applies if you use an entity query (JPQL, HQL, Criteria API): Account account1 = entityManager.createQuery( "select a from Account a where a.id = :id", Account.class) .setParameter( "id", 1L ) .getSingleResult(); assertNotNull( account1 ); try { Account account2 = entityManager.createQuery( "select a from Account a where a.id = :id", Account.class) .setParameter( "id", 2L ) .getSingleResult(); } catch (NoResultException expected) { expected.fillInStackTrace(); } So, as a workaround, use the entity query (JPQL, HQL, Criteria API) to load the entity.
unknown
d17543
val
Yes, a bot can do that. There's many ways of creating bots, and different methods will make most bots undetectable unless you have some really complex checks in place. I believe reCaptcha has a tonne of checks for example, ranging from the movement of the mouse, the react time of the user, user agents and so on and so forth. Bots can come in all shapes and forms, including some that might use Selenium to imitate a user using an actual browser, or they could even be written in a lower level and move the mouse and cause key presses on a system level. What it comes down to is how much energy/time you're willing to expend to make it harder for bots to do their thing. I doubt you'll ever get 100% accuracy on stopping bots. But yes, a bot can trigger a button press event, or even press the button directly like a normal user would
unknown
d17547
val
You can't change the PayPal payment notification sent as a result of your DoExpressCheckout call. You can, however, send them an email yourself in addition to it.
unknown
d17551
val
Unpivot using Power Query: * *Data --> Get & Transform --> From Table/Range *Select the country column * *Unpivot Other columns *Rename the resulting Attribute and Value columns to date and count *Because the Dates which are in the header are turned into Text, you may need to change the date column type to date, or, as I did, to date using locale M-Code Source = Excel.CurrentWorkbook(){[Name="Table2"]}[Content], #"Changed Type" = Table.TransformColumnTypes(Source,{{"country", type text}, {"20/01/2020", Int64.Type}, {"21/01/2020", Int64.Type}, {"22/01/2020", Int64.Type}}), #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"country"}, "date", "count"), #"Changed Type with Locale" = Table.TransformColumnTypes(#"Unpivoted Other Columns", {{"date", type date}}, "en-150") in #"Changed Type with Locale" A: Power Pivot is the best way, but if you want to use formulas: In F1 enter: =INDEX($A$2:$A$4,ROUNDUP(ROWS($1:1)/3,0)) and copy downward. In G1 enter: =INDEX($B$1:$D$1,MOD(ROWS($1:1)-1,3)+1) and copy downward. H1 enter: =INDEX($B$2:$D$4,ROUNDUP(ROWS($1:1)/3,0),MOD(ROWS($1:1)-1,3)+1) and copy downward The 3 in these formulas is because we have 3 dates in the original table.
unknown
d17553
val
I find that LINQ to SQL is much, much faster when I'm prototyping code. It just blows away any other method when I need something now. But there is a cost. Compared to hand-rolled stored procs, LINQ is slow. Especially if you aren't very careful as seemingly minor changes can suddenly make a single turn into 1+N queries. My recommendation. Use LINQ to SQL at first, then swtich to procs if you aren't getting the performance you need. A: A good question but a very controversial topic. This blog post from Frans Bouma from a few years back citing the pros of dynamic SQL (implying ORMs) over stored procedures sparked quite the fiery flame war. A: There was a great discussion on this topic at DevTeach in Montreal. If you go to this URL: http://www.dotnetrocks.com/default.aspx?showNum=240 you will be able to hear two experts in the field (Ted Neward and Oren Eini) discuss the pros and cons of each approach. Probably the best answer you will find on a subject that has no real definite answer.
unknown
d17555
val
This question is rather vague but the API documentation should be able to help you here. https://developers.google.com/maps/documentation/api-picker Just pick out which API you need. It should be something like setLocation(Coordinates) in all of them.
unknown
d17565
val
well, you could try hacks like this.... ​$(':radio:disabled').removeAttr('disabled').click(function(){ this.checked=false; })​; this will select all disabled radio buttons and enabled it but when click, will not be checked... demo and on <select> you could do like, $('select:disabled').removeAttr('disabled').change(function(){ $(this).find('option').removeAttr('selected'); // this.value = this.defaultValue; // you may also try this.. }); A: Just replace them with your own more controllable HTML/CSS construct, à la Niceforms, et al. (with disabled or readonly attribute, as appropriate, as fallback). A: A suggestion rather an answer: you can associate an event with the state change of an element, and cancel the change. You can do it the same way as the validate tools which allows to enter only digits or only some characters in <input type="text" /> fields. See a StackOverflow post about this. Another solution is to put something in front of your controls. For example: <div style="position:absolute;width:200px;height:200px;"></div> <input type="radio" /> will make your radio button unclickable. The problem is that doing so will prevent the users to copy-paste text or using hyperlinks, if the <div/> covers the whole page. You can "cover" each control one by one, but it may be quite difficult to do.
unknown
d17573
val
FIRST You cannot do this struct Shelf{ int clothes; int books; }; struct Shelf b; b.clothes=5; b.books=6; In global scope You can assign value inside a function int main (void ) { b.clothes=5; b.books=6; } Or initializing values on declaration struct Shelf b = { .clothes = 5, .books = 6 }; Moreover as you can see b is not a pointer so using -> is not correct: use . to access members of struct. SECOND Your struct has a pointer member book struct Shelf{ int clothes; int *books; }; What you can do is to set it to the address of another variable, like int book = 6; struct Shelf b = { .clothes = 5, .books = &book }; Or allocate memory for that pointer like int main (void ) { b.clothes=5; b.books=malloc(sizeof(int)); if (b.books != NULL) { *(b.books) = 6; } } BTW I guess you want an array of books, so int main (void ) { b.clothes=5; b.books=malloc(sizeof(int) * MAX_N_OF_BOOKS); if (b.books != NULL) { for (int i=0; i<MAX_N_OF_BOOKS; i++) b.books[i] = 6; } } COMPETE TEST CODE #include <stdio.h> #include <stdlib.h> struct Shelf { int clothes; int *books; }; int main(void) { struct Shelf b; b.clothes = 5; b.books = malloc(sizeof(int)); if (b.books != NULL) { *(b.books) = 6; } printf ("clothes: %d\n", b.clothes); printf ("book: %d\n", *(b.books) ); } OUTPUT clothes: 5 book: 6 A: b is a struct, not a pointer, so -> is not correct. It's like doing (*b).books, which is wrong. struct Shelf{ int clothes; int *books; }; One data member of the struct is a pointer, however: struct Shelf b; is not a pointer, it is just a struct as I said before. As for your question in comment: b.clothes=5; is correct. Also something like this would be ok: int number = 6; b.books = &number; A: -> operator used to access of member of struct via pointer. b is not dynamically allocated so b->books=6; is wrong. You should first allocate memory for member books and then dereference it. b.books = malloc(sizeof(int)); *(b.books)= 6;
unknown
d17577
val
Roman Nurik posted an answer here: https://plus.google.com/111335419682524529959/posts/QJcExn49ZrR For performance. When the settings activity loads of the watch first shows up, I didn't want to wait for an IPC call to complete before showing anything For a detailed description checkout my medium post.
unknown
d17583
val
SIMD is meant to work on multiple small values at the same time, hence there won't be any carry over to the higher unit and you must do that manually. In SSE2 there's no carry flag but you can easily calculate the carry as carry = sum < a or carry = sum < b like this. Worse yet, SSE2 doesn't have 64-bit comparisons either, so you must use some workaround like the one here Here is an untested, unoptimized C code based on the idea above: inline bool lessthan(__m128i a, __m128i b){ a = _mm_xor_si128(a, _mm_set1_epi32(0x80000000)); b = _mm_xor_si128(b, _mm_set1_epi32(0x80000000)); __m128i t = _mm_cmplt_epi32(a, b); __m128i u = _mm_cmpgt_epi32(a, b); __m128i z = _mm_or_si128(t, _mm_shuffle_epi32(t, 177)); z = _mm_andnot_si128(_mm_shuffle_epi32(u, 245),z); return _mm_cvtsi128_si32(z) & 1; } inline __m128i addi128(__m128i a, __m128i b) { __m128i sum = _mm_add_epi64(a, b); __m128i mask = _mm_set1_epi64(0x8000000000000000); if (lessthan(_mm_xor_si128(mask, sum), _mm_xor_si128(mask, a))) { __m128i ONE = _mm_setr_epi64(0, 1); sum = _mm_add_epi64(sum, ONE); } return sum; } As you can see, the code requires many more instructions and even after optimizing it may still be much longer than a simple 2 ADD/ADC pair in x86_64 (or 4 instructions in x86) SSE2 will help though, if you have multiple 128-bit integers to add in parallel. However you need to arrange the high and low parts of the values properly so that we can add all the low parts at once, and all the high parts at once See also * *practical BigNum AVX/SSE possible? *Can long integer routines benefit from SSE?
unknown
d17585
val
Check for window focus: var window_focus; $(window).focus(function() { window_focus = true; }).blur(function() { window_focus = false; }); Check if location.host matches specified domain and window is focused: if((location.host == "example.com")&&(window_focus == true)) { //window is focused and on specified domain for that website. //sounds, notifications, etc. here } Not completely sure if this is what you mean, but I hope it helps.
unknown
d17587
val
In general, the best way to record something like this is to attach it to the RequestHandler instance. For logging, you can override Application.log_request, which has access to the handler. You may need to pass either the request ID or the RequestHandler instance around to other parts of your code if you need to use this in multiple places. It is possible but tricky to use StackContext as something like a threading.Local if you really need this to be pervasive, but explicitly passing it around is probably best.
unknown
d17595
val
Here's a nice solution that works great for iOS 8 and iOS 7 on iPhone and iPad. You simply detect if there is a split view controller and if so, check if it's collapsed or not. If it's collapsed you know only one view controller is on screen. Knowing that info you can do anything you need to. //remove right bar button item if more than one view controller is on screen if (self.splitViewController) { if ([UISplitViewController instancesRespondToSelector:@selector(isCollapsed)]) { if (!self.splitViewController.collapsed) { self.navigationController.navigationBar.topItem.rightBarButtonItem = nil; } } else { self.navigationController.navigationBar.topItem.rightBarButtonItem = nil; } }
unknown
d17601
val
TypeScript will warn you if you try to pass unknown props. Eslint will warn you if you have unused variables, imports ... with rules like: * *no-unused-expressions *no-unused-vars *react/no-unused-prop-types *unused-imports
unknown
d17603
val
Update: To answer your question about type inference: The initializer list constructor of vector<string> takes an initializer_list<string>. It is not templated, so nothing happens in terms of type inference. Still, the type conversion and overload resolution rules applied here are of some interest, so I'll let my initial answer stand, since you have accepted it already: Original answer: At first, the compiler only sees the initializer list {"one","two","three"}, which is only a list of initializers, not yet an object of the type std::initializer_list. Then it tries to find an appropiate constructor of vector<string> to match that list. How it does that is a somewhat complicated process you would do best to look up in the standard itself if you are interested in the exact process. Therefore, the compiler decides to create an actual object of std::initializer_list<string> from the initializer list, since the implicit conversion from the char*'s to std::strings makes that possible. Another, maybe more interesting example: std::vector<long> vl1{3}; std::vector<string> vs1{3}; std::vector<string> vs2{0}; What do these do? * *The first line is relatively easy. The initializer list {3} can be converted into a std::initializer_list<long> analogous to the {"onm", "two", "three"} example above, so you get a vector with a single element, which has value 3. *The second line is different. It constructs a vector of 3 empty strings. Why? Because an initializer list {3} can by no means be converted into an std::initializer_list<string>, so the "normal" constructor std::vector<T>::vector(size_t, T = T()) kicks in and gives three default-constructed strings. *Well this one should be roughly the same as the second, right? It should give an empty vector, in other words, with zero default-constructed strings. WRONG!. The 0 can be treated as a nullpointer constant, and validates the std::initializer_list<string>. Only this time the single string in that list gets constructed by a nullpointer, which is not allowed, so you get an exception. A: There is no type inference because vector provide only a fully specialized constructor with the initializer list. We could add a template indirection to play with type deduction. The example below show that a std::initializer_list<const char*> is an invalid argument to the vector constructor. #include <string> #include <vector> std::string operator"" _s( const char* s, size_t sz ) { return {s, s+sz}; } template<typename T> std::vector<std::string> make_vector( std::initializer_list<T> il ) { return {il}; } int main() { auto compile = make_vector<std::string>( { "uie","uieui","ueueuieuie" } ); auto compile_too = make_vector<std::string>( { "uie"_s, "uieui", "ueueuieuie" } ); //auto do_not_compile = make_vector( { "uie","uieui","ueueuieuie" } ); } Live demo A: From http://en.cppreference.com/w/cpp/language/string_literal: The type of an unprefixed string literal is const char[] Thus things go this way: #include <iostream> #include <initializer_list> #include <vector> #include <typeinfo> #include <type_traits> using namespace std; int main() { std::cout << std::boolalpha; std::initializer_list<char*> v = {"one","two","three"}; // Takes string literal pointers (char*) auto var = v.begin(); char *myvar; cout << (typeid(decltype(*var)) == typeid(decltype(myvar))); // true std::string ea = "hello"; std::initializer_list<std::string> v2 = {"one","two","three"}; // Constructs 3 std::string objects auto var2 = v2.begin(); cout << (typeid(decltype(*var2)) == typeid(decltype(ea))); // true std::vector<std::string> vec(v2); return 0; } http://ideone.com/UJ4a0i
unknown
d17607
val
From BigQuery docs which says it seems that no error is returned when table exists: The CREATE TABLE IF NOT EXISTS DDL statement creates a table with the specified options only if the table name does not exist in the dataset. If the table name exists in the dataset, no error is returned, and no action is taken. Answering your question, DDL is supported from API which is also stated in doc, to do this: Call the jobs.query method and supply the DDL statement in the request body's query property.
unknown
d17611
val
(Question answered in the comments. See Question with no answers, but issue solved in the comments (or extended in chat) ) @WeloSefer wrote: maybe this can help you get started ... I have never worked with jsoup nor pdfbox so I am no help but I sure will try pdfbox since I've been testing itextpdf reader for extracting texts. The OP wrote: Thanks, that is what I was looking for - it works now :) this problem is solved - working code is here http://thottingal.in/blog/2009/06/24/pdfbox-extract-text-from-pdf/
unknown
d17613
val
Okay.. The code in your question seems right! However, you can still try these configuration directives in your .htaccess file: RewriteEngine on RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ RewriteRule ^(.*)$ http://theexample.com/$1 But first, make sure that there's an Apache HTTP Server with mod_rewrite in your web host.
unknown
d17615
val
Quick answer Your Main method and your task run in parallel, and the Main method does not wait the task to finish. In release mode, the task is "lucky". It finishes before Main. Not in debug mode. In both case the execution is random. The fact they run in parallel explain why your can't predict the order of the printed lines. Explanations A Task is a thread that comes from the thread pool, so they are background threads. The process running your code (which consist of all your threads) does not wait for background threads to finish in order to terminate. The process only wait that foreground threads have finished. Then you may want to use the Thread class because they are foreground by default. But using Task is easier. So @John Wu's comment is totally relevant: A task is not guaranteed to finish unless you await it or call Wait or Result or do something else to wait for it You simply want to add at the end of your code: task.Wait(); However you'll never be able to predict the order of the printed lines, because the threads run in parallel.
unknown
d17617
val
if image uploads to '/uploads' folder then try like app.use('/uploads', express.static(process.cwd() + '/uploads')) A: __dirname gives you the directory name of entry point file. I don't know where is your entry point file in your application, but that's where you have to start. By the way, I advise you to use the "join" function of the "path" module to concatenate the path so as it works on linux or window filesystem. A: I found a solution by Quora here, thanks to everyone who helped :) : link
unknown
d17619
val
If you can call MyScript (as opposed to ./MyScript), obviously the current directory (".") is part of your PATH. (Which, by the way, isn't a good idea.) That means you can call MyScript in your script just like that: #!/bin/bash mydir=My/Folder/ cd $mydir echo $(pwd) MyScript As I said, ./MyScript would be better (not as ambiguous). See Michael Wild's comment about directory separators. Generally speaking, Bash considers everything that does not resolve to a builtin keyword (like if, while, do etc.) as a call to an executable or script (*) located somewhere in your PATH. It will check each directory in the PATH, in turn, for a so-named executable / script, and execute the first one it finds (which might or might not be the MyScript you are intending to run). That's why specifying that you mean the very MyScript in this directory (./) is the better choice. (*): Unless, of course, there is a function of that name defined. A: #!/bin/bash mydir=My/Folder/ cd $mydir echo $(pwd) MyScript A: I would rather put the name in quotes. This makes it easier to read and save against mistakes. #!/bin/bash mydir="My Folder" cd "$mydir" echo $(pwd) ./MyScript A: Your nickname says it all ;-) When a command is entered at the prompt that doesn't contain a /, Bash first checks whether it is a alias or a function. Then it checks whether it is a built-in command, and only then it starts searching on the PATH. This is a shell variable that contains a list of directories to search for commands. It appears that in your case . (i.e. the current directory) is in the PATH, which is generally considered to be a pretty bad idea. If the command contains a /, no look-up in the PATH is performed. Instead an exact match is required. If starting with a / it is an absolute path, and the file must exist. Otherwise it is a relative path, and the file must exist relative to the current working directory. So, you have two acceptable options: * *Put your script in some directory that is on your PATH. Alternatively, add the directory containing the script to the PATH variable. *Use an absolute or relative path to invoke your script.
unknown
d17623
val
def _cleanup(): # clean it up return cleanup = _cleanup try: # stuff except: # handle it else: cleanup = lambda: None cleanup() A: The most clear way I can think of is do exactly the opposite of else: do_cleanup = True try: fn() except ErrorA as e: ... do something unique ... except ErrorB as e: ... do something unique ... except ErrorC as e: ... do something unique ... else: do_cleanup = False if do_cleanup: cleanup() If the code is enclosed and lets itself be done, you can simplify it by returning or breaking in the else. A: How about catching all the exceptions with one except clause and dividing up the different parts of your handling with if/elif blocks: try: fn() except (ErrorA, ErrorB, ErrorC) as e: if isinstance(e, ErrorA): ... do something unique ... elif isinstance(e, ErrorB): ... do something unique ... else: # isinstance(e, ErrorC) ... do something unique ... cleanup()
unknown
d17625
val
The type-checking is a bit weak, the annotations works as long you annotate your code but a more robust way can be achieved by using inspect from the standard library: it provides full access to frame, ... and everything you may need. In this case with inspect.signature can be used to fetch the signature of the original function to get a the original order of the parameters. Then just regroup the parameters and pass the final group back to the original function. More details in the comments. from inspect import signature def wrapper(func): def f(*args, **kwargs): # signature object sign = signature(func) # use order of the signature of the function as reference order = order = dict.fromkeys(sign.parameters) # update first key-values order.update(**kwargs) # update by filling with positionals free_pars = (k for k, v in order.items() if v is None) order.update(zip(free_pars, args)) return func(**order) return f @wrapper def foo(a, b, c, d): print(f"{a} {b} {c} {d}") foo(10, 12.5, 14, 5.2) #10 12.5 14 5.2 foo(10, 12.5, d=5.2, c=14) #10 12.5 14 5.2 The code is annotations compatible: @wrapper def foo(a: int, b: float, c: int, d: float) -> None: print(f"{a} {b} {c} {d}") The annotation's way, no imports required: It is a copy past of the above code but using __annotations__ attribute to get the signature. Remember that annotations may or may not have an annotation for the output def wrapper(func): def f(*args, **kwargs): if not func.__annotations__: raise Exception('No clue... inspect or annotate properly') params = func.__annotations__ # set return flag return_has_annotation = False if 'return' in params: return_has_annotation = True # remove possible return value return_ = params.pop('return', None) order = dict.fromkeys(params) order.update(**kwargs) free_pars = (k for k, v in order.items() if v is None) order.update(zip(free_pars, args)) # update with return annotation if return_has_annotation: func.__annotations__ = params | {'return': return_} return func(**order) return f @wrapper def foo(a: int, b: float, c: int, d: float) -> None: print(f"{a} {b} {c} {d}") A: The first thing to be careful of is that key word arguments are implemented because order does not matter for them and are intended to map a value to a specific argument by name at call-time. So enforcing any specific order on kwargs does not make much sense (or at least would be confusing to anyone trying to use your decorater). So you will probably want to check for which kwargs are specified and remove the corresponding argument types. Next if you want to be able to check the argument types you will need to provide a way to tell your decorator what types you are expected by passing it an argument (you can see more about this here). The only way to do this is to pass a dictionary mapping each argument to the expected type: @wrapper({'a': int, 'b': int, c: float, d: int}) def f(a, b, c=6.0, d=5): pass def wrapper(types): def inner(func): def wrapped_func(*args, **kwargs): # be careful here, this only works if kwargs is ordered, # for python < 3.6 this portion will not work expected_types = [v for k, v in types.items() if k not in kwargs] actual_types = [type(arg) for arg in args] # substitute these in case you are dead set on checking for key word arguments as well # expected_types = types # actual_types = [type(arg) for arg in args)] + [type(v) for v in kwargs.items] if expected_types != actual_types: raise TypeError(f"bad argument types:\n\tE: {expected_types}\n\tA: {actual_types}") func(*args, **kwargs) return wrapped_func return inner @wrapper({'a': int, 'b': float, 'c': int}) def f(a, b, c): print('good') f(10, 2.0, 10) f(10, 2.0, c=10) f(10, c=10, b=2.0) f(10, 2.0, 10.0) # will raise exception Now after all of this, I want to point out that this is functionality is probably largely unwanted and unnecessary in python code. Python was designed to be dynamically typed so anything resembling strong types in python is going against the grain and won't be expected by most. Next, since python 3.5 we have had access to the built-in typing package. This lets you specify the type that you expect to be receiving in a function call: def f(a: int, b: float, c: int) -> int: return a + int(b) + c Now this won't actually do any type assertions for you, but it will make it plainly obvious what types you are expecting, and most (if not all) IDEs will give you visual warnings that you are passing the wrong type to a function.
unknown
d17629
val
I think you should try setting it back to itself email = email.Replace(";", ","); A: String.Replace method returns new string. It doesn't change existing one. Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String. As Habib mentioned, using foreach with the current list gets a foreach iteration variable error. It is a read-only iteration. Create a new list and then add replaced values to it instead. Also you can use for loop for modifying existing list which keyboardP explained on his answer. List<string> newemailAddresses = new List<string>(); foreach (string email in emailAddresses) { newemailAddresses.Add(email.Replace(";", ",")); } return newemailAddresses; Be aware since strings are immutable types, you can't change them. Even if you think you change them, you actually create new strings object. A: As others have already mentioned that strings are immutable (string.Replace would return a new string, it will not modify the existing one) and you can't modify the list inside a foreach loop. You can either use a for loop to modify an existing list or use LINQ to create a new list and assign it back to existing one. Like: emailAddresses = emailAddresses.Select(r => r.Replace(";", ",")).ToList(); Remember to include using System.Linq; A: Strings are immutable so another string is returned. Try for(int i = 0; i < emailAddress.Count; i++) { emailAddress[i] = emailAddress[i].Replace(";", ","); } A foreach loop would not compile here because you're trying to change the iteration variable. You'd run into this issue. A: You should use somthing like: var tmpList = new List(); add each modified email address to the tmplist and when you are done, return the TmpList. In .NET strings are inmutable, that's why your code doesnt work.
unknown
d17635
val
You may need to adjust the values to higher numbers for larger files. Try doing following steps: Open Cpanel -> File manager Click search and type 'php.ini' -> Right click this file and choose edit. change value of following memory_limit post_max_size upload_max_filesize Adjust the values to higher numbers for larger files. Save and try again uploading. A: I also had this problem First you need to install a file manager plugin. Open file manager, search for a file with the name: .htaccess Edit this file, at the bottom add the following: php_value upload_max_filesize 1000M php_value post_max_size 2000M php_value memory_limit 3000M php_value max_execution_time 180 php_value max_input_time 180 Save and close Try uploading again, in my case worked. I followed the instructions from this video: https://www.youtube.com/watch?v=TnI_h-QjrWo
unknown
d17637
val
You can always write your own module to do it, but my recommendation is using the Rules module, and using several user roles. * *Any new user gets a "trial" role he registers. *Create the needed fields in the user profile *Create a rule which will change the user's role in case the field is filled (rule triggeres whenever user profile is updated). *Create a rule with cron that executes once a day, to suspend user account, and probably to send him a notification before doing so.
unknown
d17641
val
Try DBMS_METADATA_GET_DDL. enter link description here
unknown
d17645
val
I'd suggest a polymorphic many-to-many approach here so that icons are reusable and don't require a bunch of pivot tables, should you want icons on something other than a page. Schema::create('icons', function(Blueprint $table) { $table->increments('id'); $table->string('name'); }); Schema::create('iconables', function(Blueprint $table) { $table->integer('icon_id'); $table->integer('iconables_id'); $table->integer('iconables_type'); }); Now you just need to determine if the pages have an existing Icon. If they do, then hold reference to them so you can insert them: $pagesWithIcons = Page::whereNotNull('icon')->get(); At this point you need to define the polymorphic relations in your models: // icon class Icon extends Model { public function pages() { return $this->morphedByMany(Page::class, 'iconable'); } } // page class Page extends Model { public function pages() { return $this->morphToMany(Icon::class, 'iconable'); } } Now you just need to create the icons (back in our migration), and then attach them if they exist: $pagesWithIcons->each(function(Page $page) { $icon = Icon::firstOrNew([ 'name' => $page->icon }); $icon->pages()->attach($page); }); The above is creating an Icon if it doesn't exist, or querying for it if it does. Then it's attaching the page to that icon. As polymorphic many-to-many relationships just use belongsToMany() methods under the hood, you have all of the available operations at your leisure if this doesn't suite your needs. Finally, drop your icons column from pages, you don't need it. Schema::table('pages', function(Blueprint $table) { $table->dropColumn('icon'); }); And if you need to backfill support for only an individual icon (as the many-to-many will now return an array relationship), you may add the following to your page model: public function icon() { return $this->icons()->first(); } Apologies if typos, I did this on my phone so there may be some mistakes.
unknown
d17647
val
I found three problems: 1) the template(tableData) must be set to a DOM element, as in $("#output").html(template(tableData)); and 2) that the variable name inside the template must be data; and 3) the code that loads the template must be executed after the DOM is ready. Here is the complete and corrected code: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <link href="Content/kendo/2012.2.710/kendo.common.min.css" rel="stylesheet" /> <link href="Content/kendo/2012.2.710/kendo.default.min.css" rel="stylesheet" /> <script src="Scripts/jquery-1.8.2.min.js"></script> <script src="Scripts/kendo/2012.2.710/kendo.web.min.js"></script> <script type="text/javascript"> $(document).ready(function () { var template = kendo.template($("#javascriptTemplate").html()); var tableData = ["1", "2"]; $("#output").html(template(tableData)); }); </script> </head> <body> <form id="form1" runat="server"> <div id="output"></div> <script id="javascriptTemplate" type="text/x-kendo-template"> <table> # for (var i = 0; i < data.length; i++) { # <tr><td>#=data[i]#</td</tr> # } # </table> </script> </form> </body>
unknown
d17651
val
Your question is very nonspecific, but here is one way to do what you are looking for, assuming I understand what you are asking. Note that this may cause an undesirable offset in position which you will have to deal with in some way. Not knowing what point you want to scale the polygon about, these solutions assume the simplest circumstances. The reason for the square root in all of these formulas is that area tends to change with the square of linear scaling, just as volume does with the cube of linear scaling. For general polygon: A = sqrt(R) for each point in polygon: point.x := point.x * A point.y := point.y * A For circle: A = sqrt(R) circle.radius := circle.radius * A For rectangle in terms of width and height: A = sqrt(R) rect.w := rect.w * A rect.h := rect.h * A
unknown
d17657
val
Bijil, JRXML is a template that contains the format for the content that is shown on the report. And from what i understand the xml is containing the input data. How jasper reports work is, you create JASPER file by compiling the JRXML file (this can be done using iReport or through your java code). To this JASPER file you will attach a object from your java code that contain data for filling the JASPER. Please see this link for details Edited: iReport is a designer tool for creating jasper reports, I am not sure if there any tool that can convert xml to jrxml. jrxml will contain the syntax with respect to jasper report. What we used to do, were try to create a similar report(by comparing the look and feel) as the one client has given using iReport and get the final jrxml. Compile jrxml in iReport check the look and feel with the sample word doc with the generated sample report Then use the compiled jasper file in the application directly. The use of jasper has 2 advantages, * *you can use unicode characters in your report *you reduce the overhead of compiling your code every time before generating report. disadvantage * *you need to keep separate track of jrxml, to fix any defect on previous jasper file. A: Save your MS WORD file (Template) in report directory and using Apache POI, Do necessary edits to your template. Then save your file to any place you like. Apache POI tutorials Link 01: To print save your edited file in temp directory and call Desktop.getDesktop().print(file) using desktop Link 02: Wish you good luck.
unknown
d17659
val
For an external module with no exposed types and any values: declare module 'Foo' { var x: any; export = x; } This won't let you write foo.cls, though. If you're stubbing out individual classes, you can write: declare module 'Foo' { // The type side export type cls = any; // The value side export var cls: any; }
unknown
d17665
val
Your imports look like you are using Jackson 1.9.x which doesn't have a method getFactory() in ObjectMapper. There is a method getJsonFactory(), but you'd probably not need it. Just call mapper.configure( JsonGenerator.Feature.ESCAPE_NON_ASCII, true );
unknown
d17671
val
Here is the simple solution with toggleClass: $('.ShowHideClicker').on('click', function(){ $(this).next().toggleClass('hidden'); }); http://jsfiddle.net/LcYLY/ A: You should be using the .toggle() this way: JSFIDDLE and make sure you have included jQuery and jQuery UI in your header ("drop" is a jQuery UI feature) jQuery: $(document).ready(function(){ $('.ShowHideClicker').click(function(){ $('.ShowHideList').toggle('drop', 1000); }); }); CSS: .ShowHideList { display: none; }
unknown
d17673
val
Add the target attribute to open in new window: $("SeriesId").attr("target", "_blank");
unknown
d17675
val
You need to use event delegation for attaching events to dynamically added elements: $('body').on('click','.contactlist',function(e) { e.stopPropagation(); var sub = $('> ul', this); if(sub.length) { if(sub.is(':visible')) { sub.hide(); sub.removeClass('open'); } else { $('.contactlist .open').hide().removeClass('open'); sub.show(); sub.parents('ul:not(.contactlist)').addClass('open').show(); sub.addClass('open'); } } });
unknown
d17679
val
The errors warning: Exception condition detected on fd 536 and Remote communication error. Target disconnected.: No such file or directory. almost always mean that the remote target has died unexpectedly. You didn't mention if you are using standard gdbserver, or some other remote target, but if you start your remote target in a separate terminal, and then connect GDB and step through, you should notice that your remote target exits (crashes maybe?), and this will correspond to the time when GDB throws the above error. You should file a bug against whoever provides your remote target. If this is stock gdbserver, then that would be the GDB project itself, but if it is some other remote target, then you should approach them.
unknown
d17681
val
Ok, there's a much better way to do this, but since I'm on a phone that's dying and you have been waiting a year... var info = $("#div0").html(); // if Js in a php file you can do var info = <?php echo $logtext ?>; To bring it to JS $.get("phpfilehere.php", {info:info}, function(data){ alert(data); }); The mouseover function... $("#div0").on("mouseover", function(){ // my JS code above goes here }); PHP file: if(isset($_GET['info'])){ $log = $_GET['info']; // Put ur stuff here, make sure u only echo when u want ur php script to stop and be sent back to Ajax function as data var. // insert $log echo "test"; } else { echo "no get info supplied": } And here is a tool I made to teach people how to write prepared statements for SQL queries :) if you need it... http://wbr.bz/QueryPro/index.php?query_type=prepared_insert
unknown
d17685
val
Wrap your element(s) in a temp <div> and then get its .innerHTML. var select = document.createElement("select"), textDiv = document.createElement("div"), tempDiv = document.createElement("div"); tempDiv.appendChild(select); textDiv.innerHTML = data[i].text.replace(pattern, tempDiv.innerHTML); A: By using innerHTML, you're using markup. So one option is, just use markup (but more options follow): var textDiv = document.createElement("div"); textDiv.innerHTML = data[i].text.replace(pattern, "<select></select>"); Live example: var data = { 0: { text: "This is a <strong>test</strong> {0} Testing <em>1 2 3</em>" } }; var i = 0; var pattern = /\{0\}/i; var textDiv = document.createElement("div"); textDiv.innerHTML = data[i].text.replace(pattern, "<select></select>"); document.body.appendChild(textDiv); If you don't want to use markup, you can append the part of the string before the {0}, then the element, then the part of the string after the {0}: var select = document.createElement("select"), textDiv = document.createElement("div"), text = data[i].text, index = text.indexOf("{0}"); // No need for case-insensitivity if (index === -1) { index = text.length; } textDiv.innerHTML = text.substring(0, index); textDiv.appendChild(select); if (index < text.length) { textDiv.insertAdjacentHTML("beforeend", text.substring(index + 3)); } var data = { 0: { text: "This is a <strong>test</strong> {0} Testing <em>1 2 3</em>" } }; var i = 0; var select = document.createElement("select"), textDiv = document.createElement("div"), text = data[i].text, index = text.indexOf("{0}"); // No need for case-insensitivity if (index === -1) { index = text.length; } textDiv.innerHTML = text.substring(0, index); textDiv.appendChild(select); if (index < text.length) { textDiv.insertAdjacentHTML("beforeend", text.substring(index + 3)); } document.body.appendChild(textDiv); Or if the pattern has to be a regex: var select = document.createElement("select"), textDiv = document.createElement("div"), text = data[i].text, match = pattern.exec(text), index = match ? match.index : text.length; textDiv.innerHTML = text.substring(0, index); textDiv.appendChild(select); if (match) { textDiv.insertAdjacentHTML("beforeend", text.substring(index + match[0].length)); } var data = { 0: { text: "This is a <strong>test</strong> {0} Testing <em>1 2 3</em>" } }; var i = 0; var pattern = /\{0\}/i; var select = document.createElement("select"), textDiv = document.createElement("div"), text = data[i].text, match = pattern.exec(text), index = match ? match.index : text.length; textDiv.innerHTML = text.substring(0, index); textDiv.appendChild(select); if (match) { textDiv.insertAdjacentHTML("beforeend", text.substring(index + match[0].length)); } document.body.appendChild(textDiv); A: Here's the simplest solution. Use select.outerHTML var select = document.createElement("select"), textDiv = document.createElement("div"); textDiv.innerHTML = data[i].text.replace(pattern, select.outerHTML); and widely supported. Live example: var text = "This is a <strong>test</strong> {0} Testing <em>1 2 3</em>" var pattern = /\{0\}/i; var select = document.createElement("select"), textDiv = document.createElement("div"); textDiv.innerHTML = text document.body.appendChild(textDiv); setTimeout(function(){ textDiv.innerHTML = text.replace(pattern, select.outerHTML); }, 1000)
unknown
d17687
val
Your underscore.js version is too old. Try to use the new version (1.7): <script src="http://underscorejs.org/underscore.js"></script>
unknown
d17689
val
If the data must last as long as the application session lasts, then caching them as JSON objects would be suitable. You could use GSON to quickly convert them to your JAVA model, but the objects also sound simple enough to parse using Android's out of the box JSONObject class. If the data must persist beyond the application's session, you can still store them in the SharedPreferences as JSON objects. I wouldn't use SQLite, because the data doesn't sound heavy & complex. The data sounds small & light enough for caching or SharedPreferences based on the data's persistence.
unknown
d17691
val
You can create your own category method. Something like @interface NSString (Utilities) + (NSString *)stringWithFloat:(CGFloat)float @end @implementation NSString (Utilities) + (NSString *)stringWithFloat:(CGFloat)float { NSString *string = [NSString stringWithFormat:@"%f", float]; return string; } @end Edit Changed this to a class method and also changed the type from float to CGFloat. You can use it as: NSString *myFloat = [NSString stringWithFloat:2.1f]; A: You could use NSNumber NSString *myString = [[NSNumber numberWithFloat:myFloat] stringValue]; But there's no problem doing it the way you are, in fact the way you have in your question is better. A: float someVal = 22.3422f; NSNumber* value = [NSNumber numberWithFloat:someVal]; NSLog(@"%@",[value stringValue]); A: in a simple way NSString *floatString = @(myFloat).stringValue;
unknown
d17693
val
Here's an adaptation of yuk's answer using find: [ib, ia] = find(true(size(b, 1), size(a, 1))); needed = [a(ia(:), :), b(ib(:), :)]; This should be much faster than using kron and repmat. Benchmark a = [1 2 3; 4 5 6]; b = [7 8; 9 10]; tic for k = 1:1e3 [ib, ia] = find(true(size(b, 1), size(a, 1))); needed = [a(ia(:), :), b(ib(:), :)]; end toc tic for k = 1:1e3 needed = [kron(a, ones(size(b,1),1)), repmat(b, [size(a, 1), 1])]; end toc The results: Elapsed time is 0.030021 seconds. Elapsed time is 0.17028 seconds. A: Use a Kronecker product for a and repmat for b: [kron(a, ones(size(b,1),1)), repmat(b, [size(a, 1), 1])] ans = 1 2 3 7 8 1 2 3 9 10 4 5 6 7 8 4 5 6 9 10 A: It gives the desired result but you might need something else then array_merge if you have duplicated items. $a = array(array(1, 2, 3), array(4, 5, 6)); $b = array(array(7, 8), array(9, 10)); $acc = array_reduce($a, function ($acc, $r) use ($b) { foreach ($b as $br) { $acc []= array_merge($r, $br); } return $acc; }, array()); var_dump($acc); Edit: Sorry I've just noticed the "without loops" section. You can change the foreach to array_reduce to.
unknown
d17695
val
Here's a PoC that will rethrow any "possibly unhandled rejections". These will subsequently trigger Restify's uncaughtException event: var Promise = require('bluebird'); var restify = require('restify'); var server = restify.createServer(); server.listen(3000); Promise.onPossiblyUnhandledRejection(function(err) { throw err; }); server.get('/', function (req, res, next) { Promise.reject(new Error('xxx')); // no `.catch()` needed }); server.on('uncaughtException', function (req, res, route, err) { console.log('uncaught error', err); return res.send(500, 'foo'); });
unknown
d17697
val
No. You can create your own column with sequential values using an identity column. This is usually a primary key. Alternatively, when you query the table, you can assign a sequential number (with no gaps) using row_number(). In general, you want a column that specifies the ordering: select t.*, row_number() over (order by <ordering column>) as my_sequential_column from t;
unknown
d17699
val
You must disable preflight in your TailwindCSS configuration to prevent defaults overriding MUI styling: // tailwind.config.js module.exports = { corePlugins: { preflight: false, } } If you have not done so already, you should also follow MUI instructions for changing the CSS injection order if you are going to use external style sheets in order to reliably style MUI components using TailwindCSS.
unknown
d17705
val
filename users wouldn't point to the same object as filename users/. That is not true. In most filesystems, you cannot have a file named users and a directory named users in the same parent directory. cd users and cd users/ have the same result. A: Short answer: they may only identify the same resource if one redirects to the other. URI's identify resources, but they do so differently depending on the response status code to a GET request in HTTP. If one returns a 3xx to the other, then the two URI's identify the same resource. If the two resources each return a 2xx code, then the URI's identify different resources. They may return the same response in reply to a GET request, but they are not therefore the same resource. The two resources may even map to the same handler to produce their reply, but they are not therefore the same resource. To quote Roy Fielding: The resource is not the storage object. The resource is not a mechanism that the server uses to handle the storage object. The resource is a conceptual mapping -- the server receives the identifier (which identifies the mapping) and applies it to its current mapping implementation (usually a combination of collection-specific deep tree traversal and/or hash tables) to find the currently responsible handler implementation and the handler implementation then selects the appropriate action+response based on the request content. So, should /users and /users/ return the same response? No. If one does not redirect to the other, then they should return different responses. However, this is not itself a constraint of REST. It is a constraint, however, which makes networked systems more scalable: information that is duplicated in multiple resources can get out of sync (especially in the presence of caches, which are a constraint of REST) and lead to race conditions. See Pat Helland's Apostate's Opinion for a complete discussion. Finally, clients may break when attempting to resolve references relative to the given URI. The URI spec makes it clear that resolving the relative reference Jerry/age against /users/ results in /users/Jerry/age, while resolving it against /users (no trailing slash) results in /Jerry/age. It's amazing how much client code has been written to detect and correct the latter to behave like the former (and not always successfully). For any collection (which /users/ often is), I find it best to always emit /users/ in URI's, redirect /users to /users/ every time, and serve the final response from the /users/ resource: this keeps entities from getting out of sync and makes relative resolution a snap on any client. A: There are some nuances on this, while "users" represent one resource while "users/" should represent a set of resources, or operations on all resources "users"... But there does not seem to exist a "standard" for this issue. There is another discussion on this, take a look here: https://softwareengineering.stackexchange.com/questions/186959/trailing-slash-in-restful-api A: Technically they are not the same. But a request for /users will probably cause a redirect to /users/ which makes them semantically equal. In terms of JAX-RS @Path, they can both be used for the same path.
unknown
d17709
val
Are you just trying to evaluate an arbitrary expression inside a double quoted string? Then maybe you're thinking of print "@{[$this->method]}"; There is also a trick to call the method in scalar context, but the syntax is a little less clean. print "${\($this->method)}"; A: Well, if $this->method outputs a string or a number (like PHP, Perl can automatically convert numbers to strings when required), then you can do print $this->method . "\n";. If $this->method outputs a data structure (eg an array reference or a hash reference), you can use Data::Dumper to look at the structure of the data. Basically, print Dumper($foo) is the Perl equivalent of PHP's var_dump($foo). What are you trying to do, exactly? A: If $this->method is returning a string, you can do this: print $this->method . "\n"; without quotes. That will print your string. Sometimes, that can lead to a clumsy looking statement: print "And we have " . $this->method . " and " . $that->method . " and " . $there->method . "\n"; In that case you can use a little programming trick of: print "And we have @{[$this->method]} and @{[that->method]} and @{[$their->method]}\n"; Surrounding a function with @{[]} prints out the function's value. Someone explained this to me once, but I can't remember why it works.
unknown
d17711
val
Replace text from txt for each line and save as Could somebody help me with the following? I tried making it on my own, but all I could do is open a txt and replace a static word with static word. VBA script: Open and Read first line of ThisVbaPath.WordsToUse.txt Open and Find USER_INPUT in ThisVbaPath.BaseDoc.docx (or txt) Replace all occurrence of USER_INPUT with first line from WordsToUse.txt Save BaseDoc.docx as BaseDoc&First_Line.docx Close all Go next line and do same, but don't ask for user input, use previous one If error go next When done show if there were any errors (unlikely I guess) I would use it about weekly for 150-ish lines. Thanks! A: I think something like this should work? Sub test() Dim text, textReplace, findMe As String findMe = InputBox("What Text To Find?") Open "C:\Excel Scripts\test.txt" For Input As #1 Open "C:\Excel Scripts\test2.txt" For Input As #2 Open "C:\Excel Scripts\output.txt" For Output As #3 While Not EOF(1) Line Input #1, text While Not EOF(2) Line Input #2, textReplace Write #3, Replace(text, findMe, textReplace) Wend Wend Close #1 Close #2 Close #3 End Sub A: Sub TextFile_FindReplace() Dim TextFile As Integer Dim FilePath As String Dim FileContent As String FilePath = Application.ActiveWorkbook.Path & "\NEWTEST.txt" TextFile = FreeFile Open FilePath For Input As TextFile FileContent = Input(LOF(TextFile), TextFile) FileContent = Replace(FileContent, "FOO", "BAR") Print #TextFile, FileContent Close TextFile End Sub
unknown
d17713
val
If I don't misunderstood your requirements then you can try this way with json_normalize. I just added the demo for single json, you can use apply or lambda for multiple datasets. import pandas as pd from pandas.io.json import json_normalize df = {":@computed_region_amqz_jbr4":"587",":@computed_region_d3gw_znnf":"18",":@computed_region_nmsq_hqvv":"55",":@computed_region_r6rf_p9et":"36",":@computed_region_rayf_jjgk":"295","arrests":"1","county_code":"44","county_code_text":"44","county_name":"Mifflin","fips_county_code":"087","fips_state_code":"42","incident_count":"1","lat_long":{"type":"Point","coordinates":[-77.620031,40.612749]}} df = pd.io.json.json_normalize(df) df_modified = df[['county_name', 'incident_count', 'lat_long.type']] df_modified['lat'] = df['lat_long.coordinates'][0][0] df_modified['lng'] = df['lat_long.coordinates'][0][1] print(df_modified) A: Here is how you can do it as well: df1 = pd.io.json.json_normalize(df) pd.concat([df1, df1['lat_long.coordinates'].apply(pd.Series) \ .rename(columns={0: 'lat', 1: 'long'})], axis=1) \ .drop(columns=['lat_long.coordinates', 'lat_long.type'])
unknown
d17715
val
Try GNU Obstacks. From Wikipedia: In the C programming language, Obstack is a memory-management GNU extension to the C standard library. An "obstack" is a "stack" of "objects" (data items) which is dynamically managed. Code example from Wikipedia: char *x; void *(*funcp)(); x = (char *) obstack_alloc(obptr, size); /* Use the macro. */ x = (char *) (obstack_alloc) (obptr, size); /* Call the function. */ funcp = obstack_alloc; /* Take the address of the function. */ IMO what makes Obstacks special: It does not need malloc() nor free(), but the memory still can be allocated «dynamically». It is like alloca() on steroids. It is also available on many platforms, since it is a part of the GNU C Library. Especially on embedded systems it might make more sense to use Obstacks instead of malloc(). A: See Wikipedia's article about stacks. A: Quick-and-dirty untested example. Uses a singly-linked list structure; elements are pushed onto and popped from the head of the list. #include <stdlib.h> #include <string.h> /** * Type for individual stack entry */ struct stack_entry { char *data; struct stack_entry *next; } /** * Type for stack instance */ struct stack_t { struct stack_entry *head; size_t stackSize; // not strictly necessary, but // useful for logging } /** * Create a new stack instance */ struct stack_t *newStack(void) { struct stack_t *stack = malloc(sizeof *stack); if (stack) { stack->head = NULL; stack->stackSize = 0; } return stack; } /** * Make a copy of the string to be stored (assumes * strdup() or similar functionality is not * available */ char *copyString(char *str) { char *tmp = malloc(strlen(str) + 1); if (tmp) strcpy(tmp, str); return tmp; } /** * Push a value onto the stack */ void push(struct stack_t *theStack, char *value) { struct stack_entry *entry = malloc(sizeof *entry); if (entry) { entry->data = copyString(value); entry->next = theStack->head; theStack->head = entry; theStack->stackSize++; } else { // handle error here } } /** * Get the value at the top of the stack */ char *top(struct stack_t *theStack) { if (theStack && theStack->head) return theStack->head->data; else return NULL; } /** * Pop the top element from the stack; this deletes both * the stack entry and the string it points to */ void pop(struct stack_t *theStack) { if (theStack->head != NULL) { struct stack_entry *tmp = theStack->head; theStack->head = theStack->head->next; free(tmp->data); free(tmp); theStack->stackSize--; } } /** * Clear all elements from the stack */ void clear (struct stack_t *theStack) { while (theStack->head != NULL) pop(theStack); } /** * Destroy a stack instance */ void destroyStack(struct stack_t **theStack) { clear(*theStack); free(*theStack); *theStack = NULL; } Edit It would help to have an example of how to use it: int main(void) { struct stack_t *theStack = newStack(); char *data; push(theStack, "foo"); push(theStack, "bar"); ... data = top(theStack); pop(theStack); ... clear(theStack); destroyStack(&theStack); ... } You can declare stacks as auto variables, rather than using newStack() and destroyStack(), you just need to make sure they're initialzed properly, as in int main(void) { struct stack_t myStack = {NULL, 0}; push (&myStack, "this is a test"); push (&myStack, "this is another test"); ... clear(&myStack); } I'm just in the habit of creating pseudo constructors/destructors for everything.
unknown
d17717
val
Route matching is powered by https://github.com/pillarjs/path-to-regexp . You can use their documentation to look for a similar case. My first guess would be to try escaping the space: path: '/:NAS\ ID'
unknown
d17719
val
Let us look at the four situations for an element in your list (as we iterate through them). If (for terseness) we take old to be the item that is moving's old position and new to be its new position we have the following cases for an item in your list (draw them out on paper to make this clear). * *the current item is the one to be moved: move it directly *the current item's order is < new and < old: don't move it *the current item's order is ≥ new and < old: move it right *the current item's order is ≤ new and > old: move it left *the current item's order is > new and > old: don't move it When we start enumerating, we know the where the item to be moved will end up (at new) but we do not know where it has come from (old). However, as we start our enumeration at the beginning of the list, we know at each step that it must be further down in the list until we have actually seen it! So we can use a flag (seen) to say whether we have seen it yet. So seen of false means < old whilst true means >= old. bool seen = false; for (int i = 0; i < items.Length; i++) { if (items[i].ID == inputID) { items[i].Order = inputNewPosition; seen = true; } } This flag tells us whether the current item is >= old. So now can start shunting stuff around based on this knowledge and the above rules. (So new in the above discussion is inputNewPosition and whether we are before or after old we represent with our seen variable.) bool seen; for (int i = 0; i < items.Count; i++) { if (items[i].ID == inputID) // case 1 { items[i].Order = inputNewPosition; seen = true; } else if (seen) // cases 4 & 5 { if (items[i].Order <= inputNewPosition) // case 4 { items[i].Order--; // move it left } } else // case 2 & 3 { if (items[i].Order >= inputNewPosition) // case 3 { items[i].Order++; // move it right } } } Having said all of that, it is probably simpler to sort the collection on each change. The default sorting algorithm should be quite nippy with a nearly sorted collection. A: Your question isn't very clear, but for the requirements you'd likely be best off doing an event on the object that contains Order, and possibly having a container object which can monitor that. However I'd suspect that you might want to rethink your algorithm if that's the case, as it seems a very awkward way to deal with the problem of displaying in order. That said, what is the problem requirement? If I switch the order of item #2 to #5, what should happen to #3? Does it remain where it is, or should it be #6? A: This is how I solved the problem but I think there might be a more clever way out there.. The object that I need to update are policy workload items. Each one of these has a priority associated. There cannot be a policy workload item with the same priority. So when a user updates the priority the other priorities need to shift up or down accordingly. This handler takes a request object. The request has an id and a priority. public class UpdatePriorityCommand { public int PolicyWorkloadItemId { get; set; } public int Priority { get; set; } } This class represents the request object in the following code. //Get the item to change priority PolicyWorkloadItem policyItem = await _ctx.PolicyWorkloadItems .FindAsync(request.PolicyWorkloadItemId); //Get that item's priority and assign it to oldPriority variable int oldPriority = policyItem.Priority.Value; //Get the direction of change. //-1 == moving the item up in list //+1 == moving the item down in list int direction = oldPriority < request.Priority ? -1 : 1; //Get list of items to update... List<PolicyWorkloadItem> policyItems = await _ctx.PolicyWorkloadItems .Where(x => x.PolicyWorkloadItemId != request.PolicyWorkloadItemId) .ToListAsync(); //Loop through and update values foreach(var p in policyItems) { //if moving item down in list (I.E. 3 to 1) then only update //items that are less than the old priority. (I.E. 1 to 2 and 2 to 3) //items greater than the new priority need not change (i.E. 4,5,6... etc.) //if moving item up in list (I.E. 1 to 3) //items less than or equal to the new value get moved down. (I.E. 2 to 1 and 3 to 2) //items greater than the new priority need not change (i.E. 4,5,6... etc.) if( (direction > 0 && p.Priority < oldPriority) || (direction < 0 && p.Priority > oldPriority && p.Priority <= request.Priority) ) { p.Priority += direction; _ctx.PolicyWorkloadItems.Update(p); } } //finally update the priority of the target item directly policyItem.Priority = request.Priority; //track changes with EF Core _ctx.PolicyWorkloadItems.Update(policyItem); //Persist changes to database await _ctx.SaveChangesAsync(cancellationToken);
unknown
d17721
val
There seems to be no reason to JOIN the users table. You can get all public and your own private templates with SELECT `templates`.`id`, `templates`.`name`, `templates`.`description`, `templates`.`datetime`, FROM `templates` WHERE `templates`.`user_id` = 42 OR `templates`.`private` = 0 I am assuming that the id of the current user is 42, substitute this with the real value when constructing the query.
unknown
d17725
val
The first capture is greedy, which means that it will capture everything up to the last / (rather than the first / as you intended). You could make the capture non-greedy by using *? instead of *. But if the captures are not intended to capture /, you should use the [^/] character class instead. For example: rewrite ^/ap/([^/]*)/([^/]*)/?$ /ap/index.php?server=$1&guild=$2 last; The trailing / has also been made optional. See this useful resource on regular expressions.
unknown
d17727
val
I ended up creating the form (document.createElement) on page load with jquery, submitting it (.trigger("click")) and then removing it (.remove()). In addition I obfuscated the jquery code with the tool found here Crazy Obfuscation as @André suggested. That way user cannot see the htaccess username and password in Page Source nor find it using "inspect element" or firebug. A: Personally, I need a bit more information to clearly deduct a solution for your issue, I hope you can give me that. However, have you tried simply .remove()ing the form after submission? That way it gets submitted on page load and then gets removed so by the time the page loads and the user clicks view source, he will not be able to see it. He can, of course, disable JS for example, or any other workaround, but this is a very quick fix with the amount of information we have. A: You can not directly hide values in 'view source'. Similarly when the form is being submitted, using tools like 'fiddler' the user could view the values. If you want to really hide them what you can do is never have those values show in the form. You could try techniques like encrypting those values on server or something if it never needs to be displayed to the user in the web page.
unknown
d17733
val
This may not be the most elegant solution, but I would try (for a test) disabling firePHP and use instead a logging tool such as log4php and have it log your exceptions where and when they might be thrown. Thus, if you're not doing so already.. use try and catch blocks and in the catch blocks, log your exception to a file that you'd declare in the config/instantiation of log4php. Just a suggestion.
unknown