_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d15501
val
How to drag (and drop) an image back and forth between two elements: <!DOCTYPE HTML> <html> <head> <style> #div1, #div2 { float: left; width: 100px; height: 35px; margin: 10px; padding: 10px; border: 1px solid black; } </style> <script> function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } </script> </head> <body> <h2>Drag and Drop</h2> <p>Drag the image back and forth between the two div elements.</p> <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"> <img src="img_w3slogo.gif" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31"> </div> <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div> </body> </html> i am not sure if this is what you are looking for if not, please provide an example of what you need or you can refer to this link for dragging multiple items: https://codepen.io/SitePoint/pen/gbdwjj
unknown
d15502
val
Python's itertools module has a tool that does what you need: import itertools p = itertools.permutations([0, 1, 2, 3]) p_as_list = list(p) Edit: As your needs are fairly specific you could benefit from having your own function that does something alike this one: (note I haven't got the implementation down just yet, maybe someone might refine this): def magic_permutations (*args): lists = [] larg = len(args) for i in range(larg): lists.append([]) i = 0 for nums in args: for num in nums: if i >= larg: i = 0 lists[i].append(num) i += 1 return lists Edit: I misunderstood your question the first time, so I'll apologize for that. I'll however leave this be. A: Use itertools.product with a dynamically-specified list of iterators: vals = [1,3,2] for item in itertools.product(*[range(x+1) for x in vals]): print item Output: (0, 0, 0) (0, 0, 1) (0, 0, 2) (0, 1, 0) (0, 1, 1) (0, 1, 2) (0, 2, 0) (0, 2, 1) (0, 2, 2) (0, 3, 0) (0, 3, 1) (0, 3, 2) (1, 0, 0) (1, 0, 1) (1, 0, 2) (1, 1, 0) (1, 1, 1) (1, 1, 2) (1, 2, 0) (1, 2, 1) (1, 2, 2) (1, 3, 0) (1, 3, 1) (1, 3, 2) A: To obtain the exact sequence shown in the question (albeit in a different order, but that's not a problem) use this function: import itertools as it def combs(lst): return [list(e) for e in it.product(*(range(x+1) for x in lst))] The result is as expected: combs([1, 3, 2]) => [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 2, 0], [0, 2, 1], [0, 2, 2], [0, 3, 0], [0, 3, 1], [0, 3, 2], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 1, 2], [1, 2, 0], [1, 2, 1], [1, 2, 2], [1, 3, 0], [1, 3, 1], [1, 3, 2]] A: for ii in itertools.product(range(2),range(4),range(3): print ii (0, 0, 0) (0, 0, 1) (0, 0, 2) (0, 1, 0) (0, 1, 1) (0, 1, 2) (0, 2, 0) (0, 2, 1) (0, 2, 2) (0, 3, 0) (0, 3, 1) (0, 3, 2) (1, 0, 0) (1, 0, 1) (1, 0, 2) (1, 1, 0) (1, 1, 1) (1, 1, 2) (1, 2, 0) (1, 2, 1) (1, 2, 2) (1, 3, 0) (1, 3, 1) (1, 3, 2) A: It's not in the same order, but I think this is what you wanted: def xrangeCombinations(input): if len(input) > 1: for i in xrange(input[-1] + 1): for j in xrangeCombinations(input[:-1]): yield j + [i] else: for i in xrange(input[-1] + 1): yield [i] for i in xrangeCombinations([1, 3, 2]): print i Produces the output: [0, 0, 0] [1, 0, 0] [0, 1, 0] [1, 1, 0] [0, 2, 0] [1, 2, 0] [0, 3, 0] [1, 3, 0] [0, 0, 1] [1, 0, 1] [0, 1, 1] [1, 1, 1] [0, 2, 1] [1, 2, 1] [0, 3, 1] [1, 3, 1] [0, 0, 2] [1, 0, 2] [0, 1, 2] [1, 1, 2] [0, 2, 2] [1, 2, 2] [0, 3, 2] [1, 3, 2] This solution might be slower than alternatives so if speed is an issue you should probably improve it. A: Using numpy if you don't mind getting tuples in the end: >>> import numpy as np >>> e1=np.array([0,1]) >>> e2=np.array([0,1,2]) >>> e3=np.array([0,1,2,3]) >>> g=np.meshgrid(e1,e2,e3) #you need numpy ver>1.7.0, change the order of final result by changing the order of e1, e2, e3 >>> zip(*[item.flatten() for item in g]) [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3)]
unknown
d15503
val
If you wait until it shows up as an error, you can ctrl+enter on the error to bring up idea's intentions, one of which should be an option to create the new class. You can also get the intentions by clicking the red lightbulb that appears next to the error when the cursor is on it. You should change your settings so that F2 Goes to Errors First, then you can press F2 and the cursor will jump to the error making invoking the intentions a little faster. A: First thing import that currently is not referencing any real class it dont work like this in intelliJ. you cannot have an import statement for a non-existing thing. Suppose you have a package named mypackage. Then you can write something like - import mypackage.*; you can define a className inside the existing class then it will report you an error like the name appears to be RED just keep the cursor there Press alt+ins a menu pops up then select create class and then specify the package in Destination package field. In that way it will work.
unknown
d15504
val
Well, besides providing a web server, the watch command does two main things: * *it rebuilds your bootstrap.js file continuously. *it provides a Fashion server If you're trying to change the CSS for your app, by introducing a custom theme, then using Fashion and sencha app watch is a massive time saver. You can also use Tomcat and sencha app watch in parallel, by making your Tomcat instance a proxy to the sencha app watch version.
unknown
d15505
val
Some solution is to create PHP file which returns CSS code based on the variables provided via the GET parameters. BUT: 1) You have to prepare a very strict sanitization as inproper value filtering can lead to security vulnerabilities, 2) The list of params cannot be too long as servers can have limits for the maximum URL length.
unknown
d15506
val
You can do this using R.differenceWith: const blocks = [ { id: 1 }, { id: 2 }, { id: 3 }, ]; const containers = [ { block: { id: 1 } }, { block: { id: 2 } }, { block: { id: 4 } }, ]; const diff = R.differenceWith((x,y) => x.id === y.block.id); const mismatch = diff(blocks, containers).length > 0; console.log(mismatch); <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script> A: In a non ramda way, you could compare each object with the other items and use a deep check. const deep = id => o => o && typeof o === 'object' && (o.id === id || Object.values(o).some(deep(id))), compare = (source, target) => source.every(({ id }) => target.some(deep(id))), blocks = [ { id: 1 }, { id: 2 }, { id: 3 }], containers = [{ block: { id: 1 } }, { block: { id: 2 } }, { block: { id: 3 } }] console.log(compare(blocks, containers)); A: You can use the equals() method. const blocks = [ { id: 1 }, { id: 2 }, { id: 3 }, ] const containers = [ { block: { id: 1 } }, { block: { id: 2 } }, { block: { id: 3 } }, ] console.log(R.equals(containers.map(x => x.block.id),blocks.map(x => x.id))) <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script> A: There is no particular Ramda WayTM. Ramda is a library, a toolkit, or in Underscore's description, a toolbelt. It is built to make a certain style of coding easier to read and write in JS. But it is not meant to dictate at all how you write your code. Ramda's biggest goal is to make it easier to build applications through composing functions, ensuring such FP goodies as immutability and referential transparency. So for this problem, I might start with something like the following: const hasBlock = (containers) => { const ids = containers .map (c => c.block.id) return (block) => ids .includes (block.id) } const allContained = (containers) => (blocks) => blocks .every (hasBlock (containers) ) That latter function can be quickly rewritten using Ramda to const allContained = (containers) => (blocks) => all(hasBlock(containers), blocks) which simplifies to const allContained = (containers) => all(hasBlock(containers)) and from there to the elegant: const allContained = compose (all, hasBlock) But I don't see any straightforward simplifications of hasBlock. I might on some days write it as const hasBlock = (containers, ids = containers .map (c => c.block.id) ) => (block) => ids .includes (block.id) but that's only to satisfy some internal craving for single-expression function bodies, and not for any really good reason. It doesn't make the code any cleaner, and for some readers might make it more obscure. So here is where I end up: const hasBlock = (containers) => { const ids = containers .map (c => c.block.id) return (block) => ids .includes (block.id) } const allContained = compose (all, hasBlock) const containers = [{block: {id: 1}}, {block: {id: 2}}, {block: {id: 4}}] console .log ( allContained (containers) ([{id: 1}, {id: 2}, {id: 3}]), //=> false allContained (containers) ([{id: 1}, {id: 2}, {id: 4}]), //=> true allContained (containers) ([{id: 4}, {id: 1}]), //=> true allContained (containers) ([{id: 42}]), //=> false ) <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script><script> const {compose, all} = R </script> A: You can achieve this with JS/Lodash/Ramda almost same exact way. JS/Lodash having the same exact methods for every and some and in Ramda with all and any: const blocks = [{ id: 1 },{ id: 2 },{ id: 3 }] const containers = [{ block: { id: 1 } },{ block: { id: 2 } },{ block: { id: 3 } }] const blocks2 = [{ id: 1 },{ id: 2 },{ id: 3 }] const containers2 = [{ block: { id: 4 } },{ block: { id: 2 } },{ block: { id: 3 } }] let hasAllBlocks = (blks, conts) => blks.every(b => conts.some(c => c.block.id === b.id)) let hasAllBlocksLD = (blks, conts) => _.every(blks, b => _.some(conts, c => c.block.id === b.id)) let hasAllBlocksR = (blks, conts) => R.all(b => R.any(c => c.block.id === b.id, conts), blks) console.log(hasAllBlocks(blocks, containers)) // true console.log(hasAllBlocks(blocks2, containers2)) // false console.log(hasAllBlocksLD(blocks, containers)) // true console.log(hasAllBlocksLD(blocks2, containers2)) // false console.log(hasAllBlocksR(blocks, containers)) // true console.log(hasAllBlocksR(blocks2, containers2)) // false <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
unknown
d15507
val
Once the cell are displayed and didEndDisplaying is called, there are more things to process and when you scroll cellForItem calls again and that gives you different sizes. In order to get the exact contentSize of UITableView once all the cells are displayed, you can get it from below method. Just write the below method in your UIViewController class. override func viewDidLayoutSubviews() { print(tableView.contentSize.height) //Exact Content Size of UITableView } func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { tableView.layoutIfNeeded() } Hope this helps!
unknown
d15508
val
The first error is: Illegal argument(s): join(): part 0 was null, but part 1 was not. That's because pubspec.yaml contained: dependencies: htmlescape: sdk: htmlescape htmlescape no longer comes with the SDK. Removing the dependency fixed the problem. I simply made a copy of htmlescape.dart in my lib directory. Eventually, I won't need my own copy once the following bug is fixed: http://code.google.com/p/dart/issues/detail?id=1657 The second error is: Running pub install ... Pub install failed, [1] Resolving dependencies... Could not find package "unittest 0.0.0-r.13075" at http://pub.dartlang.org. dart-html5-samples depends on vector_math which depends on unittest. I think they must have changed how unittest is loaded by pub. Running pub update fixed the problem.
unknown
d15509
val
Don't try to manually query your database, let the database do its own querying. You never explained which database you're using, but most a "datetime" field of some sort you can use. You can then pass a formatted date string in your query and check if it's greater than the open field and less than the close field. For example, in SQL you would do: SELECT * FROM stores WHERE {date} >= open and {date} <= close; In this case {date} would be the formatted date you're passing into the query. That said, if you already have the store in question, you can simply compare the data you already have in your javascript object. var store = { "open" : 7200000, "day" : "Thursday", "close" : 93540000 }; var now = Date.now(); if (now >= store.open && now <= store.close) { // you are in range }
unknown
d15510
val
you can add the attribute onclick="location.href='https://google.com';". but could you post codesnippets? and do you use javascript and php? A: I found a solution. To create this behaviour, I simply saved in a UserDefault a Bool value. func registerForPushNotifications() { UNUserNotificationCenter.current() .requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, _ in print("Permission granted: \(granted)") self?.userDefault.set(granted, forKey: "notificationGranted") guard granted else { return } self?.getNotificationSettings() } } func getNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { settings in print("Notification settings: \(settings)") guard settings.authorizationStatus == .authorized else { return } // Saving the value to permit to take the user to the Notification screen only the first time if (self.userDefault.value(forKey: "permissionPopUpIsShowed") == nil) { self.userDefault.set(true, forKey: "permissionPopUpIsShowed") } DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } In the Content View inside the onAppear method you can do this: if appDelegate.userDefault.bool(forKey: "permissionPopUpIsShowed") == true && appDelegate.userDefault.bool(forKey: "notificationGranted") == true { tabSelection = .notifications appDelegate.userDefault.set(false, forKey: "permissionPopUpIsShowed") } In this way you will be able to select a new view (through the tabSelection) and obtain this behaviour only once (when the notification permission popUp is showed).
unknown
d15511
val
look at this line: moduleHtml += "</span>" i think the problem is script still printing only a span but maybe nothing :) anyway checkout below script optimization i think it should work ;) $.get("/Modules/FetchModuleActionsByModuleID", { ModuleID: ModuleID }, function (response) { if (response.replace(/"/g, '') != '{d:[]}' && response.replace(/"/g, '') != '{d:null}' && response.replace(/"/g, '') != '' && response != '') { var actions = eval('(' + response + ')'); var moduleHtml; if (actions.length > 0) { for (i = 0; i < actions.length; i++) { moduleHtml += "<div class='moduleFieldSetting'>" + "<span class='pdRL10x2 fl'><input type='checkbox' name='" + ModuleName + "_Actions' value='" + actions[i].ActionID + "' /></span>" + "<span>" + actions[i].ActionName + "</span>" + "<div class='clear'></div>" + "</div>"; } moduleHtml += "<div class='fr mt15'>" +"<span class='fr'><input type='button' class='inpuButtonAdd' value='Save' /> " + "<input type='button' class='inpuButtonAdd' value='Cancel' /> " +"</span>" + "</div>" + "</div>" + "<div class='clear'></div>" + "</div>" + "</div>" + "<div class='clear'></div>"; $("#divModuleDetails").append(moduleHtml); //appending to div } } });
unknown
d15512
val
Assuming this table: CREATE TABLE TestTable ( Col1 int, Col2 dec(9,2), Col3 money ) With these values: INSERT INTO TestTable VALUES (1, 2.5, 3.45) You can use the following code to get the types as .Net types: Dim DSN = "SERVER=XYZ;UID=XYZ;PWD=XYZ;DATABASE=XYZ" Using Con As New SqlConnection(DSN) Con.Open() Using Com As New SqlCommand("SELECT * FROM TestTable", Con) Com.CommandType = CommandType.Text Using RDR = Com.ExecuteReader() If RDR.Read Then Trace.WriteLine(RDR.GetProviderSpecificFieldType(0)) 'Returns System.Data.SqlTypes.SqlInt32 Trace.WriteLine(RDR.GetProviderSpecificFieldType(1)) 'Returns System.Data.SqlTypes.SqlDecimal Trace.WriteLine(RDR.GetProviderSpecificFieldType(2)) 'Returns System.Data.SqlTypes.SqlMoney End If End Using End Using Con.Close() End Using You can also use this to just get the SQL text version of the type: Dim DSN = "SERVER=XYZ;UID=XYZ;PWD=XYZ;DATABASE=XYZ" Using Con As New SqlConnection(DSN) Con.Open() Using Com As New SqlCommand("SELECT * FROM TestTable", Con) Com.CommandType = CommandType.Text Using RDR = Com.ExecuteReader() If RDR.Read Then Using SC = RDR.GetSchemaTable() Trace.WriteLine(SC.Rows(0).Item("DataTypeName")) 'Returns int Trace.WriteLine(SC.Rows(1).Item("DataTypeName")) 'Returns decimal Trace.WriteLine(SC.Rows(2).Item("DataTypeName")) 'Returns money End Using End If End Using End Using Con.Close() End Using EDIT Here's how to do type comparison along with a helper function that formats things. Outputs once again assume the above SQL. Dim DSN = "SERVER=XYZ;UID=XYZ;PWD=XYZ;DATABASE=XYZ" Using Con As New SqlConnection(DSN) Con.Open() Using Com As New SqlCommand("SELECT * FROM TestTable", Con) Com.CommandType = CommandType.Text Using RDR = Com.ExecuteReader() If RDR.Read Then Trace.WriteLine(FormatNumber(RDR.Item(0), RDR.GetProviderSpecificFieldType(0))) '1 Trace.WriteLine(FormatNumber(RDR.Item(1), RDR.GetProviderSpecificFieldType(1))) '2.50 Trace.WriteLine(FormatNumber(RDR.Item(2), RDR.GetProviderSpecificFieldType(2))) '$3.45 End If End Using End Using Con.Close() End Using Private Shared Function FormatNumber(ByVal number As Object, ByVal type As Type) As String If number Is Nothing Then Throw New ArgumentNullException("number") If type Is Nothing Then Throw New ArgumentNullException("type") If type.Equals(GetType(System.Data.SqlTypes.SqlInt32)) Then Return Integer.Parse(number) ElseIf type.Equals(GetType(System.Data.SqlTypes.SqlDecimal)) Then Return Decimal.Parse(number.ToString()).ToString("N") ElseIf type.Equals(GetType(System.Data.SqlTypes.SqlMoney)) Then Return Decimal.Parse(number.ToString()).ToString("C") End If Throw New ArgumentOutOfRangeException(String.Format("Unknown type specified : " & type.ToString())) End Function A: With access to only the underlying value and not the structure of the database, it's not possible to definitively tell what type the value is. The reason why is that there is an overlap in the domain of Money, Real and Int values. The number 4 for example could be both a Real an Int and likely a Money. Can you give us some more context on the issue? Are you trying to convert a raw database value into a Int style value in VB.Net? Can you show us some code?
unknown
d15513
val
If you don't pass headZ as a reference, then headZ pointer will not be changed when it is passed to this function. So for example if you do something like this: Node* resultHead = NULL; Node* inputA = GetInitialAList(); // (hypothetical function to get the inital value) Node* inputB = GetInitialBList(); SortedRecur(inputA, inputB, resultHead); then the value of resultHead will be unchanged, and thus it will still be NULL. On the other hand, if you changed SortedRecur to take headZ as a reference, then the final value of headZ will point to the last element in your list, because every time you add a new element you also do headZ = headZ->link; - and so headZ is always pointing to the end of the list. The start of the list is lost. I think the easiest way to solve the problem is to keep your current implementation of SortedRecur, but rather than passing a NULL pointer for headZ, use an initial value which points to an actual node. That way, SortedRecur can add the sorted list to the end of your headZ and it won't matter that the initial headZ pointer is unchanged. For example, here's a kludge way to do it: Node dummyNode; dummyNode.link = NULL; Node* resultHead = &dummyNode; Node* inputA = GetInitialAList(); // (hypothetical function to get the inital value) Node* inputB = GetInitialBList(); SortedRecur(inputA, inputB, resultHead); // At this point, the value of resultHead is unchanged, // but the dummyNode now points to the sorted list. // All we have to do now is discard the dummyNode. resultHead = dummyNode.link;
unknown
d15514
val
I'm not sure why that tutorial made it so complex, but all you should have to do is extend the default login view and add your get_success_url function and template_name from django.contrib.auth.views import LoginView as AuthLoginView class LoginView(AuthLoginView): success_url = '/' template_name = 'pages/login.html' redirect_field_name = REDIRECT_FIELD_NAME def get_success_url(self): redirect_to = self.request.GET.get(self.redirect_field_name) if not is_safe_url(url=redirect_to, host=self.request.get_host()): redirect_to = self.success_url return redirect_to Edit: your form is missing the name property on the inputs. That's where django is looking for the values. <input type="text" name="{{ form.username.name }}" /> <input type="password" name="{{ form.password.name }}" />
unknown
d15515
val
Django takes the WHERE filter to load the object entirely from the keys of the dictionary you provide. It is up to you to provide field lookups; you can use the iexact field lookup type, but you do need to use this on textual fields. So if you wanted to match a specific string field, case insensitively, add __iexact to the key in dictionary; e.g. {'foo': 'bar'} becomes {'foo__iexact': 'bar'}.
unknown
d15516
val
pd.set_option('display.max_colwidth', 3000) This increases the number of displayed characters and somehow this solves the problem for me. :)
unknown
d15517
val
How can I make this process interruptible, while also retaining the ease of access of the SQLDataAdapter? According to the documentation you should be able to call Close on the underlying SqlConnection instance. The documentation says this will terminate and rollback any pending transactions. Also, instead of using a SqlDataAdapter (which unfortunately does not have the async Fill methods) you could use SqlCommand.BeginExecuteReader and once that is done you can fill a DataTable by calling the overload of DataTable.Load that accepts an IDataReader. If you want to interrupt a pending a command just call Close.
unknown
d15518
val
I think your clue is here: String query = "select * from logins where USERNAME=@username and PASSWORD=@password"; By doing this, you check the username and password at the same time. So if the username OR the password is incorrect, you get 0 rows in your result. To get what your want, only mention the username in the SQL query, and if you get a record, you compare the password in .Net code. So: String query = "select * from logins where USERNAME=@username"; MySqlCommand cmd = new MySqlCommand(query, con); cmd.Parameters.AddWithValue("@username", TextBox1.Text.Trim()); MySqlDataAdapter sda = new MySqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); And then check the password if you get 1 row back. This looks like an insecure way of handling logins, so I hope you at least will hash and salt the passwords. Now you are one database leak away from a very embarasing situation. https://duckduckgo.com/?q=password+hashing+and+salting
unknown
d15519
val
You can only initialize properties with constants: http://www.php.net/manual/en/language.oop5.properties.php [Properties] are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated. So indeed, initialize them in your constructor. A: Initialize the value in your constructor A: According to the manual you can only assign a constant value when instantiating a class property.
unknown
d15520
val
Maybe FlowLayout is what you're looking for. It wraps content to the next line if there is no space in the current line.
unknown
d15521
val
I hope this help. after I look at your code I see your miss spelling on your DBSeed. just change 'ìtem_size_id' => 'item_size_id'. it will fixed. Hope it help. thanks A: use item_size_id instead of using ìtem_size_id because your databse field name is item_size_id so just change it use Illuminate\Database\Seeder; use Carbon\Carbon; class ItemOptionsSeeder extends Seeder { public function run() { //blancas DB::table('item_options')->insert([ 'item_id' => 1, 'item_color_id' => 1, 'item_size_id' => 1, 'stock' => 10 ]); //negras DB::table('item_options')->insert([ 'item_id' => 1, 'item_color_id' => 2, 'item_size_id' => 2, 'stock' => 10 ]); //rojas DB::table('item_options')->insert([ 'item_id' => 1, 'item_color_id' => 3, 'item_size_id' => 3, 'stock' => 10 ]); //verdes DB::table('item_options')->insert([ 'item_id' => 1, 'item_color_id' => 4, 'item_size_id' => 4, 'stock' => 10 ]); } }
unknown
d15522
val
//button[@ng-click='$arrowAction(-1, 0)'] is not a valid CSS selector. It actually looks like this is an XPath expression and you meant to use by.xpath() locator. You can though use the partial attribute check instead: $("button[ng-click*=arrowAction]").click(); $ here is a shortcut to element(by.css(...)), *= means "contains". Or, do an exact match: $("button[ng-click='$arrowAction(-1, 0)']").click(); I still don't like the location technique used in this case, but, given what we have, it is probably the best we can do. Ideally, if you have control over the application code and templates, add a meaningful id, class or a custom data attribute to uniquely identify the element.
unknown
d15523
val
Yes, you can do that. By default, your databases and other important files are stored in PGDATA. Traditionally, the configuration and data files used by a database cluster are stored together within the cluster's data directory, commonly referred to as PGDATA (after the name of the environment variable that can be used to define it). A common location for PGDATA is /var/lib/pgsql/data. https://www.postgresql.org/docs/10/storage-file-layout.html I don't know how you will uninstall PostgreSQL, but be sure to keep PGDATA. (yum or apt won't delete PGDATA) After re-installing PostgreSQL, make sure to launch your PostgreSQL with your existing PGDATA pg_ctl start -D YOUR_EXISTING_PGDATA/
unknown
d15524
val
Use adeneo's answer, because I also do not see why you would use this plugin, but here could be a few reasons why what you have isn't working: In the examples from the plugin's website, you should * *bind to the form, not the button *use the beforeSubmit option *Remove the submit() from the end of your call, not sure why it is there *Watch console for any errors var options= { target:'#preview', url:'ajaxcall.php', beforeSubmit: showLoading, error: function(e){ alert("Error: " + e); } }; function showLoading(){ $('#preview').html("<img src='images/loader.gif' alt='Loading.....'/>"); } $(document).ready(function(){ $("#upload_pic").ajaxForm(options); });
unknown
d15525
val
DISTINCT is not a grouping that can be used for aggregate functions. If you want take the smalled displayorder in each category, you have to explicitly group by that column: SELECT category FROM m_ipaperdara GROUP BY category ORDER BY MIN(displayorder)
unknown
d15526
val
You must access iframe content, not your page. $("#iframe").ready(function() { $.each($('#iframe').contents().find('input[type=text],textarea'), function() { var $thatButton = $(this); var idOfCurrentElement = thatButton .attr('id'); var classNameOfCurrentElement = thatButton ).attr('class'); var visibilityOfCurrentElement = thatButton .css('visibility'); if(classNameOfCurrentElement != "hidden" && visibilityOfCurrentElement == "visible") //do what you want. }); });
unknown
d15527
val
shouldChangeCharactersInRange is called just before actual text has changed. If you want to perform an action after actual text has changed, you can try the approach below: ... //start observing [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textHasChanged:) name:UITextFieldTextDidChangeNotification object:{your UITextField}]; ... - (void)textHasChanged:(NSNotification *)notification { UITextField *textField = [notification object]; //check if textField.text.length >= 10 //do stuff... } A: You can get what the string will be after the characters are changed with the method stringByReplacingCharactersInRange:withString: #define MAX_LENGTH 10 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField == user_mobile_txtField) { NSString *fullString = [textField.text stringByReplacingCharactersInRange:range withString:string]; if (fullString.length >= MAX_LENGTH && range.length == 0) { if (fullString.length == MAX_LENGTH) { NSLog(@“Want to call Call method HERE "); } return NO; // return NO to not change text } } return YES; } A: Please try with below code - #define MAX_LENGTH 10 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField==user_mobile_txtField) { if (textField.text.length >= MAX_LENGTH ) { if (textField.text.length==MAX_LENGTH) { NSLog(@“Want to call Call method HERE "); } return NO; // return NO to not change text } } return YES; }
unknown
d15528
val
I have faced this problem myself. For me the problem was path. I could get it working by using a shell script to launch a python script and launch the shell script from crontab. Here is my launcher.sh. You may not use sudo if you do not want. home/pi/record_data is the path where my file resides. cd / cd home/pi/record_data sudo python record_video.py In this case record_video.py is the python file I want to run at startup. In the crontab edit, I added this line below. @reboot sh /home/pi/record_data/launcher.sh & Do try this out if it work for you :) Good luck. I have not got the logging the error into files working yet though. A: it looks to me like you need to set/change the write permissions of the file before your python scrypt do this: f.write("it works " + t + "\n") for you is working because (maybe you are the owner of the file). typical linux file permission is described as: do use the chmod with the property flags, so linux has the rights to write the file too, please refer to the ubuntu help :)
unknown
d15529
val
If you use Jmeter 3.2, then probably it is your case: http://forum.zkoss.org/question/105222/zk-jmeter-plugin-080jar-not-working-with-jmeter-32/ (use 3.1)
unknown
d15530
val
Assuming that you've logout.php on the root, use a slash before the page name like this, to point the page from the root. <li> <a href="/logout.php">Logout</a> </li> As what you are using is just logout.php which will point the page name in that specific directory, but the server will return 404 as it may be available when you are on the root, but it will fail when you are in the directory. If it still complicates the navigation, you can also use if conditions to change the paths accordingly.
unknown
d15531
val
Assuming all this is happening in the UI thread, then it's not going to update because you are keeping the thread busy with processing your loop. You need to spawn off a background thread to do the processing so that it doesn't hang your UI thread. Then you will need to have the part where you actually set the progress bar pushed back to your UI thread using Contol.Invoke. See here: http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx for both an example of threading (although there are many ways you can do this) and Control.Invoke. A: Use BackgroundWorker: BackgroundWorker _worker; // executes on another thread void worker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = (BackgroundWorker)sender; int c = 0; OdbcConnection cn = openOdbcDB(); foreach (DataSet ds in allDataSets) { foreach (DataTable dt in ds.Tables) { foreach (DataRow dr in dt.Rows) { insertIntoDatabaseCurrentRecord(dr); } } // do not update UI elements here, but in ProgressChanged event //pbMain.Value = pbMain.Value + (33 / totalFiles); c++; worker.ReportProgress(c); // call ProgressChanged event of the worker and pass a value you can calculate the percentage from (I choose c, since it is the only calculated value here) } cn.Close(); cn.Dispose(); } // gets called on your main thread void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { // update the progressbar here. // e.ProgressPercentage holds the value passed in DoWork. } A: Since your loops are blocking the active thread, you will have to use another Thread (clean way) or simply use Application.DoEvents() on WinForms: int c = 0; OdbcConnection cn = openOdbcDB(); foreach(DataSet ds in allDataSets) { foreach(DataTable dt in ds.Tables) { foreach (DataRow dr in dt.Rows) { insertIntoDatabaseCurrentRecord(dr); Application.DoEvents(); //Quick and dirty } } pbMain.Value = pbMain.Value + (33 / totalFiles); c++; } cn.Close(); cn.Dispose();
unknown
d15532
val
This way of using command works for me fine /opt/plesk/php/5.6/bin/php /var/www/vhosts/websitename.com/httpdocs/artisan schedule:run This is working properly in Plesk A: Instead of 'php' try to use command '/opt/plesk/php/5.6/bin/php' A: it is a quite old question but for google visitors, Here a solution with Plesk in 2022 A: Try /opt/plesk/php/7.3.14/bin/php httpdocs/artisan
unknown
d15533
val
Looks like: https://bugzilla.mozilla.org/show_bug.cgi?id=203225 It was logged over 10 years ago. As a workaround you could use a div within the TD and set that to position:relative instead of setting it on the TD directly.
unknown
d15534
val
You can change your handlePageClick method to setState only when this.state.menuLocked is false. handlePageClick = () => { if (!this.state.menuLocked) { this.setState({ menuOpen: false, }); } } A: Inside of handlePageClick() you should do a check to see if this.state.menuLocked is true. If so, don't change the value of menuOpen in state. handlePageClick = () => { if (!this.state.menuLocked) { this.setState({ menuOpen: false, }); } } As a side note, in handleMenuLock() you are using the previous value of menuLocked to set the new value. Since setState is asynchronous, it's entirely possible that the value of menuLocked has changed by the time it actually saves and so you may not get the desired result. As such, you should pass it a function like this: handleMenuLock = () => { this.setState((prevState) => ({ menuLocked: !prevState.menuLocked })) } This ensures that the value is actually toggled. Docs on using setState in this manner can be found here.
unknown
d15535
val
Add require __DIR__ . '/vendor/autoload.php'; to sync.php. You can read more about it here.
unknown
d15536
val
You can block the Azure app request with particular url like "wp-includes" by using the rewrite tag inside the system.webServer tag in the web.config file of your Azure App Service like below and you can redirect to the error page by using the action tag in web.config file as shown below in the screenshot: You can find the web.config file in kudu console-->wwwroot-->views-->web.config file: The below is the sample for rejecting the request to /login and you can change it as per the requirement. <system.webServer> <rewrite> <rule name="Block X Page" stopProcessing="true"> <match url=".*" /> <conditions> <add input="{HTTP_HOST}" pattern="www.yoursite.com" /> <add input="{PATH_INFO}" pattern="/login" /> </conditions> <action type="Redirect" url="https://www.otherpage.com/" /> </rule> </rewrite> </system.webServer>
unknown
d15537
val
I have used this structure You can use a query like this : select name, person.name, person.out("hasProfile").name as profile from (select name, in('ParticipatinIn') as person from Chat unwind person) unwind profile If you use traverse, if a person is a part of two different Chat, you got that person only one time. Hope it helps. A: With this schema: Try this: select name, in('HasProfile').name as Person, in('HasProfile').out('ParticipatingIn').name as Chat from Profile This is the output: If you don't like see the bracket you can use the unwind command: select name, in('HasProfile').name as Person, in('HasProfile').out('ParticipatingIn').name as Chat from Profile unwind Person,Chat This is the output: UPDATE select name, in('ParticipatingIn').name as Person, in('ParticipatingIn').out('HasProfile').name as Profile from Chat UPDATE 2 traverse * from Chat Hope it helps Regards.
unknown
d15538
val
It seems you havn't use your JSONArray object JSONArray mainfoodlist = null; tipshealth = json.getJSONArray(TAG_RESPONSE); // looping through All RESPONSE for (int i = 0; i < tipshealth.length(); i++) { JSONObject jsonobj = tipshealth.getJSONObject(i); tipHealth = jsonobj.getString(KEY_HEALTHTIPS); listhealthtips.add(tipshealth.getJSONObject(i).getString("tips")); } A: It seems like that the problem comes from this section: user = json.getJSONArray(TAG_USER); JSONObject c = json.getJSONObject(0); you get a JOSNObject user but you never used it. I guess this is probably what you mean: user = json.getJSONArray(TAG_USER); JSONObject c = user.getJSONObject(0);
unknown
d15539
val
Well I'm not sure this will help you, but I had the same promtail logs of adding target and immediately removing them. My config was a bit different, I was running promtail locally and scraping some files. The problem was that promtail didn't have access rights to read those files. So I'd suggest double checking that your promtail pod has read access to the files you're trying to scrape and then restarting the service. I also didn't see any errors in grafana or Loki, as the logs were never pushed to Loki.
unknown
d15540
val
The use of OAUTH2 with JavaMail is explained on the JavaMail project page. Also, you should fix these common mistakes in your code.
unknown
d15541
val
android:paddingRight="0dp" should work A: Change the layout by setting weight like this. This will do the trick for you. <TableRow android:layout_marginTop="40dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:weightSum="8"> <EditText android:id="@+id/num1" android:layout_width="0dp" android:layout_weight="2" android:layout_height="wrap_content" android:ems="4" android:inputType="number" /> <TextView android:id="@+id/textView1" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="+" android:gravity="center" android:textAppearance="?android:attr/textAppearanceLarge" /> <EditText android:id="@+id/num2" android:layout_width="0dp" android:layout_weight="2" android:layout_height="wrap_content" android:inputType="number" android:ems="4" /> <TextView android:id="@+id/textView3" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="=" android:gravity="center" android:textAppearance="?android:attr/textAppearanceLarge" /> <EditText android:id="@+id/wynik" android:layout_width="0dp" android:layout_weight="2" android:layout_height="wrap_content" android:ems="4" android:inputType="text" > <requestFocus /> </EditText> </TableRow>
unknown
d15542
val
I think you want to display the "Please enter captcha text." as part of the ValidationSummary control. To do this, you just need to let the server-side know the captcha text. Do this: * *Add another textbox, but keep it hidden with display:none: <asp:textbox id="txtCaptcha" runat="server" style="display:none;"> *Modify your Javascript to copy the captcha value into the txtCaptcha textbox: <script type="text/javascript"> $(document).ready(function () { $('#' +'<%=btnSend.ClientID %>').on('click', function (e) { var captcha = $("input[name$=CaptchaControl1]").val(); $('#' + '<%=txtCaptcha.ClientID %>').val(captcha); }) }); </script> *Create a RequiredValidator for txtCaptcha textbox: <asp:RequiredFieldValidator ID="RequiredFieldValidatorForCaptcha" runat="server" ErrorMessage="Please enter captcha text." ControlToValidate="txtCaptcha" Display="None" ValidationGroup="VG"></asp:RequiredFieldValidator>
unknown
d15543
val
The HtmlTextNode class has a Text property* which works perfectly for this purpose. Here's an example: var textNodes = doc.DocumentNode.SelectNodes("//body/text()").Cast<HtmlTextNode>(); foreach (var node in textNodes) { node.Text = node.Text.Replace("foo", "bar"); } And if we have an HtmlNode that we want to change its direct text, we can do something like the following: HtmlNode node = //... var textNode = (HtmlTextNode)node.SelectSingleNode("text()"); textNode.Text = "new text"; Or we can use node.SelectNodes("text()") in case it has more than one. * Not to be confused with the readonly InnerText property. A: Try code below. It select all nodes without children and filtered out script nodes. Maybe you need to add some additional filtering. In addition to your XPath expression this one also looking for leaf nodes and filter out text content of <script> tags. var nodes = doc.DocumentNode.SelectNodes("//body//text()[(normalize-space(.) != '') and not(parent::script) and not(*)]"); foreach (HtmlNode htmlNode in nodes) { htmlNode.ParentNode.ReplaceChild(HtmlTextNode.CreateNode(htmlNode.InnerText + "_translated"), htmlNode); } A: Strange, but I found that InnerHtml isn't readonly. And when I tried to set it like that aElement.InnerHtml = "sometext"; the value of InnerText also changed to "sometext"
unknown
d15544
val
If you want a list of the permutations, you can do list(itertools.permutations(mystring)) and then you can index it. This may not be what you need; it's not memory-efficient because it stores the entire list in memory, so you can end up storing a really big list with a small mystring. If you only need to iterate over it one time, you should use a loop to iterate over itertools.permutations(mystring). for permutation in itertools.permutations(mystring): # do whatever you want to do with each permutation. itertools.permutations returns a generator, which only gives up values one-at-a-time. It's way more memory efficient, and if you only need each value once, it's the way to go. How big would the list be? If you are making a list out of itertools.permutations, it get's really big really fast. The length of the new list will be len(mystring)! (that's factorial), and the size of each element of the list will be len(mystring). So the memory complexity is something like O(n*n!), where n is the length of the input string. On my computer (32-bit Python), I can't do list(itertools.permutations(mystring)) for strings longer than 10 characters–I get a MemoryError. When I try it with a string of length 11, e.g. list(itertools.permutations('abcdefghij')), it tries to store a list with 39,916,800 elements. Apparently that's too much for me.
unknown
d15545
val
Finally, figured out that fabric sdk (https://github.com/hyperledger/fabric-sdk-node) has to be downloaded and configured before following the video tutorial in the question.
unknown
d15546
val
stock A -4.41 Stock B -1.49 Stock C 0.38 Stock D 1.43 User B Stock A -2.05 Stock B .05 I want to show table like: USER Growth A -4.09 B -2.1 here are my two tables: one portfolio where all buy sell info's are kept of users by user_id +-------------------+---------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------------+---------------+------+-----+---------+----------------+ | portfolio_ID | int(11) | NO | PRI | NULL | auto_increment | | user_id | int(11) | NO | | NULL | | | contest_id | int(11) | NO | | NULL | | | company_id | int(11) | NO | | NULL | | | share_amount | int(11) | NO | | NULL | | | buy_price | decimal(9,2) | NO | | NULL | | | total_buy_price | decimal(10,4) | NO | | NULL | | | buy_date | date | NO | | NULL | | | commision | decimal(9,2) | NO | | NULL | | | sell_share_amount | int(11) | NO | | NULL | | | sell_price | decimal(10,2) | NO | | NULL | | | total_sell_price | decimal(16,2) | NO | | NULL | | | sell_date | date | NO | | NULL | | | sell_commision | decimal(9,2) | NO | | NULL | | +-------------------+---------------+------+-----+---------+----------------+ Next the daily stock table: +-----------------+------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------------+------------------+------+-----+---------+-------+ | company_id | int(11) | NO | PRI | NULL | | | entry_date | date | NO | PRI | NULL | | | entry_timestamp | int(10) unsigned | NO | | NULL | | | open | decimal(16,2) | NO | | NULL | | | high | decimal(16,2) | NO | | NULL | | | low | decimal(16,2) | NO | | NULL | | | ltp | decimal(16,2) | NO | | NULL | | | ycp | decimal(16,2) | NO | | NULL | | | cse_price | decimal(9,2) | NO | | NULL | | | cse_volume | decimal(18,2) | NO | | NULL | | | total_trade | int(30) | NO | | NULL | | | total_volume | int(30) | NO | | NULL | | | total_value | decimal(18,4) | NO | | NULL | | | changes | float(10,2) | NO | | NULL | | | floating_cap | float(16,2) | NO | | NULL | | +-----------------+------------------+------+-----+---------+-------+ this is the sql i am using: SELECT po.user_id, ((e.ltp-po.buy_price)/po.buy_price) AS growth FROM eod_stock AS e LEFT OUTER JOIN portfolio AS po ON e.company_id = po.company_id WHERE po.contest_id = 2 GROUP BY po.user_id; but it return only first changes not the sum of the changes of the growth, i then modified it like this: SELECT po.user_id, SUM((e.ltp-po.buy_price)/po.buy_price) AS growth FROM eod_stock AS e LEFT OUTER JOIN portfolio AS po ON e.company_id = po.company_id WHERE po.contest_id = 2 GROUP BY growth ORDER BY growth DESC; but it generates a error code 1056, cant group on growth here is the sql fiddle: http://sqlfiddle.com/#!2/b3a83/2 Thanks for reading. A: You don't want to group by growth. Why did you change the group by? SELECT po.user_id, SUM((e.ltp-po.buy_price)/po.buy_price) AS growth FROM eod_stock e LEFT OUTER JOIN portfolio po ON e.company_id = po.company_id WHERE po.contest_id = 2 GROUP BY po.user_id ORDER BY growth DESC; However, I suspect that you might actually want the maximum minus the minimum: SELECT po.user_id, (MAX(e.ltp-po.buy_price) - MIN(e.ltp-po.buy_price))/po.buy_price) AS growth FROM eod_stock e LEFT OUTER JOIN portfolio po ON e.company_id = po.company_id WHERE po.contest_id = 2 GROUP BY po.user_id ORDER BY growth DESC; This gives an overall view over time. However, it doesn't show the direction. So something going from 50 to 100 gets the same value as something going from 100 to 50. This can be fixed, if this is what you are really looking for.
unknown
d15547
val
You can simplify this a lot by using lxml's getpath() method. This is input.xml: <root1> <child1/> <child2> <child21> <child221/> </child21> </child2> <child3/> </root1> Here is how you can generate an absolute XPath expression for each element in the XML document: from lxml import etree tree = etree.parse("input.xml") for elem in tree.iter(): print(tree.getpath(elem)) Output: /root1 /root1/child1 /root1/child2 /root1/child2/child21 /root1/child2/child21/child221 /root1/child3
unknown
d15548
val
Try this: function getRoot($cat_id) { foreach ($this->cat_arr as $row) { if ($row->cat_id == $cat_id && $row->parent_id == 0) { return $row->cat_id; } } return $this->getRoot($row->parent_id); }
unknown
d15549
val
If you're use VSCode it sounds like the data loader has multiple workers and it can't create more threads. Set the number of workers to 0. See: VSCode bug with PyTorch DataLoader?
unknown
d15550
val
No. The system is actually the system under consideration. It's not an actor but defines the border for actors. That's why you see a boundary grouping use cases and the actors outside that border attached to the use cases inside. p. 637 of UML 2.5: UseCases are a means to capture the requirements of systems, i.e., what systems are supposed to do. The key concepts specified in this clause are Actors, UseCases, and subjects. Each UseCase’s subject represents a system under consideration to which the UseCase applies. Users and any other systems that may interact with a subject are represented as Actors.
unknown
d15551
val
Your issue: you are using a mock representing an interface of the object containing the method you want to test, which means your code is never really called (a breakpoint would have revealed this particular issue). As for how you should have written your test : [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestAddData() { long documentID = 123; string metadataCategoryName = null; List<KeyValuePair<string, string>> metadata = null; // Configure as needed using Mock.Get() var service = Mock.Of<IService>(); var fService = Mock.Of<IFService>(); var logger = Mock.Of<ILogger>(); var documentHandler = new DocumentManagementHandler(service, fService, logger); documentHandler.AddData(documentID, metadataCategoryName, metadata); } Additionally, you might want to assert the data contained in your exception. E.g. To check that your ArgumentNullException is reporting the correct parameter name
unknown
d15552
val
You can do the following: * *you assume that your original image is looking with 90 degree angle on a planar object *you assume some camera intrinsic parameters (e.g. focal point in the middle of the image and uniform pixel size), some camera extrinsics (e.g. looking "down" with some position from above the plane) and some plane coordinates (xy-plane). This will result in every pixel to lie on some coordinates of the plane. *you change your camera extrinic parameters by rotating around the camera center *you project some (4 or more) plane positions to your camera image (e.g. use cv::projectPoints()). *you compute the perspective homography that describes the pixel "motion" between both camera views (input pixel positions are those projected plane positions and the same plane positions in your original image) *remember that homography for each chosen view. *for each image, just use those homographies, you don't have to recompute them because they are the same for each image. EDIT: this is how it looks like in action (sorry for ugly code): cv::Mat getRotationMatrixAroundY(double angle) { cv::Mat rVec; cv::Mat deg45 = cv::Mat::zeros(3,3,CV_64FC1); double cos45 = cos(CV_PI*angle/180.0); double sin45 = sin(CV_PI*angle/180.0); // different axis: /* deg45.at<double>(1,1) = cos45; deg45.at<double>(1,2) = sin45; deg45.at<double>(0,0) = 1; deg45.at<double>(2,1) = -sin45; deg45.at<double>(2,2) = cos45; */ /* deg45.at<double>(0,0) = cos45; deg45.at<double>(0,1) = in45; deg45.at<double>(2,2) = 1; deg45.at<double>(1,0) = -sin45; deg45.at<double>(1,1) = cos45; */ deg45.at<double>(0,0) = cos45; deg45.at<double>(0,2) = sin45; deg45.at<double>(1,1) = 1; deg45.at<double>(2,0) = -sin45; deg45.at<double>(2,2) = cos45; cv::Rodrigues(deg45, rVec); return rVec; } // banknode training sample generator int main() { cv::Mat input = cv::imread("../inputData/bankNode.jpg"); std::vector<cv::Point3f> pointsOnPlane; pointsOnPlane.push_back(cv::Point3f(0-input.cols/2,0-input.rows/2,0)); pointsOnPlane.push_back(cv::Point3f(input.cols-input.cols/2,0-input.rows/2,0)); pointsOnPlane.push_back(cv::Point3f(input.cols-input.cols/2,input.rows-input.rows/2,0)); pointsOnPlane.push_back(cv::Point3f(0-input.cols/2,input.rows-input.rows/2,0)); std::vector<cv::Point2f> originalPointsInImage; originalPointsInImage.push_back(cv::Point2f(0,0)); originalPointsInImage.push_back(cv::Point2f(input.cols,0)); originalPointsInImage.push_back(cv::Point2f(input.cols,input.rows)); originalPointsInImage.push_back(cv::Point2f(0,input.rows)); std::cout << "original pixel positions:" << std::endl; for(unsigned int i=0; i<originalPointsInImage.size(); ++i) std::cout << originalPointsInImage[i] << std::endl; cv::Mat cameraIntrinsics = cv::Mat::eye(3,3,CV_64FC1); cameraIntrinsics.at<double>(0,0) = 500.0; cameraIntrinsics.at<double>(1,1) = 500.0; cameraIntrinsics.at<double>(0,2) = input.cols/2.0; cameraIntrinsics.at<double>(1,2) = input.rows/2.0; std::vector<double> distCoefficients; cv::Mat rVec; cv::Mat tVec; cv::solvePnP(pointsOnPlane, originalPointsInImage, cameraIntrinsics, distCoefficients, rVec, tVec); // let's increase the distance a bit tVec = tVec*2; double angle = -45; // degrees cv::Mat rVec2 = getRotationMatrixAroundY(angle); // TODO: how to "add" some rotation to a previous rotation in Rodrigues?!? // atm just overwrite: std::vector<cv::Point2f> projectedPointsOnImage; cv::projectPoints(pointsOnPlane, rVec2, tVec, cameraIntrinsics, distCoefficients, projectedPointsOnImage); cv::Mat H = cv::findHomography(originalPointsInImage, projectedPointsOnImage); cv::Mat warped; cv::warpPerspective(input, warped, H, input.size()); cv::imshow("input", input); cv::imshow("warped", warped); cv::waitKey(0); return 0; } with this result: as you can see there is one problem: the rotation isn't around the center of the banknode. If someone can fix that, the result will be better. Atm I had to scale the translation part, this might not be necessary afterwards. Probably the problem occurs because of wrong translation + rotation combination. for comparison: tranlation scaled by 1.5: and not scaled: Is this what you wanted to achieve (if the viewing center of the camera could be fixed at the middle of the banknode)? A: Look here for a Projective Transformation using Matlab. You only have to find the right warping matrices (so-called homographies). You can build them with the mathematics on wikipedia, given a rotation matrix and an assumed camera intrinsics. However, I think synthetically created training data possibly causes some problems regarding your task. The reflecting parts of bank notes are engineered to look different from different view points. You'll lose information. Further, do not underestimate the effort, which will be necessary to develop this. There is quite sophisticated research going on in this field. See here: Towards Mobile Recognition and Verification of Holograms using Orthogonal Sampling Mobile User Interfaces for Efficient Verification of Holograms
unknown
d15553
val
Did you installed any windows security updates? Did you change any group policy like 'Turn off Data URI support'? If yes, then try to enable this policy or for a testing purpose try to remove that security update may solve the issue. Also try to make a test with other browsers and check whether you have same issue with those browsers or it works correctly. It can help us to narrow down the issue. You can let us know about your testing results. We will try to provide you further suggestions. Regards Deepak
unknown
d15554
val
To remove a file name extension, you can use os.path.splitext function: >>> import os >>> name = '2019-01-13.json' >>> os.path.splitext(name) ('2019-01-13', '.json') >>> os.path.splitext(name)[0] '2019-01-13'
unknown
d15555
val
I think your best bet is to generate the required header file from the pre-existing file. The following shell command would do the trick: (echo "#define FOO" ; cat myheader_pregen.hpp) > myheader.hpp You can incorporate the above as a script into autotools with this
unknown
d15556
val
Data is an anonymous struct, so you need to write it like this: type New struct { UserID int `json:"userId"` Data struct { Address string `json:"address"` } `json:"new_data"` } func (old Old) ToNew() New { return New{ UserID: old.UserID, Data: struct { Address string `json:"address"` }{ Address: old.Data.Address, }, } } (playground link) I think it'd be cleanest to create a named Address struct. A: You're defining Data as an inline struct. When assigning values to it, you must first put the inline declaration: func (old Old) ToNew() New { return New{ UserID: old.UserID, Data: struct { Address string `json:"address"` }{ Address: old.Data.Address, }, } } Hence it is generally better to define a separate type for Data, just like User.
unknown
d15557
val
For a simple way, you can use type number at input form <input type="number" name="grocery" id="grocery" min="100" max="500" /> Another way you can use javascript <script> function integerInRange(value, min, max) { if(value < min || value > max) { document.getElementById("grocery").value = "500"; alert("min = 100 and max = 500"); } } </script> and in your view <input type="text" class="form-control" name="grocery" id="grocery" onkeyup="integerInRange(this.value, 100, 500)" />
unknown
d15558
val
Does PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true); give you the results that you are looking for? If so then is it possible that when you make the call that the row that you want to size the grid by isn't visible?
unknown
d15559
val
You have problems when you add the elements with the same key. When emplace_hint is called with the key which exists, you push on deque duplicated iterators (emplace_hint returns the iterator to already existing element map::emplace_hint). When deque and map are cleared, you call map::erase but it accepts only valid and dereferenceable iterators. So when erase is called for the duplicated iterator (map::erase), the code crashes because this item was deleted in previous erase call.
unknown
d15560
val
Undefined index: subject in Are you 100% sure table messages has a field name subject ??? I believe case sensitive is important here. Because that is what would cause the error. A: You can get table structure by executing this query: DESCRIBE messages; Alternatively, you can use mysql_list_fields to get information about table columns.
unknown
d15561
val
Or try this in cloud shell? virtualenv --python=/usr/bin/python2 run_pipeline . ./run_pipeline/bin/activate pip install apache-beam[gcp] python -m simple_pipeline --runner DataflowRunner --project myproject --staging_location gs://bucket/staging --temp_location gs://bucket/temp A: I am able to launch dataflow jobs after upgrading to latest version. pip install apache-beam[gcp]
unknown
d15562
val
<rich:toggleControl onclick="hideDiv()">
unknown
d15563
val
You want to move the date check to the where of the inner query. Try something like: SELECT member.*,card.* FROM member LEFT JOIN member_card card on card.member=member.id WHERE member.id IN ( SELECT DISTINCT m.id FROM Member m LEFT JOIN Member_Card mc ON (mc.Member = m.id) WHERE ( m.LastModifiedDate >= sinceDate OR mc.LastModifiedDate >= sinceDate ) ) A: Try this... (yet to be tested) SELECT * FROM member m1 JOIN card c1 ON c1.member = m1.id WHERE m1.id IN ( SELECT DISTINCT m.id from member m JOIN card c ON c.member = m.id WHERE (c.LastModifiedDate >=sinceDate OR m.LastModifiedDate >= sinceDate)) A: You can try like this, SELECT o.status, o.date, c.name FROM cliente c LEFT JOIN orders o ON c.id=o.id WHERE o.date = '2/1/2015'
unknown
d15564
val
Why don't you use something like this: platformRequest("http://ololo.com"); It will call a default browser to open the link. A: public void openBrowser(String URL) { try { mainMIDlet.platformRequest(URL); } catch (ConnectionNotFoundException e) { // error } }
unknown
d15565
val
Use BindingFlags.DeclaredOnly with your Type.GetProperties call in order to specify to just get the properties from the specified type. For example, to get all non-static properties on a type without looking up it's hierarchy, you could do: var properties = theType.GetProperties( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
unknown
d15566
val
We have found an interesting Article that helped us to solve the problem. Host Visual
unknown
d15567
val
The problem is in the writeImage:ToPlistFileForKey: method. You convert an image to a data as below: NSData *data = [NSKeyedArchiver archivedDataWithRootObject:image]; But convert the data to image like this: UIImage * image = [UIImage imageWithData:data]; This will always return a nil that because the format of the archived data is NSPropertyListBinaryFormat_v1_0 not PNG(or bitmap format). Instead of using [NSKeyedArchiver archivedDataWithRootObject:image], you should use UIImagePNGRepresentation(image) as below: - (BOOL)writeImage:(UIImage*)image ToPlistFileForKey: (NSString*)imageURL { archivedDataWithRootObject:image]; NSData *data = UIImagePNGRepresentation(image); if (plistDictioary == nil) { plistDictioary = [NSMutableDictionary new]; } [plistDictioary setObject:data forKey:imageURL]; BOOL didWriteSuccessfull = [plistDictioary writeToFile:[self getPlistFilePath] atomically:YES]; return didWriteSuccessfull; } The UIImagePNGRepresentation function which returns the data for the specified image in PNG format, then you get an image [UIImage imageWithData:data]. Hope this will help you.
unknown
d15568
val
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"ANY myEmployees.employeeNumber = %d AND myProjectType.projectTypeName = %d", [theEmployee valueForKey:@"employeeNumber"], [theProjType valueForKey:@"projectTypeName"]]; Are you sure this is correct? valueForKey: always returns a NSObject but your placeholder is %d. This should create strange behaviour. Try %@ instead
unknown
d15569
val
Just get rid of while. It was useless with your old approach and become harmful with second one. You have to understand that this while thing is not some obligatory part of the database interaction but the way to get multiple rows. But since you are fetching only one row, you shouldn't use while at all. Your first code block should be $result = mysqli_query(...); $row = mysqli_fetch_array($result); $id_product = $row['id_courses']; ... and the second one as well $stmt->bind_param("i",$active); $stmt->execute(); $stmt->bind_result( $id_product,$product,$subtitle,$price); $stmt->fetch(); in the first block you saved variables manually inside while, and thet's why they were available outside the loop. But in the second they are populated directly by fetch() method and therefore it makes them all empty on the last iteration when no more data left.
unknown
d15570
val
The second query counts rows that have a non-empty (NOT NULL) EMPLOYEE_ID column value. The first one counts all rows, regardless what's in EMPLOYEE_ID. [EDIT: a simple example which shows what's being counted] Reading comments below, well, some of them seem to be wrong (or I misunderstood the author's intent) so - here you go (based on 11.2.0.4.0). SQL> select * From a1_test; COL1 COL2 COL3 ---------- ---------- ---------- 1 3 1 2 1 2 3 2 3 3 SQL> SQL> select 2 count(*) cnt, 3 count(1) cnt_1, 4 count(2) cnt_2, 5 count(3) cnt_3, 6 -- 7 count(col1) cnt_c1, 8 count(col2) cnt_c2, 9 count(col3) cnt_c3 10 from a1_test; CNT CNT_1 CNT_2 CNT_3 CNT_C1 CNT_C2 CNT_C3 ---------- ---------- ---------- ---------- ---------- ---------- ---------- 5 5 5 5 3 3 4
unknown
d15571
val
Since the partition boundaries are stored in binary parsed form, all you can do is deparse them: SELECT c.oid::regclass AS child_partition, p.oid::regclass AS parent_tbl, pg_get_expr(c.relpartbound, c.oid) AS boundaries FROM pg_class AS p JOIN pg_inherits AS i ON p.oid = i.inhparent JOIN pg_class AS c ON i.inhrelid = c.oid WHERE p.relkind = 'p'; child_partition │ parent_tbl │ boundaries ═════════════════╪════════════╪══════════════════════════════════════════════════════════════════════════ part_2022 │ part │ FOR VALUES FROM ('2022-01-01 00:00:00+01') TO ('2023-01-01 00:00:00+01') (1 row) Analyzing the boundary string is left as exercise to the reader. A: You can find the information in the relpartbound column of the system catalog pg_class. Use the function pg_get_expr() to get the data readable: select relname as partition_table, pg_get_expr(relpartbound, oid) as partition_range from pg_class where relispartition and relkind = 'r'; partition_table | partition_range ---------------------+----------------------------- testpartpartition_1 | FOR VALUES FROM (1) TO (5) testpartpartition_2 | FOR VALUES FROM (6) TO (10) (2 rows) Use regexp_matches() to extract the numbers in parentheses select relname as partition_table, matches[1] as min_rangeval, matches[2] as max_rangeval from pg_class cross join regexp_matches(pg_get_expr(relpartbound, oid), '\((.+?)\).+\((.+?)\)') as matches where relispartition and relkind = 'r'; partition_table | min_rangeval | max_rangeval ---------------------+--------------+-------------- testpartpartition_1 | 1 | 5 testpartpartition_2 | 6 | 10 (2 rows) A: Here's the query that gets generated by \d+: edb=# SELECT c.oid::pg_catalog.regclass, c.relkind, false AS inhdetachpending, pg_catalog.pg_get_expr(c.relpartbound, c.oid) FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i WHERE c.oid = i.inhrelid AND i.inhparent = '33245' ORDER BY pg_catalog.pg_get_expr(c.relpartbound, c.oid) = 'DEFAULT', c.oid::pg_catalog.regclass::pg_catalog.text; oid | relkind | inhdetachpending | pg_get_expr ---------------------+---------+------------------+----------------------------- testpartpartition_1 | r | f | FOR VALUES FROM (1) TO (5) testpartpartition_2 | r | f | FOR VALUES FROM (6) TO (10) (2 rows) Looks like you need to use pg_get_expr() to decode the stuff in pg_class.relpartbound to reconstruct the range partition parameters. You can also replace i.inhparent = '33245' with a subquery to query by parent table name: edb=# SELECT c.oid::pg_catalog.regclass, c.relkind, false AS inhdetachpending, pg_catalog.pg_get_expr(c.relpartbound, c.oid) FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i WHERE c.oid = i.inhrelid AND i.inhparent = (SELECT oid from pg_class where relname = 'parentpartitiontbl') ORDER BY pg_catalog.pg_get_expr(c.relpartbound, c.oid) = 'DEFAULT', c.oid::pg_catalog.regclass::pg_catalog.text;
unknown
d15572
val
So guess I had a brain fart, left this a few days and came back and solved it almost immediately. Creating a While loop with a new variable C for the range While Range("A" & (5 * c)).Value <> "" c = c + 1 Wend This located the nearest empty Cell every 5 cells.
unknown
d15573
val
By default, Npgsql will set the client encoding to UTF8, which means that it is PostgreSQL's responsibility to provide valid UTF8 data, performing server-side conversions in case the database isn't in UTF8. However, the SQL_ASCII is special, in that it means "we don't know anything about characters beyond 127" (see the PG docs). So PostgreSQL performs no conversions on those. If you know that your database is in some specific non-UTF8 encoding (say, ISO 8859-1), you can pass the Client Encoding parameter on the connection string with the name of a valid .NET encoding. This will make Npgsql correctly interpret characters beyond 127 coming from PostgreSQL. If you really don't know what encoding your database uses, well, there's nothing much you can do... For more info, see this issue. A: AFAIK is not possible to enable postgres's built-in conversion from SQL_ASCII. Probably you should do it manually, using a tool like iconv ou recode. If the client character set is defined as SQL_ASCII, encoding conversion is disabled, regardless of the server's character set. Just as for the server, use of SQL_ASCII is unwise unless you are working with all-ASCII data. Quote from PostgreSQL documentation.
unknown
d15574
val
You may use (?s:.*\n)?\K\[(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2})\] Moving message 123456789 from NEW to PENDING See the regex demo Details * *(?s:.*\n)? - an inline modifier group that matches any 0+ chars as many as possible up to the last LF char that is followed with the last occurrence of the subsequent patterns. *\K - match reset operator removing all text matched so far from the match memory buffer *\[(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2})\] Moving message 123456789 from NEW to PENDING - the specific line pattern to get with the datetime captured in Group 1. Alternatively, use (?s)(\[\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2}\] Moving message 123456789 from NEW to PENDING)(?!.*(?1)) See this regex demo. Details * *(?s) - DOTALL modifier making . match any char *(\[(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2})\] Moving message 123456789 from NEW to PENDING) - the necessary pattern to match captured into Group 1 and the datetime in Group 2 *(?!.*(?1)) - a negative lookahead that fails the match if there is the same pattern as defined in Group 1 after any 0+ chars to the right of the current position. A: Here is a solution that is not dependent on PCRE feature using negative lookahead: (?s)\[(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2})\] Moving message 123456789 from NEW to PENDING(?!.* Moving message 123456789 from NEW to PENDING) RegEx Demo Date-time is available in 1st capture group. Here (?!.* Moving message 123456789 from NEW to PENDING) is negative lookahead that ensures we match very last occurrence of given pattern.
unknown
d15575
val
Here's how I take a screenshot: IDirect3DSurface9 *offscreenSurface; d3dDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &offscreenSurface); D3DXSaveSurfaceToFile( filename, D3DXIFF_BMP, offscreenSurface, 0, 0 )
unknown
d15576
val
You need to print each value with the correct format specifier. Here we want numerical representations, not character ones. From the documentation on printf: * *%c writes a single character *%d converts a signed integer into decimal representation *%x converts an unsigned integer into hexadecimal representation %02X prints a hexadecimal with a minimum width of two characters, padding with leading zeroes, using ABCDEF (instead of abcdef). See also implicit conversions. An example: #include <stdio.h> #define SIZE 8 int main(int argc, char **argv) { unsigned char magic[SIZE]; FILE *file = fopen(argv[1], "rb"); if (!file || fread(magic, 1, SIZE, file) != SIZE) { fprintf(stderr, "Failure to read file magic.\n"); return 1; } /* Decimal */ for (size_t i = 0; i < SIZE; i++) printf("%d ", magic[i]); printf("\n"); /* Hexadecimal */ for (size_t i = 0; i < SIZE; i++) printf("%02X ", magic[i]); printf("\n"); fclose(file); } Output: 137 80 78 71 13 10 26 10 89 50 4E 47 0D 0A 1A 0A
unknown
d15577
val
I am fairly new to android as well, but it sounds like you need to add a layout align tag to the adView. That ought to push the application up and put the add at the bottom. I hope this helps a little bit! A: its a simple one: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" android:layout_weight="1.0"/> <LinearLayout android:layout_height="60dp" android:layout_width="match_parent" android:orientation="vertical"> <TextView android:layout_height="wrap_content" android:text="add your ad here" android:layout_width="wrap_content"/> </LinearLayout>
unknown
d15578
val
follow the following code. It inserts two columns into a table (tableName). Maintain proper space in SQL query as showing in below sample code. ALso, it's best practice to keep the code in a try-catch block to capture any error that occurs during DB operation. try { SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator"); con.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "insert into tableName(column1,column2) values(@nm,@nmm)"; cmd.Parameters.AddWithValue("@nm", Vorname.Text); cmd.Parameters.AddWithValue("@nmm", Nachname.Text); cmd.Connection = con; int a = cmd.ExecuteNonQuery(); if (a == 1) { MessageBox.Show("Dateien bitte"); } } catch (Exception ex) { MessageBox.Show("Error:"+ex.ToString()); }
unknown
d15579
val
i did this simple task and worked like charm: data(){ return{ api_value:0 } }, beforeCreate(){ axios.get('my-api-link) .then(response=>{ this.api_value = response.data.api_value }) }, computed:{ inject_theme(){ if(this.api_value ==1) return '/theme/dark.css' else if (this.api_value ==2) return '/theme/dark.1.css' else if (this.api_value ==3) return '/theme/dark.2.css' } }, head () { return { title: this.title, meta: [ { hid: 'description', name: this.inject_theme, content: 'My custom description' } ], link:[ {rel:'stylesheet',href:this.inject_theme} ] } }
unknown
d15580
val
Using dplyr: library(dplyr) df <- data.frame(user =c("P001", "P001", "P002"), tripID = c("tid1", "tid2", "tid3"), mode =c("bus", "train", "taxi"), Origin = c("Westmead", "Redfan", "Westmead"), Destination = c("Redfan", "Darlington", "Strathfield"), depart_dt = c("8:00", "8:30", "8:45") ) df %>% group_by(user) %>% arrange(depart_dt, .by_group = TRUE) %>% summarize(Origin = Origin[1], mode = paste(mode, collapse = " + "), Destination = Destination[length(Destination)], depart_dt = depart_dt[1]) %>% mutate(tripID = paste0("newtid", row_number())) #> # A tibble: 2 x 6 #> user Origin mode Destination depart_dt tripID #> <fct> <fct> <chr> <fct> <fct> <chr> #> 1 P001 Westmead bus + train Darlington 8:00 newtid1 #> 2 P002 Westmead taxi Strathfield 8:45 newtid2 Created on 2020-05-06 by the reprex package (v0.3.0) A: You don't need to use spread() or gather() (or their successors pivot_longer. and pivot_wider(). The below should give you what you want. library(tidyverse) df %>% group_by(user) %>% arrange(tripID, .by_group = TRUE) %>% summarise(mode = str_c(mode, collapse = " + "), Origin = first(Origin), Destination = last(Destination), depart_dt = first(depart_dt)) %>% mutate(tripID = str_c("newtrid", row_number())) # user mode Origin Destination depart_dt tripID # <fct> <chr> <fct> <fct> <fct> <chr> # 1 P001 bus + train Westmead Darlington 8:00 newtrid1 # 2 P002 taxi Westmead Strathfield 8:45 newtrid2
unknown
d15581
val
You could create the axes independently of the figure. I would also recommend this method because you have more control over the axes, for example you could have different shaped axes. Code: import numpy as np import matplotlib.pyplot as plt fig = plt.figure() for ii in range(5): ax = fig.add_subplot(4,3,ii+1) ax.scatter(np.random.random(5),np.random.random(5)) ax.set_xlabel('xlabel') ax.set_ylabel('ylabel') fig.tight_layout() fig.show() Result: A: The second case of deleting the axes works fine if it is used on its own (without the code from the first case executed) and if the figure is first saved and then shown, fig,axs=prep_figure() for ii in range(5,12): fig.delaxes(axs[ii]) plt.tight_layout() plt.savefig('tmpd.pdf', ) plt.show() The third case works fine if again, the figure is saved before showing it, and instead of making it invisible, turning the axes off via ax.axis("off"). fig,axs=prep_figure() for ii in range(5,12): axs[ii].axis("off") plt.tight_layout() plt.savefig('tmph.pdf', ) plt.show() The created pdf is the same in both cases:
unknown
d15582
val
You can use the following trick: #define SELF \ static auto helper() -> std::remove_reference<decltype(*this)>::type; \ typedef decltype(helper()) self struct A { SELF; }; I declare a helper function using the auto return type, which allows me to use decltype(*this) as a return type, not knowing what is the class name. Then I can use decltype(helper()) to use the class type in the code. Note that the function has to be static, otherwise you can not use it in decltype. Also the function is just declared, not defined; this should not be a problem as you are not going to call it anyway. (You can add an empty body to it, but it will raise a warning that a function has no return. Still you may change the return type to be decltype(this) and return nullptr.) You may then use the self typedef for further declarations, or just alter the macros to typedef not the class itself, but what you need to. Adjust it to suit your particular need. UPD: This seems to be a non-standard behavior of GCC. For example, ICC does not allow this in static functions even in trailing return type.
unknown
d15583
val
The ArcPy module is case sensitive, so you need to capitalize those objects, e.g. pt=arcpy.Point(x, y) point=arcpy.Polyline(parray)
unknown
d15584
val
Ok, I figured this out, it was me being stupid, but then the answer might help someone else, so here goes. The [Order Details] table has a composite key and is linked to the both the [Orders] and [Products] table (Yes, this is the Northwind database that I am working with). For my test, I hadn't mapped my Products table, and had marked up my [Order Details] class with a single primary key, rather than a composite key. So, when Nhibernate deleted rows based on the key, it expects to see only one row being deleted whereas multiple existed on the database. Which is why I was getting the error. Rather clever of Nhibernate.
unknown
d15585
val
You have to add additional columns and expand your data. For example: chartData.addColumn('string', 'X'); // Implicit series 1 data col. chartData.addColumn('number', 'DOGS'); // Implicit domain label col. chartData.addColumn({type:'string', role:'annotation'}); chartData.addColumn({type:'string', role:'annotationText'}); chartData.addColumn('number', 'CATS'); // Implicit domain label col. chartData.addColumn({type:'string', role:'annotation'}); chartData.addColumn({type:'string', role:'annotationText'}); var data1 = [ [ 'C', 4, 'Dog1', 'Dog1 note', 7, 'Cat1', 'Cat1 note'], [ 'D', 6, 'Dog2', 'Dog2 note', 11, 'Cat2', 'Cat3 note'], [ 'O', 4, 'Dog3', 'Dog3 note', 13, 'Cat3', 'Cat3 note'] ]; chartData.addColumn('string', 'X'); // Implicit series 1 data col. chartData.addColumn('number', 'DOGS'); // Implicit domain label col. chartData.addColumn({type:'string', role:'annotation'}); chartData.addColumn({type:'string', role:'annotationText'}); chartData.addColumn('number', 'CATS'); // Implicit domain label col. chartData.addColumn({type:'string', role:'annotation'}); chartData.addColumn({type:'string', role:'annotationText'}); var data1 = [ [ 'C', 4, 'Dog1', 'Dog1 note', 7, 'Cat1', 'Cat1 note'], [ 'D', 6, 'Dog2', 'Dog2 note', 11, 'Cat2', 'Cat3 note'], [ 'O', 4, 'Dog3', 'Dog3 note', 13, 'Cat3', 'Cat3 note'] ]; chartData.addRows(data1); See example at jsBin
unknown
d15586
val
Based on the information that you've provided its hard to tell what happens, I suspect (just a wild guess) that logging infrastructure wasn't configured at all, because this file somehow hasn't propagated to the artifact (WAR, I assume) When you run the application you can place a breakpoint on any log.*** message(like log.info) and check whether it has any assigned appenders in a list, again, as a hypothesis the list of appenders will be just empty. A: I am getting default logger for my wildfly server. After modified the server configuration the problem will solved. Place the jboss-deployment-structure.xml file under META-INF. jboss-deployment-structure.xml <?xml version="1.0" encoding="UTF-8"?> <jboss-deployment-structure> <deployment> <exclusions> <module name="org.apache.commons.logging" /> <module name="org.apache.log4j" /> <module name="org.jboss.logging" /> <module name="org.jboss.logging.jul-to-slf4j-stub" /> <module name="org.jboss.logmanager" /> <module name="org.jboss.logmanager.log4j" /> <module name="org.slf4j" /> <module name="org.slf4j.impl" /> </exclusions> </deployment> </jboss-deployment-structure>
unknown
d15587
val
I faced with this problem too. i use this link: dynamically load an icon. save my menu icon name at database and use <Icon>{props.iconName}</Icon> but, it doesn't work for me. so because i don't have so much time i just save the SVG format of material ui icon in my database and restore it at my JSX. i got SVG format of icons from inspect element of browser from material ui icon web page
unknown
d15588
val
In short, you can copy the file from microk8s instance that kubectl is using (kubeconfig) to the Windows machine in order to connect to your microk8s instance. As you already have full connectivity between the Windows machine and the Ubuntu that microk8s is configured on, you will need to: * *Install kubectl on Windows machine *Copy and modify the kubeconfig file on your Windows machine *Test the connection Install kubectl You can refer to the official documentation on that matter by following this link: * *Kubernetes.io: Docs: Tasks: Tools: Install kubectl Windows Copy and modify the kubeconfig file on your Windows machine IMPORTANT! After a bit of research, I've found easier way for this step. You will need to run microk8s.config command on your microk8s host. It will give you the necessary config to connect to your instance and you won't need to edit any fields. You will just need to use it with kubectl on Windows machine. I've left below part to give one of the options on how to check where the config file is located This will depend on the tools you are using but the main idea behind it is to login into your Ubuntu machine, check where the kubeconfig is located, copy it to the Windows machine and edit it to point to the IP address of your microk8s instance (not 127.0.0.1). If you can SSH to the VM you can run following command to check where the config file is located (I would consider this more of a workaround solution): * *microk8s kubectl get pods -v=6 I0506 09:10:14.285917 104183 loader.go:379] Config loaded from file: /var/snap/microk8s/2143/credentials/client.config I0506 09:10:14.294968 104183 round_trippers.go:445] GET https://127.0.0.1:16443/api/v1/namespaces/default/pods?limit=500 200 OK in 5 milliseconds No resources found in default namespace. As you can see in this example, the file is in (it could be different in your setup): * */var/snap/microk8s/2143/credentials/client.config You'll need to copy this file to your Windows machine either via scp or other means. After it's copied, you'll need to edit this file to change the field responsible for specifying where the kubectl should connect to: * *before: * * server: https://127.0.0.1:16443 *after: * * server: https://ubuntuk8s:16443 Test the connection One of the ways to check if you can connect from your Windows machine to microk8s instance is following: PS C:\Users\XYZ\Desktop> kubectl --kubeconfig=client.config get nodes -o wide NAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIME ubuntu Ready <none> 101m v1.20.6-34+e4abae43f6acde 192.168.0.116 <none> Ubuntu 20.04.2 LTS 5.4.0-65-generic containerd://1.3.7 Where: * *--kubeconfig=client.config is specifying the file that you've downloaded Additional resources: * *Kubernetes.io: Docs: Concepts: Configuration: Organize cluster access kubeconfig *Github.com: Ubuntu: Microk8s: Issues: Cannot connect to microk8s from another machine - this link pointed me to microk8s.config
unknown
d15589
val
The Entity classes are partial classes as far as i know, so you can add another file extending them directly using the partial keyword. Else, i usually have a wrapper class, i.e. my ViewModel (i'm using WPF with MVVM). I also have some generic Helper classes with fluent interfaces that i use to add specific query filters to my ViewModel. A: I think it's a mistake to put behaviors on entity types at all. The Entity Framework is based around the Entity Data Model, described by one of its architects as "very close to the object data model of .NET, modulo the behaviors." Put another way, your entity model is designed to map relational data into object space, but it should not be extended with methods. Save your methods for business types. Unlike some other ORMs, you are not stuck with whatever object type comes out of the black box. You can project to nearly any type with LINQ, even if it is shaped differently than your entity types. So use entity types for mapping only, not for business code, data transfer, or presentation models. Entity types are declared partial when code is generated. This leads some developers to attempt to extend them into business types. This is a mistake. Indeed, it is rarely a good idea to extend entity types. The properties created within your entity model can be queried in LINQ to Entities; properties or methods you add to the partial class cannot be included in a query. Consider these examples of a business method: public Decimal CalculateEarnings(Guid id) { var timeRecord = (from tr in Context.TimeRecords .Include(“Employee.Person”) .Include(“Job.Steps”) .Include(“TheWorld.And.ItsDog”) where tr.Id = id select tr).First(); // Calculate has deep knowledge of entity model return EarningsHelpers.Calculate(timeRecord); } What's wrong with this method? The generated SQL is going to be ferociously complex, because we have asked the Entity Framework to materialize instances of entire objects merely to get at the minority of properties required by the Calculate method. The code is also fragile. Changing the model will not only break the eager loading (via the Include calls), but will also break the Calculate method. The Single Responsibility Principle states that a class should have only one reason to change. In the example shown on the screen, the EarningsHelpers type has the responsibility both of actually calculating earnings and of keeping up-to-date with changes to the entity model. The first responsibility seems correct, the second doesn't sound right. Let's see if we can fix that. public Decimal CalculateEarnings(Guid id) { var timeData = from tr in Context.TimeRecords where tr.Id = id select new EarningsCalculationContext { Salary = tr.Employee.Salary, StepRates = from s in tr.Job.Steps select s.Rate, TotalHours = tr.Stop – tr.Start }.First(); // Calculate has no knowledge of entity model return EarningsHelpers.Calculate(timeData); } In the next example, I have rewritten the LINQ query to pick out only the bits of information required by the Calculate method, and project that information onto a type which rolls up the arguments for the Calculate method. If writing a new type just to pass arguments to a method seemed like too much work, I could have also projected onto an anonymous type, and passed Salary, StepRates, and TotalHours as individual arguments. But either way, we have fixed the dependency of EarningsHelpers on the entity model, and as a free bonus we've gotten more efficient SQL, as well. You might look at this code and wonder what would happen if the Job property of TimeRecord where nullable. Wouldn't I get a null reference exception? No, I would not. This code will not be compiled and executed as IL; it will be translated to SQL. LINQ to Entities coalesces null references. In the example query shown on the screen, StepRates would simply return null if Job was null. You can think of this as being identical to lazy loading, except without the extra database queries. The code says, "If there is a job, then load the rates from its steps." An additional benefit of this kind of architecture is that it makes unit testing of the Web assembly very easy. Unit tests should not access a database, generally speaking (put another way, tests which do access a database are integration tests rather than unit tests). It's quite easy to write a mock repository which returns arrays of objects as Queryables rather than actually going to the Entity Framework.
unknown
d15590
val
The commands that you use on your local machine are the same commands you can run in CodeShip Basic. CodeShip Basic is just a build machine with Ubuntu Bionic and it will run through the setup, test, and deploy commands as if you were entering each line into your CLI. :) We also have some documentation about mysql: https://documentation.codeship.com/basic/databases/mysql/ A: OK, after some digging I found out how to do all this. Below is the script I used for testing with a new mysql schema created with specific user from a sql script. Hope this helps someone in the future. mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "CREATE USER 'myuser'@'%' IDENTIFIED BY 'testpassword';" mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "CREATE SCHEMA myschemaname;" mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'%' IDENTIFIED BY 'testpassword';" mysql -u $MYSQL_USER -p$MYSQL_PASSWORD myschemaname < ./app/Ship/Migrations/1of2-schema.sql mysql -u $MYSQL_USER -p$MYSQL_PASSWORD myschemaname < ./app/Ship/Migrations/2of2-seed.sql php artisan passport:install ./vendor/bin/phpunit $MYSQL_USER and $MYSQL_PASSWORD are replaced by Codeship - these are the env variables for the user and password for the mysql that exists in the build container. the -e switch on the mysql call runs the script given and exits. Had to do it this way since I couldn't interact with the mysql client.
unknown
d15591
val
I'll just deal with performance and naive security checks since writing a sanitizer is not something you can do on the corner of a table. If you want to save time, avoid calling multiple times replace() if you replace with the same value, which leads you to this: function safe_content( text ) { text = text.replace( /<script[^>]*>.*?<\/script>|(<\/?p[^>]*>)/gi, '' ); text = text.replace( /'|&#039;|[\u2019]/g, '&#8217;'); text = text.replace( /"|&#034;|&quot;|[\u201D]/g, '&#8221;' ) text = text.replace( /([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g, '$1="$2"' ); return text.trim(); }; If you take into account dan1111's comment about weird string input that will break this implementation, you can add while(/foo/.test(input)) to avoid the issue: function safe_content( text ) { while(/<script[^>]*>.*?<\/script>|(<\/?p[^>]*>)/gi.test(text)) text = text.replace( /<script[^>]*>.*?<\/script>|(<\/?p[^>]*>)/gi, '' ); while(/'|&#039;|[\u2019]/g.test(text)) text = text.replace( /'|&#039;|[\u2019]/g, '&#8217;'); while(/"|&#034;|&quot;|[\u201D]/g.test(text)) text = text.replace( /"|&#034;|&quot;|[\u201D]/g, '&#8221;' ) while(/([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g.test(text)) text = text.replace( /([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g, '$1="$2"' ); return text.trim(); }; in standard tests cases, this will not be a lot slower than the previous code. But if the input enter in the scope of dan1111's comment, it might be slower. See perf demo
unknown
d15592
val
I don't like answers to StackOverflow Questions of the form "well even though you asked how to do X, you don't really want to do X, you really want to do Y, so here's a solution to Y" But that's what i am going to do here. I think such an answer is justified in this rare instance becuase the answer below is in accord with sound practices in statistical analysis and because it avoids the current problem in front of you which is crunching 4 GB of datda. If you want to represent the distribution of a population using a non-parametric density estimator, and you wwish to avoid poor computational performance, a kernel density estimator (KDE) will do the job far better than a histogram. To begin with, there's a clear preference for KDEs versus histograms among the majority of academic and practicing statisticians. Among the numerous texts on this topic, ne that i think is particularly good is An introduction to kernel density estimation ) Reasons why KDE is preferred to histogram * *the shape of a histogram is strongly influenced by the choice of total number of bins; yet there is no authoritative technique for calculating or even estimating a suitable value. (Any doubts about this, just plot a histogram from some data, then watch the entire shape of the histogram change as you adjust the number of bins.) *the shape of the histogram is strongly influenced by the choice of location of the bin edges. *a histogram gives a density estimate that is not smooth. KDE eliminates completely histogram properties 2 and 3. Although KDE doesn't produce a density estimate with discrete bins, an analogous parameter, "bandwidth" must still be supplied. To calculate and plot a KDE, you need to pass in two parameter values along with your data: kernel function: the most common options (all available in the MATLAB kde function) are: uniform, triangular, biweight, triweight, Epanechnikov, and normal. Among these, gaussian (normal) is probably most often used. bandwith: the choice of value for bandwith will almost certainly have a huge effect on the quality of your KDE. Therefore, sophisticated computation platforms like MATLAB, R, etc. include utility functions (e.g., rusk function or MISE) to estimate bandwith given oother parameters. KDE in MATLAB kde.m is the function in MATLAB that implementes KDE: [h, fhat, xgrid] = kde(x, 401); Notice that bandwith and kernel are not supplied when calling kde.m. For bandwitdh: kde.m wraps a function for bandwidth selection; and for the kernel function, gaussian is used. But will using KDE in place of a histogram solve or substantially eliminate the very slow performance given your 2 GB dataset? It certainly should. In your Question, you stated that the lagging performance occurred during plotting. A KDE does not require mapping of thousands (missions?) of data points a symbol, color, and specific location on a canvas--instead it plots a single smooth line. And because the entire data set doesn't need to be rendered one point at a time on the canvas, they don't need to be stored (in memory!) while the plot is created and rendered.
unknown
d15593
val
Well, looks like Winston writes to logs based on their numeric levels. So that error messages will be always written to info log, but info never to error log. So I think it is better to separate to different instances in config/bootstrap.js: sails.warnLog = new (winston.Logger)({ transports: [ new (winston.transports.Sentry)({ name: 'warn-Sentry', dsn: '{my account dsn}', patchGlobal: true level: 'warn' }) ]}); sails.infLog = new (winston.Logger)({ transports: [ new (winston.transports.Loggly)({ name: 'info-Loggly', subdomain: '{my subdomain}', inputToken: '{my input token}' level: 'info' }) ]}); sails.verbLog = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ name: 'verb-console', timestamp: true, prettyPrint: true, colorize: true, level: 'verbose' }) ]}); And then you can write to log: sails.warnLog.warn('Warning'); sails.infLog.info('Information'); sails.verbLog.verbose('Verbose'); In fact, I do not like this way. It is ugly =(
unknown
d15594
val
Use exactRankTests::wilcox.exact: If x is a weight for example time 0 e.g. chick$weight.0 and y is a weight for example time 2 e.g. chick$weight.2 Then you could do it this way: With wilcox.test you will get a warning message: > wilcox.test(c(chick$weight.0, 200), chick$weight.2)$p.value [1] 6.660003e-14 Warning message: In wilcox.test.default(c(chick$weight.0, 200), chick$weight.2) : cannot compute exact p-value with ties Use exactRankTests::wilcox.exact() that can handle ties: t.test(chick$weight.0,chick$weight.2)$p.value 6.660003e-14 exactRankTests::wilcox.exact(c(chick$weight.0, 200), chick$weight.2)$p.value [1] 5.889809e-18
unknown
d15595
val
You’re using the wrong kind of value for the usecols attribute. Check the documentation: usecols: str, list-like, or callable, default None If None, then parse all columns. If str, then indicates comma separated list of Excel column letters and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of both sides. If list of int, then indicates list of column numbers to be parsed (0-indexed). If list of string, then indicates list of column names to be parsed. If callable, then evaluate each column name against it and parse the column if the callable returns True. Returns a subset of the columns according to behavior above.
unknown
d15596
val
IIS 6 is part of Windows Server 2003 (and technically XP 64-bit). The .NET Framework 4.5 System Requirements indicate that Server 2003, thus IIS 6, is not supported. A: Not trying to throw the last answer off, this could be a typo on MS website, but looking for the same question, I found this. http://msdn.microsoft.com/en-us/library/ms733890.aspx "WCF can also be installed on Windows XP SP2, Windows Server 2003 R2, or Windows Server 2003 SP1" and that is while I have .net 4.5 selected at the top. I am thinking typo.. but hopeful ;)
unknown
d15597
val
If you mean having multiple WHERE's (ands), then yes. SELECT user.id, post.title FROM user LEFT JOIN post ON (post.user = user.id) WHERE (post.title LIKE '%Monkeys%') AND (user.id > 3) AND (user.id < 20)
unknown
d15598
val
Adding a new image element is pretty easy: // Append an image with source src to element function appendImage(element, src, alt) { // DOM 0 method var image = new Image(); // DOM 1+ - use this or above method // var image = document.createElement('img'); // Set path and alt properties image.src = src; image.alt = alt; // Add it to the DOM element.appendChild(image); // If all went well, return false so navigation can // be cancelled based on function outcome return false; } so in an A element: <a onclick="appendImage(this, 'foo.jpg', 'Picture of foo');">Add an image</a> If the A is a link and you wish to cancel navigation, return whatever the function returns. If the function doesn't return false, the link will be followed and should provide equivalent functionality: <a href="link_to_picture or useful page" onclick=" return appendImage(this, 'foo.jpg', 'Picture of foo'); ">Add an image</a> A: You should use like this. There are several other good methods, this is just for simplicity and understanding purpose <body> <a onClick='ChangeImage(this);return false'> Click Me <a> </body> <script> function ChangeImage(obj) { obj.innerHTML = "<img src='imangename.jpg'>"; } </script> A: The javascript plugin you may need is Highslides, Check here for examples. Download highslides here. A: First, you'll probably want to give the link an ID. <a id="click-me">Click me!</a> Then for the JavaScript.. document.getElementById('click-me').addEventListener('click', function () { var image = new Image(); image.src = "your-picture.jpeg/png/whatever"; this.appendChild(image); });
unknown
d15599
val
On Postgres, DISTINCT ON comes in handy here: SELECT DISTINCT ON (integration_id) * FROM yourTable WHERE name = 'approved' ORDER BY integration_id, date;
unknown
d15600
val
You are looking for something like this output my_intersection { value = setintersection( toset(var.list1), toset(var.list2) ) }
unknown