id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23535700
Is it known exactly where this file is located, and how would one interface with that? I would like that table to contain a URL for each user in addition to their password. ( I am guessing the 'table' only contains user and password ). Is this possible or would I be better of creating my own login/register system? I know it wouldn't be that much coding, but it would sure be nice to utilize what is already there. Please spare me if this is easily edited up in a menu somewhere. Was unknowingly thrown into a aspx project with little previous experience. Taking in info as fast as I can! Thanks in advance for your inputs! A: If you use the Membership class you have access to all the methods you need. This class includes methods for: * *Creating users *Changing their password *Deleting Users *etc. The users are stored in the aspnetdb and the information is in several tables. The main ones are: * *aspnet_User - this stores the users *aspnet_Applications - which applications are running *aspnet_Membership - this relates the users to the applications they are authorised for *aspnet_Profile - user profile information the the application This is a standard SQL database that exists on your SQL Server. For a fuller explanation read this MSDN article. A: The users are stored in the ASPNETDB.MDF database in the App_Data folder.This file is hidden by default so I can understand why you're confused. To make ASPNETDB visible - select the App_Data folder in Solution Explorer and click Show All Files. Now if you click on the .mdf file the database will open in the Server Explorer in Visual Studio. The user information is located in the aspnet_Users and aspnet_Membership tables. The query below will return the user id, user name,encrypted password and email: SELECT aspnet_Users.UserId, aspnet_Users.UserName, aspnet_Membership.Password, aspnet_Membership.Email FROM aspnet_Users INNER JOIN aspnet_Membership ON aspnet_Users.UserId = aspnet_Membership.UserId
doc_23535701
Thanks. <script> function ChangeDropdowns() { if ("Delivery_y:checked") { document.getElementById('BuyProduct_H').style.display = 'block'; } else if ("Delivery_n:checked") { document.getElementById('BuyProduct_H').style.display = 'none'; } } </script> This is the table that contains the Yes/No question. <table id="YesNo" style="width:100%;"> <tr> <td class="auto-style2" colspan="3">*&nbsp; Have you recently bought any electronic products from AlGhanim electronics that required delivery/ Installation Service? </td> </tr> <tr> <td class="auto-style28">&nbsp;</td> <td class="auto-style23"> <input type="radio" name="Delivery" id ="Delivery_y" onclick="displayResult(this.value)" value="Yes" >Yes</td> <td>(Continue)</td> </tr> <tr> <td class="auto-style28">&nbsp;</td> <td class="auto-style23"> <input type="radio" name="Delivery" id ="Delivery_n" onclick="displayResult(this.value)" value="No">No</td> <td>(Terminate)</td> </tr> </table> This is the table that I want to hide when answering no to the first question: <table name="BuyProduct" id ="BuyProduct_H" style="width:100%;"> <tr> <td class="auto-style2" colspan="3">1-&nbsp;&nbsp;&nbsp;&nbsp; What were the products that you bought? </tr> <tr> <td class="auto-style28">&nbsp;</td> <td colspan="2"> <asp:CheckBox ID="Button11" Text="a. Air Conditioning" runat="server" /> </td> </tr> <tr> <td class="auto-style28">&nbsp;</td> <td colspan="2"> <asp:CheckBox ID="Button12" Text="b. TV Radio (TV, Home Theatre, etc.)" runat="server" /></td> </tr> <tr> <td class="auto-style28">&nbsp;</td> <td colspan="2"> <asp:CheckBox ID="Button13" Text="c. Refrigeration" runat="server" /> </td> </tr> <tr> <td class="auto-style28">&nbsp;</td> <td colspan="2"> <asp:CheckBox ID="Button14" Text="d. Laundry (Washer, Dryer, etc)" runat="server" /> </td> </tr> <tr> <td class="auto-style28">&nbsp;</td> <td colspan="2"> <asp:CheckBox ID="Button15" Text="e. Dishwasher" runat="server" /></td> </tr> <tr> <td class="auto-style28">&nbsp;</td> <td colspan="2"> <asp:CheckBox ID="Button16" Text="f. Water Treatment (Water Dispencer)" runat="server" /> </td> </tr> <tr> <td class="auto-style28">&nbsp;</td> <td colspan="2"> <asp:CheckBox ID="Button17" Text="g. Small Housewares (Microwave, Kitchen appliances, etc.)" runat="server" /> <br /> <asp:CheckBox ID="Button18" Text="h. Others Please Specify" runat="server" /> </td> </tr> <tr> <td class="auto-style28">&nbsp;</td> <td class="auto-style51"></td> <td> <asp:TextBox ID="TextBox26" runat="server"></asp:TextBox> </td> <td> &nbsp;</td> </tr> <tr> <td class="auto-style28">&nbsp;</td> <td colspan="2"> &nbsp;</td> </tr> </table> A: "show" and "hide" are not valid values for display. Try "block" (or "inline-block") and "none", respectively, instead. See here for valid values: http://www.w3schools.com/jsref/prop_style_display.asp Also, you need to call your ChangeDropdowns() function for it to work. A: In addition to what @mayabelle pointed out in his answer (that hide and show should be replaced by style.display = 'none' and style.display = 'block' respectively), your verification in the if statement if ("Delivery_y:checked") will not work. Instead, you can check if an element is checked in javascript in the following way: if (document.getElementById('Delivery_y').checked) Alternatively, you can do this in jQuery: if ($('Delivery_y').is(':checked')) A: I Applied what Raul Rene and mayabelle to my Script: This is the script before: <script> function ChangeDropdowns() { if ("Delivery_y:checked") { document.getElementById('BuyProduct_H').style.display = 'block'; } else if ("Delivery_n:checked") { document.getElementById('BuyProduct_H').style.display = 'none'; } } </script> This is The Script After: <script> function ChangeDropdowns() { if (document.getElementById('Delivery_y').checked) { document.getElementById('BuyProduct_H').style.display = 'block'; } else if (document.getElementById('Delivery_n').checked) { document.getElementById('BuyProduct_H').style.display = 'none'; } } </script> I changed the Yes/No Table: Before: input type="radio" name="Delivery" id ="Delivery_y" onclick="displayResult(this.value)" value="Yes" >Yes</td> <td>(Continue)</td> </tr> <tr> <td class="auto-style28">&nbsp;</td> <td class="auto-style23"> <input type="radio" name="Delivery" id ="Delivery_n" onclick="displayResult(this.value)" value="No">No</td> <td>(Terminate)</td> </tr> After: <input type="radio" name="Delivery" id ="Delivery_y" onclick="displayResult(this.value)" onchange="ChangeDropdowns()" value="Yes" >Yes</td> <td>(Continue)</td> </tr> <tr> <td class="auto-style28">&nbsp;</td> <td class="auto-style23"> <input type="radio" name="Delivery" id ="Delivery_n" onclick="displayResult(this.value)" onchange="ChangeDropdowns()" value="No">No</td> <td>(Terminate)</td> </tr> It Worked Perfectly. Thank you all.
doc_23535702
#include <iostream> #include <fstream> #include <string> #include <algorithm> using namespace std; //knapsack here int knapsack(int cap, int weight[], int value[], int n) { int** K = new int* [n + 1]; int j = 0; int l = 0; for (int i = 0; i < n + 1; i++) { K[i] = new int[cap + 1]; } for (j = 0; j <= n; j++) { for (l = 0; l <= cap; l++) { if (j == 0 || l == 0) K[j][l] = 0; else if (weight[j - 1] <= l) { K[j][l] = max(weight[j - 1] + K[j - 1][l - weight[j - 1]], K[j - 1][l]); } else { K[j][l] = K[j - 1][l]; } } } return K[j][l]; <--- Exception thrown } int main(void) { string filename; ifstream infile; int capacity = 0; int items = 0; //Get input file from user and open cout << "Enter the file name: "; cin >> filename; infile.open(filename); //Get capacity and number of items infile >> capacity >> items; //Initialize arrays int* w = new int[items]; int* v = new int[items]; //Read values from file into arrays for (int i = 0; i < items; i++) { infile >> w[i]; infile >> v[i]; } //Solution Table cout << endl << endl << endl; cout << "Solution Table:" << endl; //Testing purposes cout << knapsack(capacity, w, v, items) << endl << "Test"; infile.close(); return 0; } Everything that is printed in main will print up until the final cout (after the Solution Table: line prints). The program will then pause for a moment and exit with an error code (C:\Users\Me\source\repos\Project3\Debug\Project3.exe (process 3028) exited with code -1073741819). I haven't been able to figure out a way to get a return from the function yet, and the exiting is something I haven't been able to figure out why it is occurring either. EDIT: On using the debugger, an exception is being thrown when running through the knapsack function on the return: Exception thrown at 0x006BB128 in Project3.exe: 0xC0000005: Access violation reading location 0xFDFDFE0D A: int** K = new int* [n + 1]; // ... K[i] = new int[cap + 1]; // ... for (j = 0; j <= n; j++) { for (l = 0; l <= cap; l++) { // ... } } // j == n + 1 // l == cap + 1 return K[j][l]; <--- Exception thrown because of out of bounds access to K K is an array of length n + 1, which means its elements are accessed using indices from O to (inclusive) n. n + 1 is an out of bound access. At the end of the (outer) for loop the variable j is n + 1. You make the same error with the inner loop and the second operator[]. That being said, it helps a lot if you: * *Ditch the idea of "2d arrays". These arrays of pointers to arrays are difficult to handle and have a heavy performance impact (messed up memory locality). They are (probably) only useful when the "full" array (e.g. the 2D table flattened into a single array) is too large to reliably get successfully allocated. *Use std::vector. There is really no point working with raw arrays. Except for learning. And in that case: delete[] the memory you allocate! *Why is "using namespace std;" considered bad practice? A: C-style strings might cause problems. They are hard to maintain and track. I support Jesper's idea here. Also, I do not see that you are freeing the memory after you are done with the pointers which will create memory leakage.
doc_23535703
In a lot of documentation all over the Internet I have read that the idle workers should never stay at 0. Is this true? I am going to put for example certain graphs of my server, there are several peaks where you can see that my server runs out of idle workers at certain times, but the vast majority of the time my idle workers are almost never at zero. My Apache MPM type is prefork. I am working on an EC2 m5.8xlarge server with the following configuration: * *32 vCPU *128 Memory(GiB) *Storage EBS *10 Gbps Network Bandwidth *6,800 Mbps EBS Bandwidth This server is only dedicated to Apache. My database is in RDS. Looking at the ram memory utilization of my server, I have almost 120Gb/128Gb free just for my apache. For this reason, following several tutorials on the Internet on how to optimize apache I have obtained and applied the following configurations: IfModule mpm_prefork_module> ServerLimit 749 StartServers 225 MinSpareServers 37 MaxSpareServers 75 MaxRequestWorkers 749 MaxConnectionsPerChild 10000 </IfModule> Still I am having certain "problems" with idle workers, that actually I don't know if it is problem to stay without idle worker for some minutes (look at graph of my server). I must say that my site has a concurrency of approximately 600-800 connections. But looking at my server capacity, this should be enough. Can anyone give me some light on this, is this behavior normal? Also, I leave you other graphs and values, to see if you think these are normal values or not at all.
doc_23535704
Ads, Promote, Build As I route to another rendering, the values of the the useState hook are resetting which includes the array. Related functions const [calculator, setCalculator] = useState({section: [], graphic: false}); //Sections array inside // Responsible to add item to the array, also promote and ads, just short version so you can understand function addPath(section){ if(section === "build"){ if(calculator.section.some(val => val === "build")){ let filteredArray = calculator.section.filter(item => item !== 'build') setCalculator({section: filteredArray}); $('.build').removeClass('active'); } else{ var joined = calculator.section.concat('build'); setCalculator({ section: joined }) $('.build').addClass('active'); } } } //Route from /start to /values const Continue = () =>{ history.push("/values"); history.go(0); } // Check if the item exist in the array after routing the page function checkArray(val) { return calculator.section.some(item => item === val); } JSX <Route path="/start"> <p className="secondary"> בחר מסלול רלוונטי (ניתן לבחור יותר מאחד) </p> <Row className="margTop"> <Col lg="4"><img id="firstSelectors" className="build" onClick={() => addPath('build')} src={Code} alt="בניית אתרים" /></Col> <Col lg="4"><img id="firstSelectors" className="promote" onClick={() => addPath('promote')} src={Promotion} alt="קידום אתרים" /></Col> <Col lg="4"><img id="firstSelectors" className="ad" onClick={() => addPath('ad')} src={Advertise} alt="שיווק דיגטלי" /></Col> </Row> <button onClick={Continue}>המשך</button> </Route> <Route path="/values"> {checkArray('ad') ? 'yes' : 'no'} </Route> How can I preserve useState hook after routing to another page? right now it's resetting (I have debugged calculator value to check that). A: For your use-case I would create a new hook that reads from localStorage on mount and persists changes to localStorage. The useLocalStorage hook from useHooks is a good fit here
doc_23535705
CMake Error at /usr/local/share/cmake-2.8/Modules/FindBoost.cmake:429 (message): When requesting a specific version of Boost, you must provide at least the major and minor version numbers, e.g., 1.34 Call Stack (most recent call first): demos/CMakeLists.txt:149 (find_package) A: Hope its not too late to post this. Passing it in the command line along with cmake command would resovle it cmake -DCMAKE_CXX_COMPILER=g++ -DCMAKE_INSTALL_PREFIX=dist -DBOOST_DIR="boost installation location" A: It seems you misunderstood the meaning of Boost_DIR. Boost_DIR is an environment variable used as a hint by CMake to find the boost installation directory. If this is set to Boost_DIR-NOTFOUND that does not mean that it did not find Boost. Boost_FOUND is used to indicate whether the search was successful: find_package(Boost REQUIRED thread) if(Boost_FOUND) message(STATUS "Success!") endif() In case of a successful search, CMake will also print a diagnostic message during the configure phase which looks something like Boost version: 1.53.0 Found the following Boost libraries: thread
doc_23535706
function make_test(name, job, ID) { test = {}; test.name = name; test.job = job; test.ID = ID; return test; } new make_test("Paul", "manager", 1); //doesn't work new make_test("John", "employee", 2); //doesn't work new make_test("Jan", "employee", 2); //works It should only be a match if the value is equal to the name and if the index of the textarea is equal to the person's ID. For instance if I type "Paul" in textarea1, it should output paul's job : but it should not output it in textarea2 which should only output the job of persons having an ID = 2. Problem : my code only works for the last person declared (Jan in this example). It's like the other persons don't even exist in the object, except for the last one. How can I fix this ? I'm sure the answer is pretty obvious but I can't figure out what I'm doing wrong. Demo here : https://jsfiddle.net/Lau1989/hxcpstty/ Thanks for your help A: You need to declare test to be a local variable so all invocations of your function are not referring to the exact same global variable. When you don't declare your variable it becomes an implicit global variable which can lead to all sorts of problems. If you run your code in strict mode, the interpreter will flag this as an error for you too (which is generally helpful). You also need to assign the return result from your function to a variable so you can reference the newly created object using that variable. function make_test(name, job, ID) { var test = {}; // ^^^ test.name = name; test.job = job; test.ID = ID; return test; } var o1 = make_test("Paul", "manager", 1); var o2 = make_test("John", "employee", 2); var o3 = make_test("Jan", "employee", 2); console.log(o1.name); // "Paul" console.log(o3.job); // "employee" You also don't need new in front of your function since you aren't using a system created object - you are just creating your own object and returning it. It will still work with new, but it is wasteful since you aren't using the object that the system will create with new. If you want it to be an actual constructor function where you use new and could inherit the prototype, then do this: function Make_test(name, job, ID) { this.name = name; this.job = job; this.ID = ID; } var o1 = new Make_test("Paul", "manager", 1); var o2 = new Make_test("John", "employee", 2); var o3 = new Make_test("Jan", "employee", 2); Note, I used a capitalized constructor name here since it is a common convention to use initial cap names for constructor functions and initial lowercase names for regular functions. You could also just remove the declaration entirely: function make_test(name, job, ID) { return {name: name, job: job, ID: ID}; } Or using ES6 syntax: function make_test(name, job, ID) { return {name, job, ID}; }
doc_23535707
console.log(foo); } const foo = 3; run(); How come this variable inside of a function can read a global variable that is even declared and assigned under the function statement? How does JavaScript work in this scenario? I'd like to understand how it works. fn(); function fn() { console.log("hello"); } I know this does work because of function hoisting. But the first code is another story, right? A: JavaScript is interpreted. The function is evaluated only when you call it. If you move the function call to before the variable declaration it will not work. See the code below (it gives a error) function fn() { console.log(foo); } fn(); const foo = 3; The function fn() is only a declaration till the point it is called.
doc_23535708
Map<String, Object> resultMap = new HashMap<>(); reasons.stream().forEach(reason -> { if(reason.isNotChargable()) { resultMap.put("reason1", reason); } else { resultMap.put("reason2", reason); } }); Where reasons is a list object. A: A better alternative to ternary inside the for-each would be to simply create a Map from the Stream but also use ternary to determine key. I assume the object is Reason as it's not been included in question. Props to @Naman for allowing this to handle conflicts when collecting multiple keys that are equal. This will assume the existing value instead of throwing an IllegalStateException. Map<String, Reason> results = reasons.stream() .collect(Collectors.toMap(r -> r.isNotChargable() ? "reason1" : "reason2", Function.identity(), (existing, next) -> existing); A: Replace this with a loop. No reason at all to use forEach. for (ReasonType reason : reasons) { resultMap.put(reason.isNotChargeable() ? "reason1" : "reason2", reason); } (However, you can put this resultMap.put into a forEach; it's just unnecessary). A: You can try this : String key = reason.isNotChargable() ? "reason1" : "reason2"; resultMap.put(key , reason);
doc_23535709
I have written a function that automatically gets the thumbnail of the youtube video that i embed in my code. i saved this to a variable $img. My question now is how can i set $img to be my post thumbnail. Thank you! A: Easy process should be save the thumbnail as an custom field, for say "image". Then call this custom field in theme where you need like <img src="<?php echo get_post_meta($post->ID, "image", true); ?>" alt="" /> You could also attach that image with post. A: Another alternative is to display your image in your post before any other image. Display it either in your editor, or inside your single.php loop. then use http://wordpress.org/extend/plugins/auto-post-thumbnail/. You can even hide it using CSS or img tag attributes.
doc_23535710
The Java was in MVC and I had to do a website with it. One mechanism of Java was quite pleasant. When you called the entity class corresponding to a table, if that table didn't exist, it was created with the fields corresponding to the variables of that class, avoiding errors and making it faster to implement. I was wondering, out of curiosity, if something similar existed with Zend Framework, and if no, if it was possible to do so in a loosely typed language such as php.
doc_23535711
Length 10kN 0 0.0 5 1 0.5 5 2 1.0 5 3 1.5 5 4 2.0 5 5 2.5 5 6 3.0 5 7 3.5 5 8 4.0 5 9 4.5 5 10 5.0 5 11 5.0 -5 12 5.5 -5 13 6.0 -5 14 6.5 -5 15 7.0 -5 16 7.5 -5 17 8.0 -5 18 8.5 -5 19 9.0 -5 20 9.5 -5 21 10.0 -5 b: Length1 20kN 0 0.0 50 1 0.5 45 2 1.0 40 3 1.5 35 4 2.0 30 5 2.5 25 6 3.0 20 7 3.5 15 8 4.0 10 9 4.5 5 10 5.0 0 11 5.5 -5 12 6.0 -10 13 6.5 -15 14 7.0 -20 15 7.5 -25 16 8.0 -30 17 8.5 -35 18 9.0 -40 19 9.5 -45 20 10.0 -50 c as a result of my code below: Length 10kN Length1 20kN Total 0 0.0 5 0.0 50.0 55.0 1 0.5 5 0.5 45.0 50.0 2 1.0 5 1.0 40.0 45.0 3 1.5 5 1.5 35.0 40.0 4 2.0 5 2.0 30.0 35.0 5 2.5 5 2.5 25.0 30.0 6 3.0 5 3.0 20.0 25.0 7 3.5 5 3.5 15.0 20.0 8 4.0 5 4.0 10.0 15.0 9 4.5 5 4.5 5.0 10.0 10 5.0 5 5.0 0.0 5.0 11 5.0 -5 5.5 -5.0 -10.0 12 5.5 -5 6.0 -10.0 -15.0 13 6.0 -5 6.5 -15.0 -20.0 14 6.5 -5 7.0 -20.0 -25.0 15 7.0 -5 7.5 -25.0 -30.0 16 7.5 -5 8.0 -30.0 -35.0 17 8.0 -5 8.5 -35.0 -40.0 18 8.5 -5 9.0 -40.0 -45.0 19 9.0 -5 9.5 -45.0 -50.0 20 9.5 -5 10.0 -50.0 -55.0 21 10.0 -5 NaN NaN NaN Code I tried: import pandas as pd a=pd.read_csv("first.csv") b=pd.read_csv("second.csv") c=pd.concat([a,b], axis=1) c['Total']=c['10kN']+c['20kN'] print(c['Total']) print(a) print(b) print(c) I want add two column 10kN and 20kN for same length
doc_23535712
On this side here: reflektive.com you'll see in the slider, under the text "Talent Development", how the text changes and sort of scrolls in. Thanks for any tips! A: Use this library. Same library used on the site which you mentioned in your question. <script src="jquery.js"></script> // jquery library <script src="typed.js"></script> // typed.js library <script> $(function(){ $(".element").typed({ strings: ["First sentence.", "Second sentence."], typeSpeed: 0 }); }); </script> <span class="element"></span> A: I found a link... Is this is the animation you are expecting? http://codepen.io/rusjames/pen/uAFhE @keyframes type{ from { width: 0; } } @keyframes type2{ 0%{width: 0;} 50%{width: 0;} 100%{ width: 100; } } p{ width: 30em; animation: type 4s steps(60, end); }
doc_23535713
So far everything works, but the autocomplete has a built-in keyboard function. I will need to remove all keyboard functionalities. By default, pressing the Up/Down-arrow keys, the previous/next list-item will be focused and the input field gets the value of the focused list-item. For example: Entering "searchterm" could give the list: Suggestion-item 1 Suggestion-item 2 Suggestion-item 3 Suggestion-item 4 Pressing the down-key will replace "searchterm" with "Suggestion-item-1", etc. Pressing Enter would select the currently focused item and close the menu. Can someone help me on how to remove all these keyboard-functionalities (see on jQuery Autocomple -> Keyboard Interactions)? Basically I only want to take the user to an own search-results page with the initially entered "searchterm", if Enter is pressed. Which would be the default behaviour of the search-input. Here's my js: (function( $ ) { $(function() { // Modify Autocomplete structure $.widget( "ui.autocomplete", $.ui.autocomplete, { // How to render items _renderItem: function( ul, item ) { return $( "<li>" ) //.append( "<div style='display: inline-block; width: 100px;'>" + item.number + "</div><div style='display: inline-block; width: 600px;'>" + item.label + "</div>" ) .append( "<article class='project' role='article'>" + "<header class='project-header'>" + "<h2 class='project-number col1'>" + "[&thinsp;#&thinsp;" + item.number + "&thinsp;]" + "</h2>" + "<a href='" + item.link + "' rel='bookmark'>" + "<h2 class='project-title col2'>" + "[&thinsp;#&thinsp;" + item.label + "&thinsp;]" + "</h2>" + "</a>" + "</header>" + "</article>") .appendTo( ul ); }, // How to render list _renderMenu: function( ul, items ) { var that = this; var currentTag = ""; $.each( items, function( index, item ) { var li; if(item.tag != currentTag) { ul.append( "<li class='acsearch-tag'>" + "<h2 class='col2'>" + item.tag + "</h2>" + "</li>"); currentTag = item.tag; } li = that._renderItemData( ul, item ); if(item.tag) { li; } }); } }); var url = MyAutocomplete.url + "?action=my_search"; // Bind autocomplete to any future instances $(document).on('focus', '#s:not(ui-autocomplete-input)', function(event) { // Autocomplete function $(this).autocomplete({ appendTo: '#acsearchlist', position: { my:'left top', at:'left top', of:'#acsearchlist' }, source: url, delay: 100, minLength: 3, response: function( event, ui ) { console.log(ui); }, open: function( event, ui ) { $('#list').hide(); $('.ui-autocomplete').css('width', '100%'); }, close: function( event, ui ) { $('#list').show(); }, focus: function( event, ui ) { event.preventDefault(); }, messages : { noResults : "", results : "" // function(count) { // return count + (count > 1 ? ' recordings' : ' recording ') + ' found for '; // } }, // Page transition on "selected" item select: function (event, ui) { history.pushState({}, '', ui.item.link); console.log(ui.item.link); acAjaxLoad(ui.item.link); } }); }); }); })( jQuery ); Thanks! A: For what it's worth 3 years later. This is to stop the input from getting a new value: $('#input').autocomplete({ focus: function( event, ui ) { // Stop the autocomplete of resetting the value to the selected one event.preventDefault(); } });
doc_23535714
head(sample_frame) average datetime count 1 14.60 2011-05-30T20:38:37.000Z 1 2 13.79 2013-07-25T22:54:12.000Z 1 3 17.60 2009-09-16T18:34:46.000Z 1 4 22.53 2008-08-03T18:42:35.000Z 1 5 19.30 2009-02-08T21:12:22.000Z 1 6 18.95 2009-02-04T20:00:55.000Z 1 The datetime column is as of now factor and I want to convert it to a date/time class. The issue is I wouldn't know in advance the column name so I would have to match the pattern of date time and try to convert it. Following is the code that I have written: for(i in colnames(sample_frame)) { if(regexpr("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3}Z",sample_frame[1,i]) == 1) { sample_frame$i <- strptime(as.character(sample_frame$i),"%Y-%m-%dT%H:%M:%OSZ") } } which doesn't work, the regexpr works but inside the code, it doesn't, the following command works though, sample_frame$datetime <- strptime(as.character(sample_frame$datetime),"%Y-%m-%dT%H:%M:%OSZ") A: To correct your for loop: sample_frame <- read.table(header = TRUE, text=" average datetime count 1 14.60 2011-05-30T20:38:37.000Z 1 2 13.79 2013-07-25T22:54:12.000Z 1 3 17.60 2009-09-16T18:34:46.000Z 1 4 22.53 2008-08-03T18:42:35.000Z 1 5 19.30 2009-02-08T21:12:22.000Z 1 6 18.95 2009-02-04T20:00:55.000Z 1") for(i in colnames(sample_frame)) { if(grepl("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3}Z",sample_frame[1, i])) { sample_frame[, i] <- as.POSIXct(as.character(sample_frame[, i]),"%Y-%m-%dT%H:%M:%S", tz = "") } } sample_frame$datetime # [1] "2011-05-30 20:38:37 CEST" "2013-07-25 22:54:12 CEST" "2009-09-16 18:34:46 CEST" # [4] "2008-08-03 18:42:35 CEST" "2009-02-08 21:12:22 CET" "2009-02-04 20:00:55 CET" A: Building on @LukeA's answer, you could also use lapply instead of the for loop: sample_frame[] <- lapply(sample_frame, function(x){ if(grepl("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3}Z", x[1])) { x <- as.POSIXct(as.character(x),"%Y-%m-%dT%H:%M:%S", tz = "") return(x) } else x }) sample_frame # average datetime count #1 14.60 2011-05-30 20:38:37 1 #2 13.79 2013-07-25 22:54:12 1 #3 17.60 2009-09-16 18:34:46 1 #4 22.53 2008-08-03 18:42:35 1 #5 19.30 2009-02-08 21:12:22 1 #6 18.95 2009-02-04 20:00:55 1
doc_23535715
Code to execute query: public void onJobStart(int fileType) { ContentValues cv = new ContentValues(); cv.put(Contract.Entry.UPLOAD_STATUS, STATUS_READY); String whereClause = String.format( Locale.US, "%s = %d AND %s = %d", Contract.Entry.FILE_TYPE, fileType, Contract.Entry.UPLOAD_STATUS, STATUS_CREATED ); int success = mDatabase.update( Contract.Entry.TABLE_NAME, cv, whereClause, null ); Log.e(TAG, "success=" + success); } Creation of table and it's columns: public class DbHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "cache.db"; private DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String table = "CREATE TABLE " + Contract.Entry.TABLE_NAME + " ( " + Contract.Entry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + Contract.Entry.UPLOAD_STATUS + " INTEGER, " + Contract.Entry.FILE_TYPE + " INTEGER " + ");" db.execSQL(table); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + Contract.Entry.TABLE_NAME); onCreate(db); } } public final class Contract { public Contract() {} public static abstract class Entry implements BaseColumns { public static final String TABLE_NAME = "files"; public static final String UPLOAD_STATUS = "uploadStatus"; public static final String FILE_TYPE = "fileType"; } } This code doesn't work and I'm keep gettingsuccess=0 after executing the query. It's kind of weird because till yesterday the where clause was with only one argument and it worked i.e: String whereClause = String.format( Locale.US, "%s = %d", Contract.Entry.UPLOAD_STATUS, STATUS_CREATED ); Edit: Also tried this: String whereClause = Contract.Entry.FILE_TYPE + " = ? AND " + Contract.Entry.UPLOAD_STATUS + " = ?"; String[] whereArgs = new String[] {String.valueOf(fileType), String.valueOf(STATUS_CREATED)}; int success = mDatabase.update( Contract.Entry.TABLE_NAME, cv, whereClause, whereArgs ); Basically I would like to update all rows that their status is created. For couple of hour didn't find a solution here in SO. and google. Any ideas? Thanks A: I recon it is in this part: "%s = %d AND %s = %d" try this: (they all need to be String to work tho) "%1$s = %2$s AND %3$s = %4$s"
doc_23535716
<![CDATA[ my-field-value ]]> it was being turned into &lt;![CDATA[ my-field-value ]]&gt; Which breaks functionality of using CDATA in the first place. I used a custom character handler according to some comments from How to prevent JAXB escaping a string. Everything is working for me now but i have heard that im not supposed to use com.sun.xml.internal.* packages and currently I am doing so like this (notice the use of internal): import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; JAXBContext jc = JAXBContext.newInstance(MyClass.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setProperty( "com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler", new MyCustomCharacterHandler()); return marshaller; Where MyCustomCharacterHandler is declared like so (note the use of internal): import com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler; public class XmlCdataCharacterHandler implements CharacterEscapeHandler { ... } This combination is working fine for me but when modifying my code to get rid of .internal.* like so using this dependency: <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.2.7</version> </dependency> import com.sun.xml.bind.marshaller.CharacterEscapeHandler; public class XmlCdataCharacterHandler implements CharacterEscapeHandler { ... } JAXBContext jc = JAXBContext.newInstance(PrintPack.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setProperty( "com.sun.xml.bind.marshaller.CharacterEscapeHandler", new MyCustomCharacterHandler()); return marshaller; My server will no longer start and is getting a JAXBException with the following message: name: com.sun.xml.bind.marshaller.CharacterEscapeHandler value: com.fmrco.research.search.handlers.MyCustomCharacterHandler@1f3d4305 Which makes me think that my custom handler which implements the CharacterEscapeHandler is no longer being used correctly. Does anyone know how to fix this so i can keep this implementation while avoiding com.sun.xml.internal.* packages? Is there a better/newer way to turn a java class into an XML string? Seems like I should not be stuck on this for as long as I have been. Thank you!
doc_23535717
* *A list (eg for todos, just for trying out ST2) where I can tap to edit or set it as done etc. I am not sure I am doing it right, but I am thinking I have a panel containing a list on the left and details view on the right. Looking at the docs for Conatiner: //this is the Panel we'll be adding below var aboutPanel = Ext.create('Ext.Panel', { html: 'About this app' }); //this is the Panel we'll be adding to var mainPanel = Ext.create('Ext.Panel', { fullscreen: true, layout: 'hbox', defaults: { flex: 1 }, items: { html: 'First Panel', style: 'background-color: #5E99CC;' } }); //now we add the first panel inside the second mainPanel.add(aboutPanel); I figured I might be able to use the config property for configure my Panel: Ext.define("SimpleTodo.view.Main", { extend: 'Ext.Panel', config: { items: [ { xtype: 'panel', config: { html: 'Panel 1 ...' } }, { xtype: 'panel', config: { html: 'Panel 2 ...' } } ] } }); Fails: A blank screen. If I add html property into config I get HTML shown but what I am I doing wrong with the items? You might have also noticed, I am having a list of left and details on right. This is good for tablets, but how can I make it for phones? Do I need to use Profiles and separate views for them? A: but what I am I doing wrong with the items? You don't have a config property for panel component. So, remove the config property for each individual panel and directly use html property to set html inside each panel Like this, { xtype: 'panel', html: 'Panel 1 ...' }, { xtype: 'panel', html: 'Panel 2 ...' }
doc_23535718
https://recoiljs.org/docs/api-reference/core/RecoilRoot <RecoilRoot> accept props as initializeState?: (MutableSnapshot => void) signature. That able to initialize Recoil State so I want to use this props but I don't understand how to make MutableSnapshot object. import {RecoilRoot} from 'recoil'; function AppRoot() { return ( <RecoilRoot initializeState={/* How to setup arguments here? */} > <ComponentThatUsesRecoil /> </RecoilRoot> ); } On the other hand Snapshot is easier to get from useRecoilSnapshot() though. A: I figure out answer of the question myself. MutableSnapshot is passed by Recoil library code automatically so user don't have to create MutableSnapshot object yourself. Bellow code is typically usage of initializeState. Pick argument you need (set, get etc) form MutableSnapshot with object destructuring then write your state initialization code. render( <RecoilRoot initializeState={({ set }: MutableSnapshot): void => set(recoilState, initialRecoilStateValue) } > {ui} </RecoilRoot> )
doc_23535719
### List Webhooks [GET /webhooks] + Request + Headers Authorization: Bearer <API_KEY> + Response 200 (application/json) + Attributes (array[Webhook]) doesn't look like an array when it's rendered in Apiary. See below. Did something change? A: Have you tried the new Apiary Documentation renderer? Many issues with rendering Data Structures have been fixed on it. I just tried your example and it renders as expected. https://help.apiary.io/tools/interactive-documentation-v4/
doc_23535720
<input type="text" [(ngModel)]="name" (ngModelChange)="onNameChange()"> <div *ngFor="let s of filteredScreenshots"> {{s | json}} </div> <mat-card class="example-card" *ngFor="let filteredScreen of filteredScreens" let i = index> <mat-card-header> <div mat-card-avatar class="example-header-image" > <img mat-card-image class="list-img" src="{{filteredScreen?.img}}" > </div> <mat-card-content class="names"><b>{{ filteredScreen?.name }}</b></mat-card-content> </mat-card-header> </mat-card> This is(customer.component.ts) import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; import { map } from 'rxjs/operators' import * as _ from 'lodash'; @Component({ selector: 'ylb-customer', templateUrl: './customer.component.html', styleUrls: ['./customer.component.css'] }) export class CustomerComponent { spaceScreens: Array<any>; filteredScreens = []; name: string; constructor(private http:Http){ this.http.get('assets/app.json').pipe( map(response => response.json().screenshots) ) .subscribe(res => { this.spaceScreens = this.sortByName(res); //this is what we filter against this.filteredScreens = this.sortByName(res);//init with full list }); } onNameChange() { this.filteredScreens=_.filter(this.spaceScreens,(item)=>{ console.log(this.name) return item.name.toLowerCase().indexOf(this.name.toLowerCase())>-1; }); } sortByName = function(users) { const byName = function(user1,user2) { return user1.name.localeCompare(user2.name); }; return users.slice().sort(byName); }; } This is the (app.json)json file present inside assets folder { "screenshots":[ { "img":"assets/img/json_2.jpg", "name":"Virat Kohli" }, { "img":"assets/img/json_2.jpg", "name":"Joe Root" } ] } filtering is happening fine and it is displaying the json data(name) in alphabetical order.I want to highlight the text entering in the field like in mobile contact list as like in attached image. enter image description here Tried many resources but no result A: In Chrome and also in other Browsers (see here) you can use a component like this: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'highlight' }) export class HighlightSearch implements PipeTransform { transform(value: string, args: string): any { if (args && value) { value = String(value); // make sure its a string const startIndex = value.toLowerCase().indexOf(args.toLowerCase()); if (startIndex !== -1) { const matchingString = value.substr(startIndex, args.length); return value.replace(matchingString, "<mark>" + matchingString + "</mark>"); } } return value; } } To use like this: <mat-card-content class="names"><b [innerHTML]="filteredScreen.name | highlight: name"></b></mat-card-content> A: Joniras's answer is great... but I found this problem to be all too common with little available with customizability and accessibility (like selecting, double clicking, proper focusing/blurring, etc.) I published a quick component that helps with that. Hope it can help someone else too! https://www.npmjs.com/package/ng-input-highlighter
doc_23535721
menu.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/degrees" android:title="Celsius / Fahrenheit" app:showAsAction="never"/> </menu> MainActivity.java @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case R.menu.menu: // How do change between Celsius and Fahrenheit break; } return true; } } Dropbox link for a deeper view if needed Weather Test app A: From the OpenWeather Documentation. Units format Description: Standard, metric, and imperial units are available. Parameters: units metric, imperial. When you do not use units parameter, format is Standard by default. Temperature is available in Fahrenheit, Celsius and Kelvin units. For temperature in Fahrenheit use units=imperial For temperature in Celsius use units=metric Temperature in Kelvin is used by default, no need to use units parameter in API call List of all API parameters with units openweathermap.org/weather-data Examples of API calls: standard api.openweathermap.org/data/2.5/find?q=London metric api.openweathermap.org/data/2.5/find?q=London&units=metric imperial api.openweathermap.org/data/2.5/find?q=London&units=imperial
doc_23535722
NB! I'm sorry I could not figure out how to add more than 1 space between numbers and headers in my example so i used "_" instead. The problem: I have two data frames (Graduations and Occupations). I want to match the occupations to the graduations. The difficult part is that one person might be present multiple times in both data frames and I want to keep all the data. Example: Graduations One person may have finished many curriculums. Original DF has more columns but they are not relevant for the example. Person_ID__curriculum_ID__School ID ___1___________100__________10 ___2___________100__________10 ___2___________200__________10 ___3___________300__________12 ___4___________100__________10 ___4___________200__________12 Occupations Not all graduates have jobs, everyone in the DF should have only one main job (JOB_Type code "1") and can have 0-5 extra jobs (JOB_Type code "0"). Original DF has more columns but the are not relevant currently. Person_ID___JOB_ID_____JOB_Type ___1_________1223________1 ___3_________3334________1 ___3_________2120________0 ___3_________7843________0 ___4_________4522________0 ___4_________1240________1 End result: New DF named "Result" containing the information of all graduations from the first DF(Graduations) and added columns from the second DF (Occupations). Note that person "2" is not in the Occupations DF. Their data remains but added columns remain empty. Note that person "3" has multiple jobs and thus extra duplicate rows are added. Note that in case of person "4" has both multiple jobs and graduations so extra rows were added to fit in all the data. New DF: "Result" Person_ID__Curriculum_ID__School_ID___JOB_ID____JOB_Type ___1___________100__________10_________1223________1 ___2___________100__________10 ___2___________200__________10 ___3___________300__________12_________3334________1 ___3___________300__________12_________2122________0 ___3___________300__________12_________7843________0 ___4___________100__________10_________4522________0 ___4___________100__________10_________1240________1 ___4___________200__________12_________4522________0 ___4___________200__________12_________1240________1 For me the most difficult part is how to make R add extra duplicate rows. I looked around to find an example or tutorial about something similar but could. Probably I did not use the right key words. I will be very grateful if you could give me examples of how to code it. A: You can use merge like: merge(Graduations, Occupations, all.x=TRUE) # Person_ID curriculum_ID School_ID JOB_ID JOB_Type #1 1 100 10 1223 1 #2 2 100 10 NA NA #3 2 200 10 NA NA #4 3 300 12 3334 1 #5 3 300 12 2122 0 #6 3 300 12 7843 0 #7 4 100 10 4522 0 #8 4 100 10 1240 1 #9 4 200 12 4522 0 #10 4 200 12 1240 1 Data: Graduations <- read.table(header=TRUE, text="Person_ID curriculum_ID School_ID 1 100 10 2 100 10 2 200 10 3 300 12 4 100 10 4 200 12") Occupations <- read.table(header=TRUE, text="Person_ID JOB_ID JOB_Type 1 1223 1 3 3334 1 3 2122 0 3 7843 0 4 4522 0 4 1240 1") A: An option with left_join library(dplyr) left_join(Graduations, Occupations)
doc_23535723
<%= f.select :tag_list, Artist.tag_counts_on(:tag), {}, {:multiple => true, :class => "tags-select", selected: :tag_list } %> A: Something like below should do <% Artist.tag_counts_on(:tag).each do |some_value| %> <%= f.check_box(:tag_list, { :multiple => true }, some_value, nil) %> <% end %>
doc_23535724
@property (nonatomic) BOOL done; than I am using it with self.done . Problem is that sometimes I get error when using it like that. for example(error) : //implicit conversion of bool to id disallowed in-ARC [encoder encodeObject:self.done forKey:@"text"]; With this situation I have two questions: 1. When and why should I create a property with BOOL, and what is the logic behind this? 2. Why I am getting this error ? A: Question 2 You are getting that error because BOOL is a primitive type and the encoder expects an Object. You can easily solve that wrapping your bool with a literal, like this [encoder encodeObject:@(self.done) forKey:@"text"] This basically convertes to: [encoder encodeObject:[NSNumber numberWithBool:self.done] forKey:@"text"] Question 1 You can create a property with BOOL because it is more direct that a NSNumber initiated with a BOOL. For instance, if you wanted to do ifs on that bool with a NSNumber you would need to do number.boolValue all the time. The advantage of declaring a property vs declaring an iVar is that it gives you a KVO ready structure and you have an entry point to get the value and an entry point to set the value. In the case of the BOOL this is mainly useful for debugging. Although KVO is also a plus :) (If you need more info on properties vs iVars follow my answer on SO) A: As you see encodeObject: in [encoder encodeObject:self.done forKey:@"text"]; but done is not an Objective-C object. Rather it is an BOOL. BOOL is typedef signed char BOOL; You cant box the BOOL type to Obj-C object as NSNumber and encode it. [encoder encodeObject:@(self.done) forKey:@"text"];
doc_23535725
#include <iostream> #include <dlfcn.h> int main(int argc, char** argv) { typedef void* (*fptr)(); fptr func; void *handle = dlopen(0, RTLD_NOW); std::cout << dlerror() << std::endl; *(void **)(&func) = dlsym(handle, "__libc_start_main"); std::cout << dlerror() << std::endl; std::cout << handle << " " << func << "\n"; dlclose(handle); return 0; } and try to compile in next way: g++ -rdynamic main.cpp -ldl -o test When I run this program I don’t see any message. Why? Thank U for attention. A: Your process is faulting because dlerror() is only valid to call in an error condition, which you never validated actually happened prior to invocation. From the Linux docs: The function dlerror() returns a human readable string describing the most recent error that occurred from dlopen(), dlsym() or dlclose() since the last call to dlerror(). It returns NULL if no errors have occurred since initialization or since it was last called. In other words, your dlopen succeeded, so NULL is returned from dlerror(). That NULL is then sent as a char * to std::cout, and kerboom. Bottom line: check your error conditions before invoking dlerror(). Try this instead: #include <iostream> #include <dlfcn.h> int main(int argc, char** argv) { typedef void* (*fptr)(); fptr func; void *handle = dlopen(0, RTLD_NOW); if (handle == nullptr) { std::cout << dlerror() << std::endl; exit(EXIT_FAILURE); } func = (fptr)dlsym(handle, "__libc_start_main"); if (!func) { std::cout << dlerror() << std::endl; exit(EXIT_FAILURE); } std::cout << handle << " " << func << "\n"; dlclose(handle); return 0; } A: This is (likely) undefined behavior: std::cout << dlerror() << std::endl; ...unless dlerror is actually non-null (which it probably isn't). It should be: char* error = dlerror(); if (error != 0) std::cout << error << std::endl; ...or: void *handle = dlopen(0, RTLD_NOW); if (handle == 0) std::cout << dlerror() << std::endl; Also, you probably should abort if dlerror is non-null (or handle is null), because calling dlsym on an null handle is also undefined behavior. See Why does std::cout output disappear completely after NULL is sent to it.
doc_23535726
For table A, it will be lots of duplicates for both C2 and C3; but for condition C4 as 10, there will be no duplicates which is what I want to update. For example, table A has records as: 1,100,1500,10,'ORG' 1,200,2000,10,'ORG' 1,300,2500,10,'ORG' 2,1000,500,20,'PERSON' 2,1000,200,20,'PERSON' 2,2000,200,20,'PERSON' You can see that for C4 as 10, there is no duplicate for C2 and C3. But for C4 as 20, there will be duplicates for C2 and C3. For table B, it will be like 100,1500,80 200,2000,100 300,3000,200 There is no duplicates for table B, and will join B with A as A.C2 = B.D1 and A.C3 = B.D2 to update A.C2 to B.D3. I only have to update C4=10 records to join with table B based on B.D1 and B.D2. I have SQL as below, but failed as ORA-01779: cannot modify a column which maps to a non key-preserved table Can anyone tell me what is wrong with my SQL? UPDATE ( SELECT A.C2 OID, B.D3 TID FROM A, B WHERE A.C2 = B.D1 AND A.C3 = B.D2 AND A.C4=10 AND B.D3 <> ' ' ) SET OID = TID Thanks a lot! A: Can't you use an update statement like... UPDATE A set c2 = (select D3 from B where B.D2 <> ' ' and A.C2 = b.D1 and A.C3=B.D2) ) where A.C4=10 Also, your question and the problem description itself looks like a puzzle thtis very hard to understand. Can you post some data and create table statements so that it's easy to reproduce your case ?(from next time maybe....) A: UPDATE A SET C2 = ( SELECT B.D3 FROM B WHERE A.C2 = B.D1 AND A.C3 = B.D2) WHERE A.C4=10 AND EXISTS ( SELECT * FROM B2 WHERE A.C2 = B2.D1 AND A.C3 = B2.D2) No need to alias for update statements. Also you have the condition on B.D2 <> ' ' and also A.C3 = B.D2, so it is just as easy to just filter on A.C3 <> ' ', since A is the target table. If A.C3 is never blank, then the condition is not even required. A: First, it sounds like you are trying to update TableA. Second, the official ANSI specification for the Update statement does not provide for a join directly in the statement (you can have joins only through subqueries). One reason is that it would create ambiguities when duplicate rows were involved. So, you might try something like: Update A Set OID = ( Select B.D3 From B Where B.D1 = A.C2 And B.D2 = A.C3 And B.D3 Is Not Null ) Where A.C4 = 10 And Exists ( Select 1 From B Where B.D1 = A.C2 And B.D2 = A.C3 And B.D3 Is Not Null )
doc_23535727
Here is the JQuery: $("span.boxes ul li.one").click(function(){ $("span.panel1").slideToggle(); $("span.panel2").hide('slow'); $("span.panel3").hide('slow'); $("span.panel4").hide('slow'); $("span.panel5").hide('slow'); $("span.panel6").hide('slow'); return false; }); $("span.boxes ul li.two").click(function(){ $("span.panel2").slideToggle(); $("span.panel3").hide('slow'); $("span.panel4").hide('slow'); $("span.panel5").hide('slow'); $("span.panel6").hide('slow'); $("span.panel1").hide('slow'); return false; }); $("span.boxes ul li.three").click(function(){ $("span.panel3").slideToggle(); $("span.panel4").hide('slow'); $("span.panel5").hide('slow'); $("span.panel6").hide('slow'); $("span.panel1").hide('slow'); $("span.panel2").hide('slow'); return false; }); $("span.boxes ul li.four").click(function(){ $("span.panel4").slideToggle(); $("span.panel5").hide('slow'); $("span.panel6").hide('slow'); $("span.panel1").hide('slow'); $("span.panel2").hide('slow'); $("span.panel3").hide('slow'); return false; }); $("span.boxes ul li.five").click(function(){ $("span.panel5").slideToggle(); $("span.panel6").hide('slow'); $("span.panel1").hide('slow'); $("span.panel2").hide('slow'); $("span.panel3").hide('slow'); $("span.panel4").hide('slow'); return false; }); $("span.boxes ul li.six").click(function(){ $("span.panel6").slideToggle(); $("span.panel1").hide('slow'); $("span.panel2").hide('slow'); $("span.panel3").hide('slow'); $("span.panel4").hide('slow'); $("span.panel5").hide('slow'); return false; }); And here is the html: <span class="boxes"> <ul> <li class="one">Title 1</li> <li class="two">Title 2</li> <li class="three">Title 3</li> <li class="four">Title 4</li> <li class="five">Title 5</li> <li class="six">Title 6</li> </ul> </span> <!-- boxes --> <div id="panel-holder"> <span class="panel1"> <p>Title 1</p> </span> <span class="panel1"> <p>Title 2</p> </span> <span class="panel1"> <p>Title 3</p> </span> <span class="panel1"> <p>Title 4</p> </span> <span class="panel1"> <p>Title 5</p> </span> <span class="panel1"> <p>Title 6</p> </span> </div> <!-- #panel-holder --> Thanks for your help ;o) A: Using index() method you can match index of eleemnt clicked to index of element you want to show. It would be much cleaner if you gave all the panels a common class instead of numbering the class var $panels=$('[class^="panel"]'); $('.boxes li').click(function(){ var index=$(this).index(); $panels.not(':eq('+index+')').hide('slow'); $panels.eq(index).slideToggle(); }) A: You should write an own function which contains the logic centrally and add a common class name to each panel (e.g. <span class="panel1 panels">): function togglePanels(showPanel) { $('span.panels:visible').hide(); // hides panels which are visible showPanel.slideToggle(); // shows the particular panel you're providing in the parameter } An example call would look like than this and you save many code lines, even the logic you might have to change once: $("span.boxes ul li.four").click(function(){ togglePanels($("span.panel4")); }); A: changed your HTML. block elements can't be in inline elements, that is, <p>'s and <ul>'s can't be in <span>'s HTML <ul id="links"> <li class="link-1">Title 1</li> <li class="link-2">Title 2</li> <li class="link-3">Title 3</li> <li class="link-4">Title 4</li> <li class="link-5">Title 5</li> <li class="link-6">Title 6</li> </ul> <div id="panels"> <div class="panel-1"> <p>Title 1</p> </div> <div class="panel-2"> <p>Title 2</p> </div> <div class="panel-3"> <p>Title 3</p> </div> <div class="panel-4"> <p>Title 4</p> </div> <div class="panel-5"> <p>Title 5</p> </div> <div class="panel-6"> <p>Title 6</p> </div> </div>​ JS as for the JS, we bind only one handler - to the parent using .on(). then we assign a number to each link which we will extract during click. we then find the matching panel and toggle it, while hiding all others that are not a match. $(function() { $('#links').on('click','li',function() { var itemNumber = this.className.split('-')[1]; $('#panels > div.panel-'+itemNumber).slideToggle(); $('#panels > div:not(.panel-'+itemNumber+')').hide('slow'); return false; }); });​ CSS #links li{ display:inline-block; padding: 10px; background:#ccc; margin-bottom:50px; } #panels > div{ padding: 10px; background:red; margin-bottom:50px; display:none; } ​ A: Use the index() method: http://jsfiddle.net/C2PfW/ $("span.boxes ul li").on("click", function(){ var $this = $(this); // each li var panels = $("#panel-holder span"); panels.hide(); panels.eq($this.index()).slideDown(200); return false; });
doc_23535728
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE event_id = '1243'' at line 1 in INSERT INTO expiredEvents (event_id,sport_type,tournament,round,team1,team2,venue,event_date) values ('1243','Rugby','Super15','3','Waratahs','Sharks','Allianz Stadium','') WHERE event_id = '1243' $sql="INSERT INTO expiredEvents (event_id,sport_type,tournament,round,team1,team2,venue,event_date) values ('$id','$sport','$trnmnt','$rnd','$t1','$t2','$ven','$eDate') WHERE event_id = '$id'" A: There is no WHERE clause in the correct syntax of the INSERT statement. Depending on what you want to achieve, choose one of the following. Insert a new row, don't bother if another one having the same event_id already exists INSERT INTO expiredEvents (event_id, sport_type, tournament, round, team1, team2, venue, event_date) VALUES ('$id', '$sport', '$trnmnt', '$rnd', '$t1', '$t2', '$ven', '$eDate') If event_id is an UNIQUE INDEX of table expiredEvents, this query fails if another record having event_id = '$id' already exists. Assuming event_id is the PK of the table, keep reading. Insert a new row but only if it does not already exists INSERT IGNORE INTO expiredEvents (event_id, sport_type, tournament, round, team1, team2, venue, event_date) VALUES ('$id', '$sport', '$trnmnt', '$rnd', '$t1', '$t2', '$ven', '$eDate') The IGNORE keyword turns the errors into warnings and the query completes successfully but it does not insert the row if another one having event_id = '$id' already exists. Inserts a row if it does not exist or update the existing one, if it exists INSERT INTO expiredEvents (event_id, sport_type, tournament, round, team1, team2, venue, event_date) VALUES ('$id', '$sport', '$trnmnt', '$rnd', '$t1', '$t2', '$ven', '$eDate') ON DUPLICATE KEY UPDATE sport_type=VALUES(sport_type), round=round+1, event_date=NOW() If the row does not exist, this query insert it using the values from the VALUES clause. If the row already exists then it uses the ON DUPLICATE KEY UPDATE to know how to update it. There are three fields modified in this query: * *sport_type=VALUES(sport_type) - the value of column sport_type is updated using the value provided in the query for column sport_type (VALUES(sport_type), which is '$sport'); *round=VALUES(round)+1 - the value of column round is updated using its current value plus 1 (round+1); the value provided in the VALUES clause is not used; *event_date=NOW() - the value of column event_date is modified using the value returned by the function NOW(); both the old value and the one provided in the VALUES clause of the query are ignored. This is just an example, you put there whatever expressions you need to update the existing row. Completely replace the existing row with a new one REPLACE INTO expiredEvents (event_id, sport_type, tournament, round, team1, team2, venue, event_date) VALUES ('$id', '$sport', '$trnmnt', '$rnd', '$t1', '$t2', '$ven', '$eDate') The REPLACE statement is a MySQL extension to the SQL standard. It first DELETEs the row having event_id = '$id' (if any) then INSERTs a new row. It is functionally equivalent with DELETE FROM expiredEvents WHERE event_id = '$id' followed by the first query exposed above in this answer. A: WHERE keyword is not allowed in INSERT INTO / VALUES http://dev.mysql.com/doc/refman/5.6/en/insert.html Elaborate what you would like to accomplish. A: Don't use where in insert statment, instead of just get the data from the respective tables which contains the exact records and insert necessary rows alone by adding your conditions in the select statement of that query. Here is the simple one to resolve your error, $sql="INSERT INTO expiredEvents (event_id,sport_type,tournament,round,team1,team2,venue,event_date) SELECT event_id,sport_type,tournament,round,team1,team2,venue,event_date from events WHERE event_id = '$id'"
doc_23535729
Assume we have a subject string "apple:banana:cherry:durian". We want to match the subject and have $1, $2, $3 and $4 become "apple", "banana", "cherry" and "durian", respectively. The pattern I'm using is ^(\w+)(?::(.*?))*$, and $1 will be "apple" as expected. However, $2 will be "durian" instead of "banana". Because the subject string to match doesn't need to be 4 items, for example, it could be "one:two:three", and $1 and $2 will be "one" and "three" respectively. Again, the middle item is missing. What is the correct pattern to use in this case? By the way, I'm going to use PCRE2 in C++ codes, so there is no split, a Perl built-in function. Thanks. A: If the input contains strictly items of interest separated by :, like item1:item2:item3, as the attempt in the question indicates, then you can use the regex pattern [^:]+ which matches consecutive characters which are not :, so a substring up to the first :. That may need to capture as well, ([^:]+), depending on the overall approach. How to use this to get all such matches depends on the language.† In C++ there are different ways to approach this. Using std::regex_iterator #include <string> #include <vector> #include <iterator> #include <regex> #include <iostream> int main() { std::string str{R"(one:two:three)"}; std::regex r{R"([^:]+)"}; std::vector<std::string> result{}; auto it = std::sregex_iterator(str.begin(), str.end(), r); auto end = std::sregex_iterator(); for(; it != end; ++it) { auto match = *it; result.push_back(match[0].str()); } std::cout << "Input string: " << str << '\n'; for(auto i : result) std::cout << i << '\n'; } Prints as expected. One can also use std::regex_search, even as it returns at first match -- by iterating over the string to move the search start after every match #include <string> #include <regex> #include <iostream> int main() { std::string str{"one:two:three"}; std::regex r{"[^:]+"}; std::smatch res; std::string::const_iterator search_beg( str.cbegin() ); while ( regex_search( search_beg, str.cend(), res, r ) ) { std::cout << res[0] << '\n'; search_beg = res.suffix().first; } std::cout << '\n'; } (With this string and regex we don't need the raw string literal so I've removed them here.) † This question was initially tagged with perl (with no c++), also with an explicit mention of it in text (still there), and the original version of this answer referred to Perl with /([^:]+)/g The /g "modifier" is for "global," to find all matches. The // are pattern delimiters. When this expression is bound (=~) to a variable with a target string then the whole expression returns a list of matches when used in a context in which a list is expected, which can thus be directly assigned to an array variable. my @captures = $string =~ /[^:]+/g; (when this is used literally as shown then the capturing () aren't needed) Assigning to an array provides this "list context." If the matching is used in a "scalar context," in which a single value is expected, like in the condition for an if test or being assigned to a scalar variable, then a single true/false is returned (usually 1 or '', empty string). A: Repeating a capture group will only capture the value of the last iteration. Instead, you might make use of the \G anchor to get consecutive matches. If the whole string can only contain word characters separated by colons: (?:^(?=\w+(?::\w+)+$)|\G(?!^):)\K\w+ The pattern matches: * *(?: Non capture group * *^ Assert start of string *(?=\w+(?::\w+)+$) Assert from the current position 1+ word characters and 1+ repetitions of : and 1+ word characters till the end of the string *| Or *\G(?!^): Assert the position at the end of the previous match, not at the start and match : *) Close non capture group *\K\w+ Forget what is matched so far, and match 1+ word characters Regex demo To allow only words as well from the start of the string, and allow other chars after the word chars: \G:?\K\w+ Regex demo
doc_23535730
The path for the index.php file goes like this: mysite/index.php The path for the include files goes like this: mysite/pages/include/header.php Here is the HTML file with the include files: <html> <head> <?php include ("pages/include/headertop.php"); include ("pages/include/header.php"); include ("pages/include/nav.php"); ?> </head> </html> Kindly correct me if I have missed something here. By the way, I'm using XAMPP. Thank you and More power! A: edit your index.php: include ("../pages/include/headertop.php"); include ("../pages/include/header.php"); include ("../pages/include/nav.php"); and try again "mysite/index.php" A: Firstly make sure that you are calling these include commands in a .php file and not .html file. Secondly make sure that your server is up and running well. After this try this code: <html> <head> <?php include "pages/include/headertop.php"; include "pages/include/header.php"; include "pages/include/nav.php"; ?> </head> </html> P.S: just remove the brackets from include. Please also make sure that the file names are correct and they follow the proper case.
doc_23535731
function bgchange(edit) { var bgurl; switch(edit) { case edit="categories": bgurl = 'url(img/categories_bg.jpg)'; break; case edit="ishot": bgurl = 'url(img/appslist_bg.jpg)'; break; default: bgurl =''; } return bgurl; }; bg = bgchange(edit, id); $('#wrapper').css("background", "black "+ bg + "no-repeat right"); Now, whenever you click a page, a bg should change, that works when I run it from the desktop, however when I run it from my iPhone, it's not working, is it because iPhone has a problem doing so, and if so - can I use a different command to change the bg? Help is appreciated, Thanks A: Well, the problem seemed to be that safari wasn't running the code for some reason, once I moved it away from the <head> everything worked just fine... weird.
doc_23535732
sample json: [ { "id" : 1, -- this is not a primary key and not unique but cannot be null "name" : "John Doe", "phone" : [ { "type" : "home", "ref" : "111-111-1234"}, { "type" : "work", "ref" : "222-222-2222"} ] }, { "id" : 2, -- this is not a primary key and not unique but cannot be null "name" : "Jane Doe", "phone" : [ { "type" : "home", "ref" : "111-111-1234"}, { "type" : "work", "ref" : "222-222-2222"} ] } ] This is what i need after saving in the database id name phone 1 John Doe { "type" : "home", "ref" : "111-111-1234"} 1 John Doe { "type" : "work", "ref" : "222-222-2222"} 2 Jane Doe { "type" : "home", "ref" : "111-111-1234"} 2 Jane Doe { "type" : "work", "ref" : "222-222-2222"} This is what I am getting id name phone 1 John Doe [{ "type" : "home", "ref" : "111-111-1234"},{ "type" : "work", "ref" : "222-222-2222"}] 2 Jane Doe [{ "type" : "home", "ref" : "111-111-1234"},{ "type" : "work", "ref" : "222-222-2222"}] here is how i am parsing the json object to pojo and saving to db @Entity @Table(name="person") public class person{ private Integer id; private String name; private String phone; @Transient JsonNode phoneJson; private static OhjectMapper mapper = new ObjectMapper(); getter/setter @Transient public JsonNode getPhoneJson(){ return phoneJson; } public void setPhoneJson(JsonNode phoneJson){ this.phoneJson = phoneJson; } @JsonIgnore @Column(name="phone") public String getPhone() throws Exception{ return mapper.writeValueAsString(phoneJson); } public void setPhone(String phone) throws Exception{ this.phone = mapper.readTree(phone); } } dao- save personRepository.save(person) any help would be appreciated. UPDATE Multiple jSON Column [ { "id" : 1, -- this primary key and not unique but cannot be null "name" : { --this element can be empty/null "first" : "John", "last" : "Doe" }, "phone" : [ { "type" : "home", "ref" : 1111111234}, { "type" : "work", "ref" : 2222222222} ] }, { "id" : 2, -- this primary key and not unique but cannot be null "name" : { "first" : "Jane", "last" : "Doe" }, "phone" : [ { "type" : "home", "ref" : 1111111234}, { "type" : "work", "ref" : 2222222222} ] } ] how do i get result as below id name phone 1 [{John},{Doe}] { "type" : "home", "ref" : "111-111-1234"} 1 [{John},{Doe}] { "type" : "work", "ref" : "222-222-2222"} 2 [{Jane},{Doe}] { "type" : "home", "ref" : "111-111-1234"} 2 [{Jane},{Doe}] { "type" : "work", "ref" : "222-222-2222"} A: You need to duplicate Person objects n times where n is size of phone array. To make it clear, I propose, to create two separate models which we can use separately for parsing JSON and saving in DB. Below you can find simple example which: * *Parses JSON to List<JsonPerson> *Converts List<JsonPerson> to List<Person> *Prints List<Person> (you can save it to DB) Example: import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.type.CollectionType; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class JsonApp { public static void main(String[] args) throws Exception { File jsonFile = new File("./resource/test.json").getAbsoluteFile(); ObjectMapper mapper = new ObjectMapper(); CollectionType personsType = mapper.getTypeFactory().constructCollectionType(List.class, JsonPerson.class); // parse List<JsonPerson> jsonPersons = mapper.readValue(jsonFile, personsType); // convert List<Person> persons = jsonPersons.stream() .map(p -> p.mapTo(mapper)) .flatMap(List::stream) .collect(Collectors.toList()); persons.forEach(System.out::println); // save persons to DB // ... } } class JsonPerson { private Integer id; private String name; private ArrayNode phone; public List<Person> mapTo(ObjectMapper mapper) { List<Person> persons = new ArrayList<>(); phone.elements().forEachRemaining(phone -> { persons.add(map(mapper, phone)); }); return persons; } private Person map(ObjectMapper mapper, JsonNode p) { Person person = new Person(); person.setId(id); person.setName(name); try { person.setPhone(mapper.writeValueAsString(p)); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return person; } // getters, setters, toString } class Person { private Integer id; private String name; private String phone; // getters, setters, toString } Above code prints: Person{id=1, name='John Doe', phone='{"type":"home","ref":"111-111-1234"}'} Person{id=1, name='John Doe', phone='{"type":"work","ref":"222-222-2222"}'} Person{id=2, name='Jane Doe', phone='{"type":"home","ref":"111-111-1234"}'} Person{id=2, name='Jane Doe', phone='{"type":"work","ref":"222-222-2222"}'} Above code separates parsing JSON from other parts. Also, do not create ObjectMapper in each POJO. POJO should not know anything about ObjectMapper and Jackson. Update Because name is JSON Object you can create new POJO - Name with first and last properties or treat it similarly to phone and deserialise to JsonNode: class JsonPerson { private Integer id; private JsonNode name; private ArrayNode phone; public List<Person> mapTo(ObjectMapper mapper) { List<Person> persons = new ArrayList<>(); phone.elements().forEachRemaining(phone -> { persons.add(map(mapper, phone)); }); return persons; } private Person map(ObjectMapper mapper, JsonNode p) { Person person = new Person(); person.setId(id); person.setName(getNameAsString()); try { person.setPhone(mapper.writeValueAsString(p)); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return person; } private String getNameAsString() { if (name == null) { return null; } StringBuilder builder = new StringBuilder(); if (name.isObject()) { ObjectNode nameObject = (ObjectNode) name; builder.append("["); builder.append("{").append(nameObject.get("first")).append("}"); builder.append(","); builder.append("{").append(nameObject.get("last")).append("}"); builder.append("]"); } return builder.toString(); } // getters, setters, toString } After change above code should print: Person{id=1, name='[{"John"},{"Doe"}]', phone='{"type":"home","ref":1111111234}'} Person{id=1, name='[{"John"},{"Doe"}]', phone='{"type":"work","ref":2222222222}'} Person{id=2, name='[{"Jane"},{"Doe"}]', phone='{"type":"home","ref":1111111234}'} Person{id=2, name='[{"Jane"},{"Doe"}]', phone='{"type":"work","ref":2222222222}'} getNameAsString method is simplified, you need to handle all corner cases and create String representation better for null, empty and semi-empty nodes.
doc_23535733
I've found that the project type can't be a website. But it still doesn't work for appsettings at all, for connection strings, it uses the Debug build version, even when on Release mode. My project is a default Visual Studio Single Page Web Application with authentication removed. The following secrets files: **Web.settings.secrets:** <?xml version="1.0" encoding="utf-8"?> <connectionStrings xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <add name="Default" providerName="Oracle.ManagedDataAccess.Client" connectionString="Release connectionString" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/> </connectionStrings> **Web.settings.Release.secrets:** <?xml version="1.0" encoding="utf-8" ?> <appSettings xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <add name="setting" value="Release setting" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/> </appSettings> **Web.connection.secrets:** <?xml version="1.0" encoding="utf-8"?> <connectionStrings> <add name="Default" providerName="Oracle.ManagedDataAccess.Client" connectionString="Debug connectionString" /> <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApp-20170304072749.mdf;Initial Catalog=aspnet-WebApp-20170304072749;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> **Web.connection.Release.secrets:** <?xml version="1.0" encoding="utf-8"?> <connectionStrings xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <add name="Default" providerName="Oracle.ManagedDataAccess.Client" connectionString="Release connectionString" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/> </connectionStrings> The Web.config and Web.Release.config refer to these files in their connectionStrings and appSettings elements. Web.config: <?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=301879 --> <configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <connectionStrings configSource="Web.connection.secrets"> </connectionStrings> <appSettings file="Web.settings.secrets"> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> <system.web> <authentication mode="None" /> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web> <system.webServer> <modules> <remove name="FormsAuthentication" /> </modules> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <remove name="TRACEVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers></system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" /> <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" /> </dependentAssembly> </assemblyBinding> </runtime> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="mssqllocaldb" /> </parameters> </defaultConnectionFactory> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> </configuration> Web.Release.config: <!-- For more information on using Web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=301874 --> <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <!-- In the example below, the "SetAttributes" transform will change the value of "connectionString" to use "ReleaseSQLServer" only when the "Match" locator finds an attribute "name" that has a value of "MyDB". --> <connectionStrings configSource="Web.connection.Release.secrets"> </connectionStrings> <appSettings file="Web.settings.Release.secrets"> </appSettings> <system.web> <compilation xdt:Transform="RemoveAttributes(debug)" /> <!-- In the example below, the "Replace" transform will replace the entire <customErrors> section of your Web.config file. Note that because there is only one customErrors section under the <system.web> node, there is no need to use the "xdt:Locator" attribute. <customErrors defaultRedirect="GenericError.htm" mode="RemoteOnly" xdt:Transform="Replace"> <error statusCode="500" redirect="InternalError.htm"/> </customErrors> --> </system.web> </configuration> I would really like to: * *Include connection strings from the right secrets file, based on the used build configuration. *Include app settings from the Web.setting.secrets file at default. *Include app settings from right secrets file, based on the used build configuration. A: Your first block - what you are referring to as the separate settings files shouldn't have XML declarations, nor transforms. Examples: * *Secrets.config file <add name="setting" value="Release setting" /> <add name="foo" value="bar" /> Your last block, which you are referring to as your release config should have transforms: <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> ... <connectionStrings configSource="Web.connection.Release.secrets.config" xdt:Transform="Replace"> </connectionStrings> <!-- AppSettings file location sample - leaves child elements intact--> <appSettings file="releasekeys.config" xdt:Transform="SetAttributes(file)"></appSettings> REF: Web.config Transformation Syntax for Web Application Project Deployment Hth ~
doc_23535734
Here's a sample input table: let T = datatable(Timestamp:datetime, Count:int) [ datetime(2021-01-01), 1, datetime(2021-01-02), 1, datetime(2021-01-03), 2, datetime(2021-01-04), 1, datetime(2021-01-05), 1, datetime(2021-01-06), 3, datetime(2021-01-07), 1, datetime(2021-01-08), 2, ]; The desired output is: Timestamp Count MaxToDate 2021-01-01 1 1 2021-01-02 1 1 2021-01-03 2 2 2021-01-04 1 2 2021-01-05 1 2 2021-01-06 3 3 2021-01-07 1 3 2021-01-08 2 3 Thanks! A: you can use the scan operator: https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/scan-operator for example: datatable(Timestamp:datetime, Count:int) [ datetime(2021-01-01), 1, datetime(2021-01-02), 1, datetime(2021-01-03), 2, datetime(2021-01-04), 1, datetime(2021-01-05), 1, datetime(2021-01-06), 3, datetime(2021-01-07), 1, datetime(2021-01-08), 2, ] | order by Timestamp asc | scan declare (max_to_date:int = 0) with ( step s1: true => max_to_date = case(Count > s1.max_to_date, Count, s1.max_to_date); ) Timestamp Count max_to_date 2021-01-01 00:00:00.0000000 1 1 2021-01-02 00:00:00.0000000 1 1 2021-01-03 00:00:00.0000000 2 2 2021-01-04 00:00:00.0000000 1 2 2021-01-05 00:00:00.0000000 1 2 2021-01-06 00:00:00.0000000 3 3 2021-01-07 00:00:00.0000000 1 3 2021-01-08 00:00:00.0000000 2 3
doc_23535735
Non compilant example public Car createRedCar() { Car car = new Car(); car.setColor(Color.RED); car = makeCool(car); // <- error, car variable was reassigned // do other irrelevant stuff with car, eg log, dispatch event or whatever return car; } Compilant example public Car createRedCar() { Car car = new Car(); car.setColor(Color.RED); Car coolCar = makeCool(car); // <- it's ok, because all local variables are effectively final // do other irrelevant stuff with car, eg log, dispatch event or whatever return coolCar; } Another compilant example public Car createRedCar() { final Car car = new Car(); car.setColor(Color.RED); final Car coolCar = makeCool(car); // <- it's also ok, but i don't want to force every variable to be final // do other irrelevant stuff with car, eg log, dispatch event or whatever return coolCar; } I don't want to force every variable to have final keyword, just for them to be effectively final OR final. If no default rule for this is present i'm okay with using custom rules and / or plugins, or finally even write one, but someone probably already did this and this is why i'm posting here. I am using sonarqube-7.4, and i am willing to update if it comes with the rule i want. A: If anyone is interested, i've developed a rule that does what i was asking for in the question. For now, it was tested only on sonarqube-8.3.1. link to the repo.
doc_23535736
So my question is that: * *Are shader information now separated from .gltf? I know there is KHR_technique_webgl extensions which consist of the technique and shader properties(exactly like how gltf1.0 represent shader), are we suppose to be use that if our material arent pbr? *How do rendering engines now grab shader information from normal .gltf now(without the extensions)? Do we do it like old school way ie loading our own shader and manually map the model attributes to shaders attribute? A: The KHR_technique_webgl extension will eventually be finished, and will provide a way to include custom shaders with your glTF2.0 model. But as of this writing, the extension is not fully defined and tools cannot implement it. The more general case (and recommended if it suits your needs) would be to use PBR or Blinn-Phong materials. These are declared abstractly in glTF, so that rendering engines can build their own shaders for these material types, and will generally integrate better with engines' own lighting and/or shadows.
doc_23535737
A: I'd rather say that you aren't granted to use it. Ask your DBA (or, if you have those privileges, do it yourself) to grant execute on dbms_xslprocessor to your_user; [EDIT] The package exists in my 11g: SQL> select object_name, object_type 2 from dba_objects where object_name = 'DBMS_XSLPROCESSOR'; OBJECT_NAME OBJECT_TYPE ------------------------------ ------------------- DBMS_XSLPROCESSOR SYNONYM DBMS_XSLPROCESSOR PACKAGE DBMS_XSLPROCESSOR PACKAGE BODY SQL> select * from v$version; BANNER -------------------------------------------------------------------------------- Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production PL/SQL Release 11.2.0.4.0 - Production CORE 11.2.0.4.0 Production TNS for Linux: Version 11.2.0.4.0 - Production NLSRTL Version 11.2.0.4.0 - Production SQL> What does your query return?
doc_23535738
The following is my script: select *, DATEDIFF (yy, Begin_date, GETDATE()) AS 'Age in Years' from Report_Stage; The 'Age_In_Years' column is being rounded. How do I get the exact date in years? A: I think that division by 365.2425 is not a good way to do this. No division can to this completely accurately (using 365.25 also has issues). I know the following script calculates an accurate date difference (though might not be the most speedy way): declare @d1 datetime ,@d2 datetime --set your dates eg: select @d1 = '1901-03-02' select @d2 = '2016-03-01' select DATEDIFF(yy, @d1, @d2) - CASE WHEN MONTH(@d2) < MONTH(@d1) THEN 1 WHEN MONTH(@d2) > MONTH(@d1) THEN 0 WHEN DAY(@d2) < DAY(@d1) THEN 1 ELSE 0 END -- = 114 years For comparison: select datediff(day,@d1 ,@d2) / 365.2425 -- = 115 years => wrong! You might be able to calculate small ranges with division, but why take a chance?? The following script can help to test yeardiff functions (just swap cast(datediff(day,@d1,@d2) / 365.2425 as int) to whatever the function is): declare @d1 datetime set @d1 = '1900-01-01' while(@d1 < '2016-01-01') begin declare @d2 datetime set @d2 = '2016-04-01' while(@d2 >= '1900-01-01') begin if (@d1 <= @d2 and dateadd(YEAR, cast(datediff(day,@d1,@d2) / 365.2425 as int) , @d1) > @d2) begin select 'not a year!!', @d1, @d2, cast(datediff(day,@d1,@d2) / 365.2425 as int) end set @d2 = dateadd(day,-1,@d2) end set @d1 = dateadd(day,1,@d1) end A: All datediff() does is compute the number of period boundaries crossed between two dates. For instance datediff(yy,'31 Dec 2013','1 Jan 2014') returns 1. You'll get a more accurate result if you compute the difference between the two dates in days and divide by the mean length of a calendar year in days over a 400 year span (365.2425): datediff(day,{start-date},{end-date},) / 365.2425 For instance, select datediff(day,'1 Jan 2000' ,'18 April 2014') / 365.2425 return 14.29461248 — just round it to the desired precision. A: You want the years difference, but reduced by 1 when the "day of the year" of the future date is less than that of the past date. So like this: SELECT * ,DATEDIFF(YEAR, [Begin_date], [End_Date]) + CASE WHEN CAST(DATENAME(DAYOFYEAR, [End_Date]) AS INT) >= CAST(DATENAME(DAYOFYEAR, [Begin_date]) AS INT) THEN 0 ELSE -1 END AS 'Age in Years' from [myTable]; A: Have you tried getting the difference in months instead and then calculating the years that way? For example 30 months / 12 would be 2.5 years. Edit: This SQL query contains several approaches to calculate the date difference: SELECT CONVERT(date, GetDate() - 912) AS calcDate ,DATEDIFF(DAY, GetDate() - 912, GetDate()) diffDays ,DATEDIFF(DAY, GetDate() - 912, GetDate()) / 365.0 diffDaysCalc ,DATEDIFF(MONTH, GetDate() - 912, GetDate()) diffMonths ,DATEDIFF(MONTH, GetDate() - 912, GetDate()) / 12.0 diffMonthsCalc ,DATEDIFF(YEAR, GetDate() - 912, GetDate()) diffYears A: For me I calculate the difference in days Declare @startDate datetime Declare @endDate datetime Declare @diff int select @diff=datediff(day,@startDate,@endDate) if (@diff>=365) then select '1Year' if (@diff>=730) then select '2Years' -----etc A: I have found a better solution. This makes the assumption that the first date is less than or equal to the second date. declare @dateTable table (date1 datetime, date2 datetime) insert into @dateTable select '2017-12-31', '2018-01-02' union select '2017-01-03', '2018-01-02' union select '2017-01-02', '2018-01-02' union select '2017-01-01', '2018-01-02' union select '2016-12-01', '2018-01-02' union select '2016-01-03', '2018-01-02' union select '2016-01-02', '2018-01-02' union select '2016-01-01', '2018-01-02' select date1, date2, case when ((DATEPART(year, date1) < DATEPART(year, date2)) and ((DATEPART(month, date1) <= DATEPART(month, date2)) and (DATEPART(day, date1) <= DATEPART(day, date2)) )) then DATEDIFF(year, date1, date2) when (DATEPART(year, date1) < DATEPART(year, date2)) then DATEDIFF(year, date1, date2) - 1 when (DATEPART(year, date1) = DATEPART(year, date2)) then 0 end [YearsOfService] from @dateTable date1 date2 YearsOfService ----------------------- ----------------------- -------------- 2016-01-01 00:00:00.000 2018-01-02 00:00:00.000 2 2016-01-02 00:00:00.000 2018-01-02 00:00:00.000 2 2016-01-03 00:00:00.000 2018-01-02 00:00:00.000 1 2016-12-01 00:00:00.000 2018-01-02 00:00:00.000 1 2017-01-01 00:00:00.000 2018-01-02 00:00:00.000 1 2017-01-02 00:00:00.000 2018-01-02 00:00:00.000 1 2017-01-03 00:00:00.000 2018-01-02 00:00:00.000 0 2017-12-31 00:00:00.000 2018-01-02 00:00:00.000 0
doc_23535739
For that, I have used MTCNN (https://github.com/timesler/facenet-pytorch) for face detection and official pytorch implementation of arcface algorithm (https://github.com/deepinsight/insightface/tree/master/recognition/arcface_torch) for CNN implementation. I have used a pretrained model (ms1mv3_arcface_r50_fp16) trained on resnet 50 and a backbone CNN model from their repository for implementing the CNN. The CNN takes a 112x112 image and produces an array of 512x1. So I get two arrays as a result of the network. I have tried to compare the two array using cosine similarity but It is not giving me the correct results all the time. So, do I need to change my model parameters or do I need to use another metric for comparison? My code: https://gist.github.com/desertSniper87/26f5f45f4cece9d0f3008e89cea94be8 A: I've tried and got fully enjoied Elasticsearch with standard dlib face vectors (128x1)... ES can store and search&compare such kind vectors super fast and accurate. I've used somthing like this to creat a ES index: from elasticsearch import Elasticsearch es = Elasticsearch([{'host': ELASTIC_HOST, 'port': ELASTIC_PORT }], timeout=30, retry_on_time=True, max_retries=3, http_auth=(ELASTIC_NAME, ELASTIC_PSW) ) mapping = { "mappings": { "properties": { "face_vector":{ "type": "dense_vector", "dims": 128 }, "pic_file": { "type": "text"}, "face_loc": { "type": "integer"} } } } es.indices.create(index="fr_idx", body=mapping) and then s_body = {"size": ELASTIC_MAX_RESULTS, "min_score": tolerance, "query": { "script_score": { "query": { "match_all": {} }, "script": { "source": "1 / (1 + l2norm(params.query_vector, 'face_vector'))", "params": {"query_vector": UNKNOWN_FACE_ENCOD} } } } } res = es.search(index="fr_idx", body=s_body) #standard index for hit in res["hits"]["hits"]: ... to search similar vectors.
doc_23535740
<com.projector.interaction.layout.MapMouseView2 xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mouse" android:layout_width="fill_parent" android:layout_height="fill_parent"> </com.projector.interaction.layout.MapMouseView2> I then try and referene the View by public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { setContentView(R.layout.testlayout); MapMouseView2 view = (MapMouseView2)findViewById(R.id.mouse); view.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.d("Debug","Touch Not Working"); return true; } }); } catch (Exception e) { Log.e("Error","Error in TestActivity",e); } } But it gives me a null pointer exception. Then only fix I can find is to wrap my view in the xml file inside a LinearLayout and reference the view by public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { setContentView(R.layout.testlayout); LinearLayout lay = (LinearLayout)findViewById(R.id.lin); MapMouseView2 mouseView = (MapMouseView2)lay.getChildAt(0); mouseView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.d("Debug","Touch Not Working"); return true; } }); } catch (Exception e) { Log.e("Error","Error in TestActivity",e); } } Can anybody please tell me what I am doing wrong??? The View class is here public class MapMouseView2 extends View{ WindowManager mWinMgr; Rect zoom; Rect panLeftRight; Rect panUpDown; public MapMouseView2(Context context,AttributeSet attrs){ super(context); Log.d("Debug","Context,AttribyteSet"); try { mWinMgr = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); zoom = new Rect(0, 0, 45, mWinMgr.getDefaultDisplay().getHeight()); panLeftRight = new Rect(0, 458, mWinMgr.getDefaultDisplay().getWidth(), mWinMgr.getDefaultDisplay().getHeight()); panUpDown = new Rect(mWinMgr.getDefaultDisplay().getWidth() - 45, 0, mWinMgr.getDefaultDisplay().getWidth(), mWinMgr .getDefaultDisplay().getHeight()); Log.d("Debug","Leaving Constructor"); } catch (Exception e) { Log.e("Error","Error in MapMouseView",e); } } protected void onDraw(Canvas canvas) { super.onDraw(canvas); try { Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); // make the entire canvas white paint.setColor(Color.BLACK); canvas.drawPaint(paint); paint.setColor(Color.BLUE); canvas.drawRect(zoom, paint); paint.setColor(Color.RED); canvas.drawRect(panLeftRight, paint); paint.setColor(Color.RED); canvas.drawRect(panUpDown, paint); //canvas.drawCircle(x,y,30,threadPaint); } catch (Exception e) { Log.e("Error","Exception in OnDraw",e); } } } A: I think you should call super(context, attrs); in constructor of MapMouseView2. edit: If you don't do that your view doesn't get id. In the second approach you refer to the view by position not name, so it works.
doc_23535741
My data object items[ { "currentBUName":"Financial Services" } { "currentBUName":"State Owned Entities" } { "currentBUName":"State Owned Entities" } ] My ts code extract <ion-item> <ion-label>Please select current business unit</ion-label> <ion-select [(ngModel)]="selectedValue"> <ion-option *ngFor="let indexx of this.items;"[value]="indexx">{{indexx.currentBUName}}</ion-option> </ion-select> </ion-item> A: When you set the value of items use a filter function to only get the unique values. This can be done like so: this.items = this.items.filter((v, i, arr) => arr.indexOf(v) === i); NOTE: If this data is coming from a server then it would make more sense to do this filtering server-side to reduce the amount of duplicate information that is coming across the wire. A: Why not use an array filter ? items = [ { "currentBUName":"Financial Services" } { "currentBUName":"State Owned Entities" } { "currentBUName":"State Owned Entities" } ] uniqueItems = items.filter(function(item, pos) { return items.indexOf(item) == pos; }) then use uniqueItems instead A: Other answers are good but one way you might do this would be to define it in terms of some more general utility functions function groupBy<T>(values: T[], keySelector: (value: T) => string): {[key: string]: T[]} { return values .map(value => ({ key: keySelector(value), value })) .reduce((groups, { key, value }) => ({ ...groups, [key]: groups[key] && groups[key].concat(value) || [value] }), {}); } function distinctBy<T>(values: T[], keySelector: (value: T) => string): T[] { const groups = groupBy(values, keySelector); return Object.values(groups).map(([representative]) => representative); } Then you could write this.items = distinctBy(incomingItems, item => item.currentBUName);
doc_23535742
Left Div (Client One) Right Div (Client Two) Left Div (Client Three) Right Div (Client Four) I am passing a simple model to my view from the controller. No matter how I try, it seems that the only way to access the "entities"/rows in the model is via a foreach and iterating over them sequentially. I really need to get "entities" by their index value, by turning the model data from an IEnumerable into an array and getting entity[ n ]. Is this possible or do I not understand the relationship between the View and the model data. Here's my controller: public ActionResult ClientView() { return View("ClientView", db.Clients.ToList()); My model is a simple list of typical client properties with no navigation: FirstName, LastName, Address, etc. In the view, I'm trying to get client 1 in a left side div, and client 2 in a right side div, then a new row and start over. Thanks much in advance Allen A: Suppose your view is strongly typed to List: @Model List<MySoftware.Models.Client> Then you can access the clients by index: Model[0] Model[1] Model[2] This is possible because the IList interface allows you to retrieve items by index, just like an array. A List is generally the preferred method as arrays are... well... a bit old fashioned. However, a better design might be to simply work this into your UI code instead, since this is really a UI display issue. Something like: @Model IEnumerable<MySoftware.Models.Client> var i = 0; foreach (var client in Model) { <div> [client details] </div> i++; if (i % 2 == 1) <br/> }
doc_23535743
I want to provide a button called "Manage subscription". This should jump to the App Store under the subscription management for my specific app. What URL should I redirect to achieve this? A: From the Apple documentation: Rather than needing to code your own subscription management UI, your app can open the following URL: https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/manageSubscriptions Opening this URL launches iTunes or iTunes Store, and then displays the Manage Subscription page. A: This is the new URL that should be used: https://apps.apple.com/account/subscriptions A: Based on account subscriptions URL provided by @i4guar, the below code is how I am navigating to the Account Subscriptions page using Swift 4.2. This is working for me on iOS 14.5. if let url = URL(string: "https://apps.apple.com/account/subscriptions") { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:]) } } A: If someone want to put the "Manage Subscriptions" button inner a long description text, as an option, we can just use UITextView's delegate to handle the NSURL interaction, it'll redirect user to App Store's subscription management view directly once user tap the "Manage Subscriptions" text. Below is a sample code: static NSString *const kURLOfManageSubscriptions = @"https://apps.apple.com/account/subscriptions"; - (void)setupSubviews { UITextView *aTextView = [[UITextView alloc] init]; aTextView.delegate = self; aTextView.editable = NO; aTextView.scrollEnabled = NO; // ... NSString *text = @"... long text contains ... Manage Subscriptions"; UIFont *textFont = [UIFont systemFontOfSize:UIFont.systemFontSize]; NSDictionary *textAttributes = @{NSFontAttributeName : textFont, NSForegroundColorAttributeName : UIColor.labelColor }; NSDictionary *linkedTextAttributes = @{NSFontAttributeName : textFont, NSForegroundColorAttributeName : UIColor.blueColor, NSLinkAttributeName : kURLOfManageSubscriptions }; NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString:text attributes:textAttributes]; NSRange linkedTextRange = [text rangeOfString:@"Manage Subscriptions"]; [content addAttributes:linkedTextAttributes range:linkedTextRange]; aTextView.attributedText = content; } #pragma mark - UITextViewDelegate - (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction { if ([URL.absoluteString isEqualToString:kURLOfManageSubscriptions]) { // The default interaction will redirect user to App Store's subscription // management view directly. // Or you can manage it by yourself here. return YES; } else { return NO; } } A: In iOS15+ you can present the App Store sheet for managing subscriptions in your app by calling showManageSubscriptions(in:) See here.
doc_23535744
A: Google no longer counts the meta keywords tags. They stopped doing so since somewhere near 2009.Here is the official link of the announcement. http://googlewebmastercentral.blogspot.gr/2009/09/google-does-not-use-keywords-meta-tag.html You can check the article above from google support about what types of meta tags their bots are taking into consideration when they crawl your page. https://support.google.com/webmasters/answer/79812?hl=en On the other hand it is very good to have different pages for different keywords since only one of them is going to receive high ranking for a specific keyword. But you have to do that without the meta keywords tags. You can use the title tags and the description tags also.You will can get some more by adding the keyword in the images alt text too. But yet again your meta keyword tags will have no value at all. So in my honest opinion try using the the methods i mentioned above and forget about managing the keywords with JavaScript. If u have need more details feel free to ask in comments of my answer A: Google is on record saying they no longer look at this meta keywords tag. As for the meta description and title tag, place text there that you think will optimize your click through rate on the SERPs, but don't cram keywords in.
doc_23535745
road ... should return: black, flat, tar, porous, long... I've tried several unsatisfying approaches. For example, dictionaries should provide such words, but their definitions are too strict and too short. I also tried semantic networks such as ConceptNet (see this link). But to the best of my knowledge, the available resources (for my application) are scarce. I was never able to predict that a road is (usually) black. Do you have any better idea/approach? If this question is too naive, please excuse my poor knowledge of the field. Note: In my understanding, the problem is difficult because it deals with the "common sense": I get less Google results for "black road" (1.8m results) than "white road" (2.4m results) because nobody talks about the black roads (too obvious!). As a result, the training of the machine is biased.
doc_23535746
I try to fill an Html table with data from an array. It's an array of object. export interface OrderDetails { orderId? : number; truckMenuId: number; price? : number; quantity : number; truckMenu? : TruckMenu; title?: string; } The method below ask an OrderDetails array as parameter. public generatePDF(truck: Truck, orderItems: OrderDetails[]) { let rows: string[] = ['Price', 'Quantity']; orderItems.forEach((item) => { var lign = [item.price, item.quantity]; rows.push(<string><unknown>lign); }) let docDefinition = { content: [ { text: truck.name, fontSize: 20, alignment: 'center', color: '#FF4F02', margin: [0, 20], }, { text: 'Facture', fontSize: 14, bold: true, alignment: 'Left', decoration: 'underline', color: '#000', margin: [0, 20] }, { table: { widths: ['*', 70, 50], body: rows } }, { text: 'Total : ', fontSize: 14, alignment: 'right', margin: [140,20] }, { text: 'Thanks', fontSize: 12, margin: [0,20] } ], } pdfMake.createPdf(docDefinition).open(); } As you can see, I use a forEach to loop into the array and display the data. My problem is that a get an error message but I don't understand why. TypeError: Cannot assign to read only property '0' of string 'Price' I found the same error message here but this doesn't solved my problem. What's wrong? A: I finaly found the solution. I change rows type by any[] and push element like below: ... var rows: any[] = []; rows.push(['Plats', 'Prix unitaire', 'Quantité']); orderItems.forEach((item) => { rows.push([item.title, item.price, item.quantity]); }) ...
doc_23535747
.then(user => { const mailOptions = { from: "Mohammad.front.dev@gmail.com", to: user.email, subject: "Reset Password", html: ` <html> <head> <meta charset="utf-8" /> <style> body, * { direction: ltr; } </style> </head> <body> <h1>You've requested a password reset!</h1> <h3> Click this <a href="http://localhost:8000/new-password/${token}">Link</a> to set a new password. </h3> <body> </html> ` }; req.flash("info", "Checkout your email for reset password link."); res.redirect("/products"); transporter.sendMail(mailOptions, (error, info) => { if(error) console.log(error); else console.log(info); }); ... I want to send a html reversed file instead of writing all that stuff in a js file. How do i do this? A: You can just read the content from the HTML file to the variable and use this variable in mailOptions Similar questions: * *How do I send a html file using nodemailer *Pass variable to html template in nodemailer A: I recommend using ejs for this purpose. It has a simple syntax that you can implement your HTML text in a ".ejs" extension file. A: Hope this is helpful to you public static send(data) { const transport = nodemailer.createTransport({ name: process.env.SMTP_HOST, host: process.env.SMTP_HOST, port: process.env.SMTP_PORT, auth: { user: process.env.SMTP_USER_NAME, pass: process.env.SMTP_PASSWORD, }, pool: true, // use pooled connection rateLimit: true, // enable to make sure we are limiting maxConnections: 1, // set limit to 1 connection only maxMessages: 3, // send 3 emails per second }); var mailOptions = { from: process.env.FROM, html: data.html, replyTo: process.env.REPLY_TO, to: data.to, subject: data.subject, text: data.text, }; transport.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } console.log("Message sent: %s", info.messageId); return; }); }
doc_23535748
String myColorString = "rgb(26,33,37)"; int color = Integer.parseInt(myColorString, 16); int r = (color >> 16) & 0xFF; int g = (color >> 8) & 0xFF; int b = (color >> 0) & 0xFF; FooterColor.setBackgroundColor(Color.rgb(r, g, b)); A: I would suggest to use String Manipulation methods like .subString() After it use split method. Its simple to use. String colrStr="rgb(12,13,14)"; String tempStr=colrStr.substring(4,11); String rgbArray[]=tempStr.split(",");
doc_23535749
I tried deleting the item and then adding the new one on the position of the deleted item... After click it always opens a new blank activity though... How could I make this work ? Thanks in advance switch (item.getItemId()) { case R.id.rename: final AlertDialog.Builder alert = new AlertDialog.Builder(getView().getContext()); alert.setTitle("Rename"); final EditText editText = new EditText(getActivity().getApplicationContext()); editText.setTextColor(Color.BLACK); alert.setView(editText); jsonArray = new JSONArray(); jsonArrayName = new JSONArray(); try { jsonArray = new JSONArray(preferences.getString("ListNotes", jsonArray.toString())); subCategoryName = jsonArray.getString(id); jsonArrayName = new JSONArray(preferences_notes.getString("subjectNotes", jsonArrayName.toString())); subCategoryNameRename = jsonArrayName.getString(id); } catch (Exception e) { } editText.setText(subCategoryName); for(int i = 0; i < jsonArrayName.length(); i++) { try { arrayListItemName.add(jsonArrayName.get(i).toString()); } catch (JSONException e) { e.printStackTrace(); } } for (int i = 0; i < jsonArray.length(); i++) { try { arrayListRename.add(jsonArray.get(i).toString()); } catch (Exception e) { e.printStackTrace(); } } alert.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { newSubCategoryName = editText.getText().toString(); subCategoryName = newSubCategoryName; subCategoryNameRename = subCategoryName; arrayListRename.remove(id); arrayListRename.add(id, newSubCategoryName); Toast.makeText(getActivity().getApplicationContext(), "Updated text: " + subCategoryName, Toast.LENGTH_SHORT).show(); editorNotes.putString("subjectNotes", subCategoryNameRename).apply(); editor.putString("ListNotes", arrayListRename.toString()).apply(); m_adapter_notes.notifyDataSetChanged(); onResume(); } });
doc_23535750
Everything is working fine except for the ListItemSecondaryAction in the list. (i.e) When I drag a list item, the ListItemText and the ListItemIcon are draggable. The ListItemSecondaryAction just remains in the same place and gets rearranged only when that particular item is dropped. You can try out the same in the sandbox link: https://codesandbox.io/s/4qp6vjp319 Changing the position of the ListItemSecondaryAction did not solve the problem. A: Solution Move the IconButton out of the ListItemSecondaryAction fix this problem * *Change from <ListItemText primary={item.primary} secondary={item.secondary} /> <ListItemSecondaryAction> <IconButton> <EditIcon /> </IconButton> </ListItemSecondaryAction> * *To <ListItemText primary={item.primary} secondary={item.secondary} /> <ListItemIcon> <IconButton> <EditIcon /> </IconButton> </ListItemIcon> <ListItemSecondaryAction /> Screenshot
doc_23535751
Here is a Sample: http://jsbin.com/abezob/1 <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> </script> </head> <body style="background-color: #ccc;"> <div id="reload" style="display: block"> <img width="24" height="24" src="http://info.kicktipp.de/img/mobil/reload.png" alt="reload" /> </div> <div id="loading" style="display: none"> <img width="24" height="24" src="http://info.kicktipp.de/img/mobil/loading.gif" alt="loading" /> </div> <p> <a href="http://www.google.de/">Link to Google</a> </p> <script type="text/javascript"> $("a").click(function() { $("#reload").hide(); $("#loading").show(); }); </script> </body></html> I can't see the spinner on my device and I want to see it while the page is loading of course. The Sample works fine with Firefox, Chrome and Safari, but not with the native Android 4.1.2 Browser. Here is my UserAgent: Mozilla/5.0 (Linux; U; Android 4.1.2; de-de; GT-I9100 Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 Any suggestions appreciated. UPDATE: Setting a timeout like shown below will make the spinner appear. However the spinner is animating only for the set timeout. So if the connection is bad and the loading will take some amount of time, the app looks non responsive. SAMPLE: http://jsbin.com/uxopuy/1 with 3 sec timeout A: I'm not sure if it would change anything, but you could try using something like this: $("a").click(function(e) { e.preventDefault(); var $this = $(this); $("#reload").hide(); $("#loading").show(); setTimeout(function () { window.location.href = $this.attr("href"); }, 500); }); All this does is add a half second delay before actually navigating away. To me, that might help show the spinner when leaving the page. I don't know why it's not "showing" the spinner on your phone, but I wouldn't be surprised if it's because the browser is leaving the page so quickly and you're not given much time to see the spinner.
doc_23535752
Python 3 and Windows 10 I have some cpu intensive code that currently runs through all rows in a data-set and computes something for each row. It currently takes about 1 minute to do around 10k rows and I think this can can dramatically reduced with a process pool (it doesn't matter what order the results are computed in). I am relatively new to python programming and after some research, futures seems ideal. Doing something like: with futures.ProcessPoolExecutor() as executor: my_futures = [executor.submit(my_function,row) for row in my_data] ..do stuff with results The problem is that in windows it seems that I need to run this code in the main module? if __name__ == '__main__': Due to recursive calls (and yes I managed to crash my computer like others have :) ) My code is in a class called by another class so it is not under the main module. Without rewriting everything (and making the code somewhat clunky) I don't see a way to sort this. Is there a way around this or another library for concurrent processes which can be used?
doc_23535753
please tell me is it possible to make a combo box in Qt like shown in the picture. Any help would be appreciated Regards A: Easy way: comboBox->setIconSize(QSize(100, 24)); comboBox->addItem(lineIcon, ""); comboBox->addItem(dotLineIcon, ""); comboBox->addItem(dashLineIcon, ""); ... Correct way: comboBox->setItemDelegate(...);
doc_23535754
We have an Address-book and an user want to add a new contact to it. In this scenario we have 2 classes: * *User: that determine the user that logged in. *Contact: A contact object that consists of Name, Address, Phone Number, etc And the questions: * *Who have to save a new contact?User class or Contact Class *If we try to check the user's permission before doing anything where is the best place for it? *Is it OK that these classes have a access to database?(Is it better to create 3rd class for doing query stuffs?) Thanks for any good idea ;) A: Usable distribution of "responsibility" is an OOP design and architecture decision with no single simple correct answer. For discussion refer to Stack Overflow question What is the single most influential book every programmer should read? You'll learn the pros/cons by coding (using someone's design or creating your own design which does not work well). However there are some useful/frequent distributions of responsibility already known as http://en.wikipedia.org/wiki/Software_design_pattern In my opinion the only fixed fact is that each class/function/structure should have its responsibility clearly defined/documented - since the very first lines of code - and "do one thing and do it well" A: Contacts are user specific. Thus every user object (class instance) should contain its own contacts object which is a container of contact (other user) objects, comprising in turn of name, address, phone etc. class User { String name; String phone; String address; Contacts contacts; .... } class Contacts { List<User> items; } The Contacts class should have the implementation of saving a new contact, which needs to be called from a User method, something like the following. User u; Contacts c = u.getContacts(); c.addContact(name, address, phone); User's permissions should be checked in the User class. The methods of these classes should interface with the database. For this each class method can open a new connection to a database and execute SQL queries. Example method of User cass: User getContact(String name) { Connection conn = getConnection(); .... PreparedStatement ps = con.prepareStatement("select * from Contacts where name = ?"); ... return userRcd; } A: 1) Save new contact must the separate class, which working directly with database 2) Best place to check user permission - in user class of course 3) See the item 1:) I recommend you get strong knowledge about SOLID principles, it's basics for good design.
doc_23535755
He is a pro .NET so he send me .cshtml file that I never heard about it. I try the simple drag and drop inside htdocs and it's not working. Before downloading all the VM/iso to run W10 on my machine, I would like to know if I have to setup up something on MAMP to make it works ? A: If the cshtml file is work. You can running it in Visual Studio Code . reference: https://docs.asp.net/en/latest/tutorials/your-first-mac-aspnet.html download: https://www.visualstudio.com/
doc_23535756
On my browsers, I always get a warning that the page includes resources that are not secured. I just can't find out why! Looking at the source code seems fine. All img src and javascript tags are using relative path (/images/...). It does not consider href links as resources does it? Is there a way to know what actually is the source of that problem? A: I guess you could use the Net tab of Firebug to see that. (source: ibm.com) A: Try capturing all your traffic using Fiddler - it will help you identify any extraneous HTTP calls easily. A: It's unlikely to be a hyperlink, but could it be a stylesheet? They're linked using the href attribute as well: <link rel="stylesheet" href="..."> Also, how about stylesheets/Javascript that import other resources (other stylesheets, Ajax libraries, etc.)? Edit: the image at https://www.makemeheal.com/classifieds/images/1.0/dline_hmpmid1px.gif seems to be redirecting to a non-https version of its URL; the other images are under https://www.makemeheal.com/images/ which doesn't do that. Looks like a webserver config issue? A: The easiest way is usually to look through the source (with the Find utility in your editor) for http:. It is often part of some code that calls some Flash. A: I guess you include some content that links to http. Try a search in the source on http://, ftp:// or anything alike. Also take a look at forms. Forms can also post to http by accident. Is it possible to put the website online somewhere so we can take a look? Perhaps you include a style sheet that refers to some image which is without ssl, or you reference some js which in turn references some other content over http? A: Do you have any background images in your CSS that are referenced absolutely? Also, what about any iframe tags on the page with the src attribute set to an unsecure page? A: +1 for using Fiddler. One very quick check you can make is to only get the HTTPS content when prompted, and then see what is missing from your page once it is loaded. If is is a resource file, or a css file, or some javascript, or an image, then you will spot that virtually straight away.
doc_23535757
I've read the documentation for matplotlib.pyplot.colorbar() but wasn't able to figure out how to do what I wanted to do without using one of matplotlib's previously defined colormaps. My guess is that I'll need to define my own colormap that transitions from red to blue and then it will be relatively simple to feed that to matplotlib.pyplot.colorbar() and get the color bar that I want. Here is an example of the code I use to plot the lines: import numpy as np from matplotlib import pyplot as pp x= ##x-axis values for plotting ##start_time is the time of the earliest timestep I want to plot, type int ##end_time is the time of the latest timestep I want to plot, type int for j in range(start_time,end_time+1): ##Code to read data in from time step number j y = ##the data I want to plot red = 1. - (float(j)-float(start_time))/(float(end_time)-float(start_time)) blue = (float(j)-float(start_time))/(float(end_time)-float(start_time)) pp.plot(bin_center,spectrum,color=(red,0,blue)) pp.show() EDIT: Maybe this will make it clearer what I mean. Below is my figure: Each line shows the relation between the x-values and the y-values at a different time step. The red lines are earlier time steps, the blue lines are later time steps, and the purple lines are in the middle, as I defined above. With this already plotted, how would I create a color bar (vertically on the right side if possible) mapping the colors of the lines (continuously) to the time value of the time step each color represents? A: There are two things that you need to do here. * *Create a red to blue color map, because that isn't one of the standard maps in matplotlib.cm. *Create a mapping from time value to a color value recognized by matplotlib.pyplot.plot(). At the moment you're essentially doing both of these through the red and blue variables, which is fine for plt.plot(), but plt.colorbar() will require this information as a Matplotlib mappable object, e.g., a ScalarMappable. If you set up this object before you start plotting you can also use it to select the appropriate color in the plt.plot() call. import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as mcol import matplotlib.cm as cm start_time = 100 end_time = 120 # Generate some dummy data. tim = range(start_time,end_time+1) xdat = np.arange(0,90.1) ydat = [np.sin(0.2*(xdat-t)/np.pi) for t in tim] # Make a user-defined colormap. cm1 = mcol.LinearSegmentedColormap.from_list("MyCmapName",["r","b"]) # Make a normalizer that will map the time values from # [start_time,end_time+1] -> [0,1]. cnorm = mcol.Normalize(vmin=min(tim),vmax=max(tim)) # Turn these into an object that can be used to map time values to colors and # can be passed to plt.colorbar(). cpick = cm.ScalarMappable(norm=cnorm,cmap=cm1) cpick.set_array([]) F = plt.figure() A = F.add_subplot(111) for y, t in zip(ydat,tim): A.plot(xdat,y,color=cpick.to_rgba(t)) plt.colorbar(cpick,label="Time (seconds)")
doc_23535758
The problem is, when I try to get the JSON from the diagram, the attributes I've added to the custom node are not shown, although they appear on the lateral panel. Here's an example: <html> <head> <script src="http://cdn.alloyui.com/2.5.0/aui/aui-min.js"></script> <link href="http://cdn.alloyui.com/2.5.0/aui-css/css/bootstrap.min.css" rel="stylesheet"></link> <style> .diagram-node-custom .diagram-node-content { background: url(http://www.saltlakemailing.com/wp-content/uploads/2012/03/process_icon.png) no-repeat scroll center transparent; } </style> <script> var Y = YUI().use('aui-diagram-builder', function(Y) { Y.DiagramNodeCustom = Y.Component.create({ NAME: 'diagram-node', ATTRS: { type: { value: 'custom' }, customAttr: { validator: Y.Lang.isString, value: 'A Custom default' } }, EXTENDS: Y.DiagramNodeTask, prototype: { getPropertyModel: function () { var instance = this; var model = Y.DiagramNodeTask.superclass.getPropertyModel.apply(instance, arguments); model.push({ attributeName: 'customAttr', name: 'Custom Attribute' }); return model; } } }); Y.DiagramBuilder.types['custom'] = Y.DiagramNodeCustom; Y.diagramBuilder = new Y.DiagramBuilder( { boundingBox: '#myDiagramContainer', fields: [ { name: 'name1', type: 'custom', customAttr: 'VALUECUSTOM', xy: [100, 100] } ], srcNode: '#myDiagramBuilder' } ).render(); } ); </script> </head> <body> <div id="myDiagramContainer"> <div id="myDiagramBuilder"></div> </div> <button onClick="console.log('JSON: '+JSON.stringify(Y.diagramBuilder.toJSON()));">GET JSON</button> </body> </html> And this is the JSON I get when I do Y.diagramBuilder.toJSON(): {"nodes":[{ "transitions":[], "description":"", "name":"name1", "required":false, "type":"custom", "width":70, "height":70, "zIndex":100, "xy":[100,100] }]} A: The new attribute needs to be added to the SERIALIZABLE_ATTRS array. Something like that: this.SERIALIZABLE_ATTRS.push('customAttr'); I created a JSFiddle example: http://jsfiddle.net/aetevpfn/
doc_23535759
//This is the code of my QuestionViewController. I will provide the codes of my other view controller and class below as well import UIKit class QuestionViewController: UIViewController { struct currentAnswers{ static var currentAnswers = [Answer]() } @IBOutlet weak var questionLabel: UILabel! @IBOutlet weak var singleStackView: UIStackView! @IBOutlet weak var singleButton1: UIButton! @IBOutlet weak var singleButton2: UIButton! @IBOutlet weak var singleButton3: UIButton! @IBOutlet weak var singleButton4: UIButton! //My new single stack view @IBOutlet weak var SecondSingleStack: UIStackView! @IBOutlet weak var secondButton1: UIButton! @IBOutlet weak var secondButton2: UIButton! @IBOutlet weak var secondButton3: UIButton! @IBOutlet weak var secondButton4: UIButton! @IBOutlet weak var rangedStackView: UIStackView! @IBOutlet weak var rangedLabel1: UILabel! @IBOutlet weak var rangedLabel2: UILabel! @IBOutlet weak var rangedSlider: UISlider! @IBOutlet weak var questionProgressView: UIProgressView! var questions: [Question] = [ Question(text: "Little interest or pleasure in doing things?", type: .single, answers: [ Answer(text: "Not at all", type: .A), Answer(text: "Several Days", type: .B), Answer(text: "More than half of the days", type: .C), Answer(text: "Nearly everyday", type: .D) ]), Question(text: "Feeling down, depressed, or hopeless?", type: .single, answers: [ Answer(text: "Not at all", type: .A), Answer(text: "Several Days", type: .B), Answer(text: "More than half of the days", type: .C), Answer(text: "Nearly everyday", type: .D) ]), Question(text: "If you checked off any problems, how difficult have these problems made it for you at work/home/or with other people?", type: .ranged, answers: [ Answer(text: "Not difficult at all", type: .A), Answer(text: "Somewhat difficult", type: .B), Answer(text: "Very difficult", type: .C), Answer(text: "Extremely difficult", type: .D) ]) ] var questionIndex = 0 var answersChosen: [Answer] = [] override func viewDidLoad() { super.viewDidLoad() updateUI() } @IBAction func singleAnswerButtonPressed(_ sender: UIButton) { let currentAnswers = questions[questionIndex].answers switch sender { case singleButton1: answersChosen.append(currentAnswers[0]) case singleButton2: answersChosen.append(currentAnswers[1]) case singleButton3: answersChosen.append(currentAnswers[2]) case singleButton4: answersChosen.append(currentAnswers[3]) default: break } nextQuestion() } @IBAction func secondSinglePressed(_ sender: UIButton) { let currentAnswers = questions[questionIndex].answers switch sender { case secondButton1: answersChosen.append(currentAnswers[0]) case secondButton2: answersChosen.append(currentAnswers[1]) case secondButton3: answersChosen.append(currentAnswers[2]) case secondButton4: answersChosen.append(currentAnswers[3]) default: break } nextQuestion() } @IBAction func rangedAnswerButtonPressed() { let currentAnswers = questions[questionIndex].answers let index = Int(round(rangedSlider.value * Float(currentAnswers.count - 1))) answersChosen.append(currentAnswers[index]) nextQuestion() } func updateUI() { singleStackView.isHidden = true rangedStackView.isHidden = true let currentQuestion = questions[questionIndex] let currentAnswers = currentQuestion.answers let totalProgress = Float(questionIndex) / Float(questions.count) navigationItem.title = "Question #\(questionIndex+1)" questionLabel.text = currentQuestion.text questionProgressView.setProgress(totalProgress, animated: true) switch currentQuestion.type { case .single: updateSingleStack(using: currentAnswers) case .ranged: updateRangedStack(using: currentAnswers) } } func updateSingleStack(using answers: [Answer]) { singleStackView.isHidden = false singleButton1.setTitle(answers[0].text, for: .normal) singleButton2.setTitle(answers[1].text, for: .normal) singleButton3.setTitle(answers[2].text, for: .normal) singleButton4.setTitle(answers[3].text, for: .normal) } func updateSecondSingleStack(using answers: [Answer]){ SecondSingleStack.isHidden = false secondButton1.setTitle(answers[0].text, for: .normal) secondButton2.setTitle(answers[1].text, for: .normal) secondButton3.setTitle(answers[2].text, for: .normal) secondButton4.setTitle(answers[3].text, for: .normal) } func updateRangedStack(using answers: [Answer]) { rangedStackView.isHidden = false rangedSlider.setValue(0.5, animated: false) rangedLabel1.text = answers.first?.text rangedLabel2.text = answers.last?.text } func nextQuestion() { questionIndex += 1 if questionIndex < questions.count { updateUI() } else { performSegue(withIdentifier: "ResultsSegue", sender: nil) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ResultsSegue" { let resultsViewController = segue.destination as! ResultsViewController resultsViewController.responses = answersChosen } } } //This is my QuestionData class import Foundation struct Question { var text: String var type: ResponseType var answers: [Answer] } enum ResponseType { case single, ranged } struct Answer { var text: String var type: CaseScore } enum CaseScore: Character { case A = "", B = "", C = "", D = "" var definition: String { switch self { case .A: return "Not at all - Should be replaced with percentage and Advice" case .B: return "Several Days" case .C: return "More than half of the days" case .D: return "Nearly everyday" } } } //And finally this is my ResultsViewController import UIKit class ResultsViewController: UIViewController { @IBOutlet weak var resultAnswerLabel: UILabel! @IBOutlet weak var resultDefinitionLabel: UILabel! var responses: [Answer]! override func viewDidLoad() { super.viewDidLoad() navigationItem.hidesBackButton = true calculatePersonalityResult() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func calculatePersonalityResult() { var frequencyOfAnswers: [CaseScore:Int] = [:] let responseTypes = responses.map { $0.type } for response in responseTypes { frequencyOfAnswers[response] = (frequencyOfAnswers[response] ?? 0) + 1 } let mostCommonAnswer = frequencyOfAnswers.sorted { $0.1 > $1.1 }.first!.key resultAnswerLabel.text = "You are a \(mostCommonAnswer.rawValue)!" resultDefinitionLabel.text = mostCommonAnswer.definition } } I am developing a Personality Test IOS app for school on XCode and I have done it similar to the IBooks 'App Development with Swift' book, Guided Project: Personality Quiz, page 398. Moreover, my goal is a bit different. I have 10 questions for the quiz and each of the questions will require answer options like: (A. Not at all, B. Several Days, C. More than half o the days, D. Nearly every day). The way mentioned in the book is for different types of questions with different answer options. The code provided is an example of the 2 questions and answers, but there will be more to come if I complete the 10 questions the same way. var questions: [Question] = [ Question(text: "Little interest or pleasure in doing things?", type: .single, answers: [ Answer(text: "Not at all", type: .A), Answer(text: "Several Days", type: .B), Answer(text: "More than half of the days", type: .C), Answer(text: "Nearly everyday", type: .D) ]), Question(text: "Feeling down, depressed, or hopeless?", type: .single, answers: [ Answer(text: "Not at all", type: .A), Answer(text: "Several Days", type: .B), Answer(text: "More than half of the days", type: .C), Answer(text: "Nearly everyday", type: .D) ]), I would like to know another way to reduce amount of code and use the same answer options for all questions, without affecting accuracy of choice for each question. Please let me know if you know how to do it. Much appreciated. A: You can do something like this var answers = [Answer]() answers.append(Answer(text: "Not at all", type: .A)) answers.append(Answer(text: "Several Days", type: .B)) answers.append(Answer(text: "More than half of the days", type: .C)) answers.append(Answer(text: "Not at all", type: .A)) And (How to use) var questions: [Question] = [ Question(text: "Little interest or pleasure in doing things?", type: .single, answers: answers), Question(text: "Feeling down, depressed, or hopeless?", type: .single, answers: answers), The basic idea is to create a variable which holds the array of Answer and then use it in your questions.
doc_23535760
>>> a = {'test1.1': 5} >>> 'test: {test1.1}'.format(**a) KeyError: 'test1' It obviously fails because format is literally trying to access the object test1 and its attribute 1. Is there a way to format this string and force the key values to be taken as strings? (Looking for a Python 2 and 3 solution.) A: Just another alternative. The old %-style formatting doesn't care: >>> a = {'test1.1': 5} >>> 'test: %(test1.1)s' % a 'test: 5' A: A little hack, but this does the trick: In [5]: 'test: {0[test1.1]}'.format(a) Out[5]: 'test: 5' Use dict-like indexing with [..]. The 0 is positional indexing, and a is the 0th argument. If it's the only argument, you can omit 0.
doc_23535761
Anyone tried it out? A: It seems so: System.out.println(WordUtils.capitalizeFully("можеше да провериш сам")); prints Можеше Да Провериш Сам The documentation says: Capitalization uses the unicode title case, normally equivalent to upper case A: Chinese and other similar languages (Japanese, Korean, Vietnamese) does not have concept of upper- and lower-case characters (unless transliterated). There are quite a lot languages like this. The only way to be 100% sure is test, since documentation might be erroneous. I would be more concerned if the utility you mention capitalizes Turkish language correctly - it has strange concept of dotted and dotless I. German could also be a problem, since sharp S should be uppercased to SS.
doc_23535762
doc_23535763
I work on a cluster with several nodes which are managed via slurm. All these nodes share the same disk memory (I think it uses NFS4). My problem is that since this disk memory is shared by a lots of users, we have a limit a mount of disk memory per user. I use slurm to launch python scripts that runs some code and saves the output to a csv file and a folder. Since I need more memory than assigned, what I do is I mount a remote folder via sshfs from a machine where I have plenty of disk. Then, I configure the python script to write to that folder via an environment variable, named EXPERIMENT_PATH. The script example is the following: Python script: import os root_experiment_dir = os.getenv('EXPERIMENT_PATH') if root_experiment_dir is None: root_experiment_dir = os.path.expanduser("./") print(root_experiment_dir) experiment_dir = os.path.join( root_experiment_dir, 'exp_dir') ## create experiment directory try: os.makedirs(experiment_dir) except: pass file_results_dir = os.path.join( root_experiment_dir, 'exp_dir' , 'results.csv' ) if os.path.isfile(file_results_dir): f_results = open(file_results_dir, 'a') else: f_results = open(file_results_dir, 'w') If I directly launch this python script, I can see the created folder and file in my remote machine whose folder has been mounted via sshfs. However, If I use sbatch to launch this script via the following bash file: export EXPERIMENT_PATH="/tmp/remote_mount_point/" sbatch -A server -p queue2 --ntasks=1 --cpus-per-task=1 --time=5-0:0:0 --job-name="HOLA" --output='./prueba.txt' ./run_argv.sh "python foo.py" where run_argv.sh is a simple bash taking info from argv and launching, i.e. that file codes up: #!/bin/bash $* then I observed that in my remote machine nothing has been written. I can check the mounted folder in /tmp/remote_mount_point/ and nothing appears as well. Only when I unmount this remote folder using: fusermount -u /tmp/remote_mount_point/ I can see that in the running machine a folder has been created with name /tmp/remote_mount_point/ and the file is created inside, but obviously nothing appears in remote machine. In other words, it seems like by launching through slurm, it bypasses the sshfs mounted folder and creates a new one in the host machine which is only visible once the remote folder is unmounted. Anyone knows why this happens and how to fix it? I emphasize that this only happens if I launch everything through slurm manager. If not, then everything works. I shall emphasize that all the nodes in the cluster share the same disk space so I guess that the mounted folder is visible from all machines. Thanks in advance. A: I shall emphasize that all the nodes in the cluster share the same disk space so I guess that the mounted folder is visible from all machines. This is not how it works, unfortunately. Trying to put it simply; you could say that mount point inside mount points (here SSHFS inside NFS) are "stored" in memory and not in the "parent" filesystem (here NFS) so the compute nodes have no idea there is an SSHFS mount on the login node. For your setup to work, you should create the SSHFS mount point inside your submission script (which can create a whole lot of new problems, for instance regarding authentication, etc.) But before you dive into that, you probably should enquiry whether the cluster has another filesystem ("scratch", "work", etc.) where there you could temporarily store larger data than what the quota allows in your home filesystem.
doc_23535764
#include <iostream> using namespace std; class node { public: int element; node* ptr; friend class list; }; class list { public: //Including head and tail attributes and making them public so that they are easily accessible to anyone using the linked list construction node head; node tail; list() { head.element = -1; //-1 is sentinel value tail.element = -1; head.ptr = NULL; tail.ptr = NULL; head = tail; } bool empty() { return((head.ptr == NULL) && (head.element == -1)); } void insert(int a) { if(empty()) { head.element = a; tail.element = a; } else { //Making a new unnamed node, inserting the new value, and updating the tail attribute node* v = new node; tail.ptr = v; v -> element = a; v -> ptr = NULL; tail.element = v-> element; tail.ptr = v -> ptr; } } void print() { int i = 0; node *pointer = head.ptr; while(pointer != NULL) { cout << "The " << i+1 << "th element is: " << pointer -> element; pointer = pointer -> ptr; i++; } } }; int main() { int values[3] = {1, 2, 3}; list lst; for(int i = 0; i < 3; i++) { lst.insert(values[i]); } cout << lst.head.element << endl; cout << lst.tail.element; lst.print(); }; A: The head and tail nodes should remain as dummy nodes and not made part of the list. The element values of head and tail nodes do not need to be initialized or checked. An insert sequence for a non-empty list is // ... v->ptr = head.ptr; head.ptr = v; // ... See if you can fix the rest of the code. If you create an append function, an append sequence for a non-empty list is // ... v->ptr = NULL; tail.ptr->ptr = v; // ..
doc_23535765
In my base class: EventListenerCustom* listener = EventListenerCustom::create("my_event", myVirtualEventMethod); Updated based on Kazuki's answer: class BaseScene : public cocos2d::Layer { public: virtual void myVirtualEventMethod(); }; My method: EventListenerCustom* listener = EventListenerCustom::create("my_event", CC_CALLBACK_1(BaseScene::myVirtualEventMethod, this)); See the error in comments below. A: EventListenerCustom::create() accepts std::function. https://github.com/cocos2d/cocos2d-x/blob/v3/cocos/base/CCEventListenerCustom.h#L59 static EventListenerCustom* create(const std::string& eventName, const std::function<void(EventCustom*)>& callback) So you can specify a member function with std::bind like this. EventListenerCustom* listener = EventListenerCustom::create("my_event", std::bind(&YourSubclass::myVirtualEventMethod, this, std::placeholders::_1)); And there is a macro for it in cocos2d-x. EventListenerCustom* listener = EventListenerCustom::create("my_event", CC_CALLBACK_1(YourSubclass::myVirtualEventMethod, this)); EDITED No viable conversion from '__bind<void (BaseScene::*)(), BaseScene , std::__1::placeholders::__ph<1>&>' to 'const std::function<void(Eventcustom)>' Because the type of myVirtualEventMethod is not the same as void(EventCustom*). Thus it should be virtual void myVirtualEventMethod(EventCustom*); Or EventListenerCustom* listener = EventListenerCustom::create("my_event", CC_CALLBACK_0(YourSubclass::myVirtualEventMethod, this));
doc_23535766
* *Why does this code return this error? import random with open('rn.txt', 'w') as f: for i in range(10): number = random.random() f.write(str(number) + '\n') content=f.read() print (content) Error: Traceback (most recent call last) <ipython-input-11-ddb88b6f5426> in <module> 4 number = random.random() 5 f.write(str(number) + '\n') ----> 6 content=f.read() 7 print (content) UnsupportedOperation: not readable *Why does this code write only a single value to the file? import random for i in range(10): with open('rn.txt', 'w') as f: number = random.random() f.write(str(number) + '\n') content=f.read() print (content) This code is supposed to generate 10 random numbers and write them to the file rn.txt. What am I doing wrong? A: You're trying to perform both read and write operations to a file which is opened in read or write mode. Choose one at a time. For example, the following could work: import random # first open the file in Write mode ('w') with open('rn.txt', 'w') as f: for i in range(10): f.write(str(random.random()) + '\n') # now open the file in Read mode ('r') with open('rn.txt', 'r') as f: for line in f: print(line)
doc_23535767
public class Project { private String name; private Path path; private Map<String, Process> processes; //getters and setters } public class Process { private String name; private String path; private Map<String, Activity> activities; //getters and setters } public class Activity { private String name; private String type; //getters and setters } I'm trying to write a function which will return a Stream of Process or Process.path where the Process contains at least one activity having type="starter" i.e. Activity.type="starter". I came up with the below code but it returns a Stream<Activity> whereas what I'm looking for is a Stream<Process> or Stream<String> containing the path. project.processes.values().stream() .flatMap(process -> process.getActivities().values().stream() .filter(activity -> "starter".equals(activity.getType()))); What is the most efficient way of doing this? A: Don't use flatMap if you want a Stream<Process> because flatMap will "destroy" information about the processes. You should create a "nested" stream: project.getProcesses().values().stream() .filter(x -> x.getActivities().values().stream().anyMatch( y -> "starter".equals(y.getType()) ) ); Now it's a Stream<Process>. A: The code given will map the processes to activities via the .flatMap operator. The operator You are looking for is probably .filter if I understand correcly the request of I'm trying to write a function which will return a Stream of Process or Process.path where the Process contains at least one activity having type="starter" i.e. Activity.type="starter". project.processes.values().stream() .filter(process -> process.getActivities().values().stream() .filter(activity -> "starter".equals(activity.getType())).findFirst().isPresent()); You can then map to Project.path via a .map operator. Given the previous operation as processStream, we might write processStream.map(process -> process.getPath()) It may be worth to note that, if the list of activities may be finite, the .findFirst terminal operation may be substituted for a .count terminal operation. It all depends on the clarity of the code, and the speed requirements of the code.
doc_23535768
[ Grid width is ONE, but because of anti-aliasing, it became so fat. I managed to hack it: when coordinates are (0.5, 0.5) averything is okay… [ Looks good. But the hack works in designer only: in actual application nothing changes. Actually, the first image was shot with this hack. Is there a way to fix it? Is it a hardware problem? Got an ATI Radeon HD 3200 graphic card.
doc_23535769
But I can't configure nixops to use /secrets/stage_ssh_key ssh key This is not working ( actually this is not documented, I have found it here https://github.com/NixOS/nixops/blob/d4e5b779def1fc9e7cf124930d0148e6bd670051/nixops/backends/none.py#L33-L35 ) { stage = { pkgs, ... }: { deployment.targetHost = (import ./nixos-generated/stage.nix).terraform.ip; deployment.targetEnv = "none"; deployment.none.sshPrivateKey = builtins.readFile ./secrets/stage_ssh_key; deployment.none.sshPublicKey = builtins.readFile ./secrets/stage_ssh_key.pub; deployment.none.sshPublicKeyDeployed = true; environment.systemPackages = with pkgs; [ file ]; }; } nixops ssh stage results in asking for password, expected - login without password nixops ssh stage -i ./secrets/stage_ssh_key works as expected, password is not asked How to reproduce: * *download repo *rm -rf secrets/* *add aws keys in secrets/aws.nix { EC2_ACCESS_KEY="XXXX"; EC2_SECRET_KEY="XXXX"; } *nix-shell *make generate_stage_ssh_key *terraform apply *make nixops_create *nixops deploy asks password
doc_23535770
r_id comment 1 Weight cannot exceed 40 kg 2 You must not make the weight go over 31 k.g 3 Don't excel above 94kg 4 Optimal weight is 45 kg 5 Don't excel above 62 kg 6 Weight cannot exceed 7000g What I want to select is the weight a r_id's cannot exceed. So my desired output is r_id max weight 1 40 2 31 3 94 5 62 As you can see, r_id 4 wasn't included since it wasn't taking about the maximum weight and 6 wasn't included because it is in grams. I am struggling with two things. * *There are multiple phrases, how can I do a OR operator check in my regex column. *Sometimes the kg number is written like 40kg, 40 KG, 40 k.g or 40kilos. While all things are kilograms, the kg is written in different ways. How can I only extract the number (but ensuring the kg is written in one of the above ways, so I don't accidentally extract something like 4000g. SELECT r_id, REGEX_SUBSTR(REGEX_SUBSTR('cannot exceed [0-9]+ kg'), '[0-9]+ kg')) as "max weight" FROM reviews; My statement only checks for one particular type of sentence and doesn't check if the number is in kilograms. A: You could just extract the number from the string. There only appears to be one and then check if the string looks like certain patterns: select regexp_substr(comm, '[0-9]+') from reviews where regexp_like(comm, '(exceed|go over|above).*[0-9]+ ?(kg|k.g)'); Here is a db<>fiddle. A: You can use a more robust regex expression to extract the number. I don't have an oracle DB, but try something like: SELECT r_id, REGEX_SUBSTR(comment, '([0-9]+) ?(k\.?g\.?|kilos)', 1, 1, 'i') as "max weight" FROM reviews; You can see this regex matching the given string in action at https://regex101.com/r/07Rstk/1. This also explains what the regex means. We also turn on the case insensitive flag in order to properly handle any capitalization. https://docs.oracle.com/cd/E18283_01/olap.112/e17122/dml_functions_2069.htm Edit: To do checks for exceed, go over, etc. Note that we have changed the position parameter from 1 to 2 since we now care about the second capture group. SELECT r_id, REGEX_SUBSTR(comment, '(exceed|go over|above)\h*([0-9]+) ?(k\.?g\.?|kilos)', 1, 2, 'i') as "max weight" FROM reviews;
doc_23535771
I need to use Scanner in = new Scanner("123 232 2323"); and get this result in the terminal inside Intellij: 123 232 2323 Thanks! A: You can get the nextInt while there is one and print integers to the console. while (in.hasNextInt()) { System.out.println(in.nextInt()); } A: try to use hasNext() and nextLine() methods of scanner class, like: String res; while(in.hasNext()){ res += in.nextLine(); } System.out.println(res);
doc_23535772
var myConfig = { type: 'bar', legend: { layout: "x4", overflow : "page", shadow : false, align : "left", alpha :0.05, "adjust-layout": true, marker : { type : "circle", size : "7px", "border-color" :"none" } }, scaleX: { // convert text on scale indices labels: ['Automotive', 'Retail', 'Wholesale'] }, plot: { barWidth:"50%", animation: { effect: 'ANIMATION_EXPAND_BOTTOM', method: 'ANIMATION_STRONG_EASE_OUT', sequence: 'ANIMATION_BY_NODE', speed: 275, } }, series: [ { // plot 1 values, linear data values: [23, 20, 27], text: 'Sum of target Premi', backgroundColor: '#fa6383', borderRadius: 5, }, { // plot 2 values, linear data values: [35, 42, 33], text: 'Sum of premi Leads', backgroundColor: '#fb9f40', borderRadius: 5, }, { // plot 2 values, linear data values: [15, 22, 13], text: 'Sum of premi Activity', backgroundColor: '#fdcd55', borderRadius: 5, }, { // plot 2 values, linear data values: [15, 22, 13], text: 'Sum of premi Booking', backgroundColor: '#4bc0c1', borderRadius: 5, } ] }; for my settings like this. there are suggestions so there can be no space ? i have try documentation but does not work. https://www.zingchart.com/docs/chart-types/bar A: I'm not sure that I correctly understood your problem but probably you can try to use "barsOverlap" in "plot" configuration to achieve the desired result. var myConfig = { type: 'bar', legend: { layout: "x4", overflow : "page", shadow : false, align : "left", alpha :0.05, "adjust-layout": true, marker : { type : "circle", size : "7px", "border-color" :"none" } }, scaleX: { // convert text on scale indices labels: ['Automotive', 'Retail', 'Wholesale'] }, plot: { barWidth:"50%", barsOverlap: '50%', animation: { effect: 'ANIMATION_EXPAND_BOTTOM', method: 'ANIMATION_STRONG_EASE_OUT', sequence: 'ANIMATION_BY_NODE', speed: 275, } }, series: [ { // plot 1 values, linear data values: [23, 20, 27], text: 'Sum of target Premi', backgroundColor: '#fa6383', borderRadius: 5, }, { // plot 2 values, linear data values: [35, 42, 33], text: 'Sum of premi Leads', backgroundColor: '#fb9f40', borderRadius: 5, }, { // plot 2 values, linear data values: [15, 22, 13], text: 'Sum of premi Activity', backgroundColor: '#fdcd55', borderRadius: 5, }, { // plot 2 values, linear data values: [15, 22, 13], text: 'Sum of premi Booking', backgroundColor: '#4bc0c1', borderRadius: 5, } ] };
doc_23535773
create or replace procedure SwapDutyRota(row_id1 in varchar2,row_id2 in varchar2) as temp_officer varchar2(20); begin SELECT duty_officer INTO temp_officer FROM duty_rota WHERE ROWID = row_id1 ; UPDATE duty_rota SET duty_officer = (SELECT duty_officer FROM duty_rota WHERE ROWID = row_id2) WHERE ROWID = row_id1; UPDATE duty_rota SET duty_officer = temp_officer WHERE ROWID = row_id2; END SwapDutyRota; The below snippet of ASP.NET is firing that particular stored proc. OracleConnection conn = new OracleConnection(connectionString); OracleCommand cmd = new OracleCommand("SwapDutyRota('" + Label1.Text + "','" + DropDownList2.SelectedValue + "')", conn); cmd.CommandType = CommandType.StoredProcedure; conn.Open(); var a = cmd.ExecuteNonQuery(); if (a > 0) { lblSuccess.Visible = true; lblSuccess.Text = "Swapped Successfully"; } else { lblSuccess.Visible = true; lblSuccess.Text = "Could not be Swapped"; } conn.Close(); When I am running the Stored Proc from Oracle prompt(SQL Developer) it works like a charm but when it is getting fired from above code it is giving below error ORA-06550: line 1, column 7: PLS-00801: internal error [22503] ORA-06550: line 1, column 7: PL/SQL: Statement ignored Can somebody please help how to get rid of this error? I tried to debug but unable to find any proper way to determine how the whole query is executed and where the stored proc is failing.
doc_23535774
the text of the error I get in the terminal: fs.readdir("./komutlar/",(err,files) => { ^ TypeError: Cannot read properties of undefined (reading 'readdir') at Object. (C:\Users\tDiff\Desktop\TDIFF\tdıff.js:15:4) enter code here const client = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS ] }) const {token} = require("./ayarlar.json") const {fs} = require("fs"); const { Options } = require("discord.js"); global.client = client; client.commands = (global.commands = []); fs.readdir("./komutlar/",(err,files) => { // where l got the error if(err) throw err; files.forEach(f => { if(!f.endsWith(".js")) return; let p = require(`./komutlar/${f}`) client.commands.push({ name:p.name.toLowerCase(), description:p.description, options:p.options, type:p.type, }); console.log(`✔ Komut eklendi: ${p.name}`); }) }); fs.readdir("./events/",(err,files) => { // where l got the error files.forEach(f => { if(!f.endsWith(".js"))return; const e = require(`./events${f}`); let eName = f.split(".")[0]; client.on(eName, (...args) => { e() }) }) }); client.once("ready",() => { console.log(`${client.user.tag} Aktif!`); client.user.setPresence({ activities:[ { name:"TDIFF", type:"LISTENING" } ], status:"dnd" }) }) client.login(token)``` A: The error you are getting is actually telling you that you are trying to read/call someting (in your case readdir) on an object/class/... which is undefined. in your case fs is undefined and the interpreter is trying execute this: undefined.readdir(...) which does not make any sense since undefined does not have any properties on its own. I would assume that you forgot to import the fs package on top of the file: const fs = require('fs');
doc_23535775
A: These names are used in the Django admin pages. So instead of using the name of the model class, it will use the verbose_name of that model to make messages that are less "mechanical". Furthermore you can use these in your own projects. For example if you want to obtain the verbose_name of a model you do not (statically) know, you can retrieve it with: model._meta.verbose_name This can be useful to write generic messages. You can write a warning message like: Are you sure you want to delete the {{ obj._meta.verbose_name }}? If your model is PizzaTopping, then the default verbose_name is 'pizza topping'. It is more human friendly to write "Are you sure you want to delete the pizza topping?" than "Are you sure you want to delete the PizzaTopping?". You can for example retrieve the verbose_name of a field with: model._meta.get_field('some_field').verbose_name Django's ModelForm [Django-doc] furthermore use by default the (capitalized) verbose_name and the help_text as label and help_text in the form. If you thus render a model form, and you do not tweak the settings, it will take the verbose_names of the model fields as labels, and the help_text will show up over that field.
doc_23535776
I have imported many modules in the script (for example: kiteconnect). I wish to have a separate logger for all the imported modules. something like import_logger = logging.getLogger(**all_modules_excluding__name__**) I wish to have separate loggers for the module ( that i am inside) and for the modules ( which I have imported) How can I do that? thanks in advance A: If you do not control the source code of the modules you can't stop them from creating their own loggers that all have different names. There is however one feature that helps you: loggers are hierarchical, and unless propagation hasn't been explicitly turned off on them they all will send their logs up to the root logger. So in effect the root logger will have all the logs from all modules. If you turn of propagation on your app logger you effectively have your app logs on that logger, and all module logs in the root logger. You may still have to get the individual modules loggers to set their level. In code it would look something like this: import logging #import modules here import_logger = logging.getLogger() import_logger.addHandler(logging.StreamHandler()) # use any handler you want logger = logging.getLogger(__name__) logger.propagate = False
doc_23535777
For example: John works in India. Output should be: John PER NNP works O O in O O India LOC NNP So it should identify the named entity as well as the POS tags. I have created my own set of training data. I am using the below property file trainFile = training.tsv serializeTo = model.ser.gz map = word=0,answer=1,tag=2 useClassFeature=true useWord=true useNGrams=true noMidNGrams=true maxNGramLeng=6 usePrev=true useNext=true useSequences=true usePrevSequences=true useTags = true useWordTag = true useGenericFeatures = true mergeTags = true maxLeft=1 useTypeSeqs=true useTypeSeqs2=true useTypeySequences=true wordShape=chris2useLC useDisjunctive=true The training file looks like this: John PER NNP works O O in O O India LOC NNP I am using the below code to run NER in python: tagging_NER = StanfordNERTagger('.../model.ser.gz','.../stanford-ner.jar',encoding='utf-8') token = StanfordTokenizer('.../stanford-ner.jar') tok = token.tokenize(text) tags = tagging_NER.tag(tok) Now this code gives me just the named entities. It does not return me the POS tags. Is there any method by which I could get both these things?
doc_23535778
I am able to insert into other SQL tables in Windows Azure using below code. MSClient *client = [MSClient clientWithApplicationURLString:@"https://xxxxxxxxxx.azure-mobile.net/" applicationKey:@"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"]; NSDictionary *item = @{ @"latitude" : latitude, @"longitude" : longitude, @"speed" : speed, @"channel" : [deviceIDs objectAtIndex:notificationcounter], @"message" : @"Notification from iOS MapApp", @"truck_number" : @"T201" }; MSTable *smart_truck_incidentTable = [client tableWithName:@"smart_truck_incident"]; [smart_truck_incidentTable insert:item completion:^(NSDictionary *insertedItem, NSError *error) { if (error) { NSLog(@"Error: %@", error); } else { NSLog(@"Item inserted, id: %@", [insertedItem objectForKey:@"id"]); } }]; I tried to reuse this code by changing clientWithApplicationURLString and applicationKey values to storage account values. But the insert simply not working. Can anyone point me to some sample code or reference? Or any other better suggestions to store images in Windows Azure is also welcome. A: Thought of sharing if anyone else is looking for the same. Download iOS code from http://www.files.com/shared/51f622c62ba2f/BlobExample.zip. Update credentials in ViewController.m with your storage name and access key.
doc_23535779
Below is the way I think this can be done, and need your opinions whether this is the standard/right way of doing this, or any better approaches exist. What I've thought of is this: I add triggers in SQL Server, which, on any modification, will insert the identifiers of modified/added rows into special table, which I will check periodically from my application. Suppose there are 3 tables: Customers, Products, Services. i will make three additional tables: Change_Customers, Change_Products, Change_Services, and will insert the identifiers of modified rows of the respective tables. Then I will read these Change_* tables from my application periodically and delete processed records. Now if you agree that above solution is right, I have another question: Is it better to have separate Change_* tables for each of my tables I wish to monitor, or is it better to have one fat Changes table which will contain the changes from all tables. A: Query Notifications is the technology designed to do exactly what you're describing. You can leverage Query Notifications from managed clients via the well known SqlDependency class, but there are native Ole DB and ODBC ways too. See Working with Query Notifications, the paragraphs about SSPROP_QP_NOTIFICATION_MSGTEXT (OleDB) and SQL_SOPT_SS_QUERYNOTIFICATION_MSGTEXT (ODBC). See The Mysterious Notification for an explanation how Query Notifications work. This is the only polling-free solution that work with any kind of updates. Triggers and polling for changes has severe scalability and performance issues. Change Data Capture and Change Tracking are really covering a different topic (synchronizing datasets for occasionally connected devices, eg. Sync Framework). A: Change Data Capture(CDC)--http://msdn.microsoft.com/en-us/library/cc645937.aspx First you will need to enable CDC in database :: USE db_name GO EXEC sys.sp_cdc_enable_db GO Enable CDC on table then :: sys.sp_cdc_enable_table Then you can query changes A: * *If your version of Sql Server is 2005 - you may use Notification Services *If your Sql Server is 2008+ - there is most preferrable way to use triggers and log changes to log tables and periodically poll these tables from application to see the changes
doc_23535780
However, for my domain entities (which contain both data and behavior) I'd still like to have features like automatic toString, equals and destructuring declarations. I can easily achieve this with data classes, but based on the above that seems to be semantically incorrect: data class Person( private var name: String, val age: Int ) { fun isAdult() = age >= 18 fun changeName(newName: String) { this.name = newName } } Is it inherently wrong to use data class for this purpose? Is there another way to keep these features but be semantically correct at the same time? A: I think there are two important topics: Immutability I would embrace immutability and not provide any mutation method in the domain classes. You can use copy method to create new instance with different immutable properties. Identity A Data class uses all properties declared in the constructor in the equals method. It means it is a value class, that is, it doesn't have identity. It is a value like Point(x,y). Two instances Point(1,2) and Point(1,2) are indistinguishable. They are the same if all of their properties are the same. Conclusion Use a regular class for a domain entity like an User. Use the properties which define the identity of your entity to implement equals, hashcode, etc. Use a data class for a domain value like an Address. It is fine for a data class to have functions as long as they are mutation free. In your case I would implement something like that: data class Address(val streetName: String) class Person( val id: Int, val name: String, val age: Int, val address: Address ) { fun isAdult() = age >= 18 override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Person if (id != other.id) return false return true } override fun hashCode(): Int { return id } fun copy( id: Int = this.id, name: String = this.name, age: Int = this.age, address: Address = this.address) = Person(id, name, age, address) override fun toString(): String { return "Person(id=$id, name='$name', age=$age, address=$address)" } } fun main() { val personA = Person(123312, "Person A", 17, Address("Street 1")) println(personA.isAdult()) println(personA.age) val olderPersonA = personA.copy(age = 18) println(olderPersonA.isAdult()) println(olderPersonA.age) } EDIT: As you said, there is the option of using a data class and only override equals and hashcode, but I'm no sure if it is semantically correct. Comments on that are appreciated. data class Person( val id: Int, val name: String, val age: Int, val address: Address ) { fun isAdult() = age >= 18 override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Person if (id != other.id) return false return true } override fun hashCode(): Int { return id } }
doc_23535781
def login(): # find user in db # check if user exists # check password # login user Should each action be its own function? or should all the code just stay in there? Edit: I ask this because I usually just put all my code in one function, but a friend of mine puts everything he needs to do in multiple functions and then fills in the blanks on functions he wrote down ex. he would write this: def login(): findUser() checkUser() checkPass() userLoggedin() he would then create those functions and fill them in. A: My advice is: Break it into meaningful, re-usable functions. This will be most useful to maintain when your code base grows. # find user in db => re-usable # check if user exists => No. If you find it, it exists. So you don't need that. If you don't find it, it does not. So both should be the same. # check password => re-usable # login user => re-usable Note: There is a WWDC 2012 session video entitled: Basics+Habits: Building Your Software Projects To Last that you could watch. The targeted audience is mainly MAC developers, but many of their advices applies to other object-oriented languages as well. You will need a free MAC developer account to access it. A: I'd say YES and they should be split into separate projects speaking from a Visual Studio point of view. Find User - Data Repository Check User exists - Probably a Model or Business Layer Check Password, model or business layer Login - Business layer The aim here is to group code into logical concerns.
doc_23535782
Class A *instanceACasted = (ClassA *)idvalue ; then call the method [instanceACasted methodCall]; This is one way but i dont know about the class name using id how i call the method A: You can use introspection and performSelector: SEL selector = @selector(yourMethodSignature:); if ([obj respondsToSelector:selector]) { [obj performSelector:selector]; } Apple documentation on how to use introspection. A: To get rid of the warning method not found , you must cast/convert your id type object to the proper object type. But in this case you need to know the Class name of id type object. If you don't know the class name then follow this answer. A: The correct answer depends heavily on what you are actually doing. Your code doesn't compile, and your error message "method not found" does not exist in Clang, so I can't tell what is actually happening. Also, your subject contradicts what I might guess from your code (there is no mention of "id" in your code). Here are a few guesses: You are calling a method that has not been declared ObjC mostly reads code from top to bottom, and reads each source file (implementation file, .m file, not header) separately, as its own "compilation unit". So if your source file tries to call a method that is not in your file, you'll get an error message like error: no known instance method for selector 'doSomething' or error: no known class method for selector 'doSomething'. To fix that, you need to #import the header that declares the class/protocol that defines the method you want to call. You are calling a class method on an instance (object) or an instance method on a class Class methods start with a +, instance methods with a -. They are totally separate. So if you declare a method with a +, then call it on an object of that type (instead of on myObject.class or the class name), the compiler may warn you about error: no known instance method for selector 'doSomething' resp. error: no known class method for selector 'doSomething'. Here the important part is that it is looking for a class method, even though an instance method exists, and vice versa. You are calling a method that the given object/class does not have In that case, you get an exception that bounces you back into the run loop and a log message at runtime. This could mean that your code is expecting a newer OS's version of a class (which has that method) but is running on an older OS (where this method didn't exist yet). In that case, you get a message like unrecognized selector sent to instance 0x7fffdb13cf38 or unrecognized selector sent to class 0x7fffdb13cf38. To fix that, you can check whether an object responds to a given method by asking it [theObject respondsToSelector: @selector(doSomething)], and only then calling it, otherwise doing something equivalent that doesn't rely on that method. Or you could check if that method is available ahead of time and just hide the button or whatever that needs this on older OSes that way. Note that, if you had e.g. an NSObject* and you knew that in one special case it could actually be an NSString*, and you use -respondsToSelector: to verify that it implements @selector(characterAtIndex:) in that case, you may still get an error message that NSObject instances do not responds to -characterAtIndex:. In this case, you can turn off that warning by doing: NSObject* myNSObject = myArray.firstObject; if( [myNSObject respondsToSelector: @selector(characterAtIndex:)] ) [(NSString*)myNSObject characterAtIndex: 0]; or whatever. You usually never write code like this, though. Checking "what class is my object" is usually an indicator that you built your class hierarchy wrongly, so I only mention that for completeness' sake. How does 'id' figure into this? You mention id in your headline, but your example doesn't use it. If you call a method on id, ObjC will let you do anything. All it wants is that somewhere there is a class or instance method declaration for the given method, on any object. In that case, it will only blow up at runtime if you call a method the given object doesn't have.
doc_23535783
[more details] This server is a Azure VM. It has an internal IP address and a Public IP address. On the same server, when I lauch P4Admin and enter localhost:1666, it works. It also works when I enter <computername>:1666. It also works when I use <Internal IP>:1666. It DOES NOT work when I enter <Public IP>:1666. The machine is fully accessible via the Internet using the public IP. A: Resolved. In the Azure Portal, created a new endpoint with public port 1666 and private port 1666. I guess it provides a mapping between external and internal IP addresses and ports. Thanks everybody.
doc_23535784
The search has a dropdown for categories. I want the search go to the respective model/controller based on the dropdown. <php echo $this->Form->create('Fashion', array( 'url' => array_merge(array('action' => 'search'), $this->params['pass']))); echo $this->Form->input('name', array('div' => false, 'empty' => true, 'label'=>'')); echo $this->Form->input('id', array('div' => false, 'empty' => 'All', 'label'=>'', 'class' => 'dropdown_categories', 'options'=>array(array(1 => 'Fashion', 2 => 'Books, Games & Music', 3 => 'Electronic Gadget', 4 => 'Gifts, Toys & Hobbies', 5 => 'Health & Beauty', 6 => 'Homes, Garden & Tools', 7 => 'Sports', 8 => 'Automotives')))); with this coding, its only search items in fashion table. I have tables: fashions, books, electronics, gifts and many more. How can I change the "$this->Form->create('Fashion');" based on the dropdown. is there any better way to solve this. Either using if else or javascript. A: This is not a search index plugin. The plugin implements the PRG pattern as stated here in the readme.md. If your tables are not related, and they don't seem so, you'll need to implement a search index or better use a dedicated DB like Elastic Search for it. The search plugin can then be used to filter that index. If and only if your tables are related you can search across them. The documentation in the develop branch was updated and is awaiting its merge to master. See the example section of how to search across related tables.
doc_23535785
and later someone said can't use anymore. So I ask here to make sure, Can use in my app and pass to Appstore? Best Regards A: Take a look at this Apple tech note. It shows how to "legally" do screenshots in UIKit where it will get accepted into the App Store: http://developer.apple.com/library/ios/#qa/qa1703/_index.html#//apple_ref/doc/uid/DTS40010193 A: They have been rejecting it again for a long time, since iOS 4 release in 2010 when they introduced AVFoundation framework which was a solution for all the camera frame capturing that UIGetScreenImage() was mostly used for before. They offered two alternatives, one for camera frames (Technical Q&A QA1702) and one for UIKit elements (Technical Q&A QA170 - the one that Michael mentioned), but neither of those is nearly enough usable for taking actual screenshots. You can read the announcement at developer forums (iOS Developer Program account required). A: Around a year ago, Apple started to run static analysis on submitted binaries during the App Store review process. Before that, access to private APIs will pass the review if the functionality itself wasn't too obvious to be caught by the reviewer. Currently, reviewer uses automated methods to identify private APIs by their names. I recall reading somewhere that, not only aren't you allowed to call them, but also can't you use private API names in Category method names. I imagine because the scanning process is automated, you wouldn't have a shot to pass the review if you did use undocumented methods.
doc_23535786
Really noone at Google thought about Preference Migrations? The only sensible way for now seems to version preferences and mark for removal preferences that changed with a given version..? A: Try to read key with new data type, in case of ClassCastException exception delete "old" key, and create new key with same name but new type. Something like this: SharedPreferences prefs; String key = "key"; prefs = PreferenceManager.getDefaultSharedPreferences(this); if (prefs.contains(key)) { // key exists, so tetermine it's type try { prefs.edit().get<old_type_name>(key, <default_old_type_value>); } catch (Exceprtion e) { if (e instanceOf ClassCastException) { prefs.edit().remove(key).apply(); } } } // we are here if no key exists or key removed prefs.edit().put<new_type_name>(key, <new_type_value>).apply(); and if needed do check if (prefs.contains(key)) ... only once on first app start. A: I did something that works on raw SharedPreferences and does not need a PreferenceFragment: * *introduced settings version. *preferences are stored in xml resources both with dedicated xml strings. *split code to load, migrate, set default settings on application start. *created two string arrays versions and keys - that keep track of preference changes - keys is a comma separated string - with the same index this pair keeps information on given version migration. *check the current version from stored settings and verify against versions stored in string arrays, if its current version is older (lower number) then delete keys provided in a keys string array with the same index (needs string split) and re-create them with default values. This gives me a nice way of settings migration, based purely on strings xml resources and no code changes, also it should migrate step by step all following versions if user did not update the application frequently :-) It is also good to mark recent migration for a user review of recent changes..
doc_23535787
How do I install the certificate? Do I have to install it on my development server or does it matter where I install it? How does the whole process work? I don't want to spend 3-5 hundred dollars on a certificate, and install something wrong and be out of luck. Are there good tutorials on purchasing and installing a certificate and signing a ClickOnce application? A: I recently went through this process. A certificate is not that expensive - we got a code-signing certificate for less than a $100. After you have the certificate, follow the FAQ HOWTO: Code signing how-to* to sign your code (binaries). After that, you have to go to project properties -> Signing and upload your certificate there as well (it's for ClickOnce). You can skip code signing though and sign ClickOnce only. ClickOnce requires a certificate for code signing, and others will not work, see ClickOnce Deployment and Authenticode: For ClickOnce applications, you must have an Authenticode certificate that is valid for code signing; if you attempt to sign a ClickOnce application with another type of certificate, such as a digital e-mail certificate, it will not work. Jan'18 UPDATE: StartSSL is not trusted anymore, and I did NOT find any free (or similar to what StartSSL was offering) code signing certificates. At the end of the day, I went with ksoftware.net - $84/year for Comodo code-signing certificate (but you need to have DUNS record available for them to check!)
doc_23535788
I want to build a website, the service is so simple: It gets a document as input, and tries to replace each word of it with something that it keeps in the database for the word. It also has a forum in which people can vote for the equivalents, and these votes form the basis of the main service. I want to do it in XML way, meaning that in bottom there is an XML native database, and there is an XQuery engine in the middle layer, handling the requests and elections. However, the problem is that although I've read a lot about each of these product, and also implemented some codes, I don't have any clue from where I should start. I mean I don't know what should be displayed to users, and how I can pass the form to the XQuery engine in server side, and how I connect the XQuery to the database. A: You need three components; * *An XML database / xquery processor. *A web server. *A scripting language. Examples * *XML database/processor: You could simply store your XML data as plain text files on disk, in which case you only need an XML processor eg. Saxon-HE. This is absolutely fine for data of less than say 1mb in size. Above 1mb you'll probably need a combined xquery processor and XML database eg. Saxon-PE, eXist DB, BaseX or Qizx. This wiki page lists the major ones. *Web server: You're creating a website so you need a web server, eg. Apache, IIS or Nginx. In this context, the web server accepts an HTTP request from the web browser, then invokes the scripting language engine which in turn invokes the xquery processor. The web server then returns an HTTP response to the browser. *A scripting language to tie everything together eg. PHP, ASP or PERL. I'm currently using this combination; XML Processor: Saxon-HE Web server: Nginx Scripting: PHP In the past I've used; XML DB & processor: BaseX Web server: IIS Scripting: PHP and; XML DB & processor: eXist DB Web server: IIS Scripting: ASP The trickiest bit is working out how to get your chosen scripting language to invoke your chosen xquery processor. A: I think it woild be sooo sloooowww.... (I might be wrong, but I've never heard about any production-ready xml database). Think twice: do you really need all this xml crap? Why not traditional relational database? May be key-value database?
doc_23535789
For now Aws Glue is out because they do not support pushdown predicates. Other option we are thinking is dividing input data into several smaller chunks and each chunk goes to new lambda instance which basically does BatchGetItem. Do you have any advice in which direction to go? A: You could look at using AWS EMR with Apache Hive. By doing this you can load your DynamoDB tables as an external table and then perform normal SQL like syntax to perform queries. A: Your approach of "dividing input data into several smaller chunks and each chunk goes to new lambda instance which basically does BatchGetItem" Can work but you would require fleet of lambdas to process your data. Here one thing you can consider is using pywren which is also suggested by aws team. Pywren manages the fleet of lambda for you and provide you with the results you expected in far less time.. You can go through this here Here is a link to samples provided by aws https://github.com/aws-samples/pywren-workshops
doc_23535790
I am using a cron job to run an import every day at 3am, but I have a question regarding the setup of it all. Would it be good practice to import the feed, create posts based on the feed and then populate the posts on the site? To remove duplicates I would run a DB check for the product ID and skip those that are already created. I am really new to cron and dynamically creating posts so I am not sure if this is the best way to go about it. A: I solved it by adding an AJAX handler to my functions.php, fetch the jobs through a curl request and then looping through the feed inserting new posts to DB and updating already existing posts. //CURL request to fetch feed when getting AJAX call function import_feed() { $url = "http://url-to-jsonfeed.com"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $data = json_decode($response, true); create_posts($data); wp_die(); } add_action('wp_ajax_import_feed', 'import_feed'); //Loop through JSON data and create post function create_posts($jsonfeed) { $data = $jsonfeed['Report']; if (!empty($data) ) { foreach ($data as $entry) { //Set post data before creating post $post_data = array( 'post_title' => $entry['Entry_Title'], 'post_name' => $entry['EntryID'], 'post_status' => 'publish', 'post_author' => 1, 'post_type' => 'entries' ); if (get_page_by_title($post_data['post_title'], 'entries') == null && empty(get_posts(array('post_type' => 'entries', 'name' => $post_data['post_name'])))) { wp_insert_post($post_data, $wp_error); } else if (!empty(get_posts(array('post_type' => 'entries', 'name' => $post_data['post_name'])))) { $post = get_posts(array('post_type' => 'entries', 'name' => $post_data['post_name'])); $post_id = $post[0]->ID; $post_data['ID'] = $post_id; wp_update_post($post_data, $wp_error); } } } }
doc_23535791
** LATER: WRONG JVM: There's another "java" executable in my environment that was being picked up. The OpenJDK. When I forced the "java" executable to run the Sun/Oracle jvm it worked just fine.
doc_23535792
<html lang="en" prefix="content: http://purl.org/rss/1.0/modules/content/ dc: http://purl.org/dc/terms/ foaf: http://xmlns.com/foaf/0.1/ og: http://ogp.me/ns# rdfs: http://www.w3.org/2000/01/rdf-schema# schema: http://schema.org/ sioc: http://rdfs.org/sioc/ns# sioct: http://rdfs.org/sioc/types# skos: http://www.w3.org/2004/02/skos/core# xsd: http://www.w3.org/2001/XMLSchema#"> . . .</html> Doing some research: some say Open Graph, some say RDF vocabulary and some 'Foaf, (Friend of a friend)' image say XML. I'm so confused. A post on Quora said this: RDFa is used to implement the Semantic Web in web pages represented in many markup languages, like HTML and XML. Instead of having a web page telling the browser just how it should be structured, now you can also tell it what the page represents, like a Person, a List of Products, etc. What do we mean by Semantic Web? We all strive to make a webpage completely accessible and 'Semantically' correct, sure. Section tags... Article tags... Can we literally enforce that by this prefix tag? This Museum site isn't a person, a List or a product but it is a place. Why does this museum need to add this prefix tag to the HTML element? Also inspecting... I can see what looks like Schema. Now, this does make sense because of the visibility they wish to gain through search engines. <img src="/src.jpg" typeof="foaf:img"> Then on their Donate page <div about="/support-us/donate" typeoof="schema:WebPage"> ... </div> Who knew you could put URLs there? :-) It seems with a majority of their headings we also have <span property="schema:name">Corporate support</span> Does doing this have any real benefit? And why the very long HTML prefix? Seldom seen on the web nowadays in my opinion. Penny for your thoughts on this? A: What do we mean by Semantic Web? Wikipedia has a good introduction, but essentially it involves adding more machine readable data to the WWW. We all strive to make a webpage completely accessible and 'Semantically' correct, sure. Section tags... Article tags... Can we literally enforce that by this prefix tag? The goal of the semantic web is to go beyond the semantics of HTML. some say Open Graph, some say RDF vocabulary and some 'Foaf, (Friend of a friend)' image say XML. I'm so confused. Open Graph is a means to encode a certain set of additional semantics. FOAF is a means to encode a different set of additional semantics (specifically about how people relate to each other). RDF is a more generic means to encode semantics. FOAF and Open Graph are used with it. XML is a generic markup language that is designed to be used as the foundation of other markup languages. RDF is often expressed using XML. RDFa defines the prefix attribute that you have quoted. foaf: http://xmlns.com/foaf/0.1/ defines a prefix for FOAF data in the document. og: http://ogp.me/ns# defines a prefix for Open Graph data in the document. Attributes then reference it. e.g. <img src="/src.jpg" typeof="foaf:img"> states the element is what FOAF defines as img. Does doing this have any real benefit? I have no data on either: * *Third party tools interacting with the data on webpages (beyond the use of social media using Open Graph for thumbnails et al) *Any internal tools the museum is using on their own data. And why the very long HTML prefix? Because they have data from a lot of namespaces.
doc_23535793
Problem: I have several datasets with time series data. Example: * *Dataset A: [[product1, date1, price], [product1, date2, price]] *Dataset B: [[product2, date1, price], [product2, date2, price]] *Dataset C: [[product3, date1, price], [product3, date2, price]] When describing the columns in Google AutoML you can mark the data as time series data and specify the date column as the time serie. It is very important to keep in mind it is time series data. I'd think combining the datasets wouldn't be a good idea because there will be duplicate dates. Is it possible to train the model on dataset A and after that finishes on dataset B, etc. or would you advice to combine the datasets? Thanks. A: You can combine the data, I don't see how that would matter with what you are describing. Marking a column as a Time column has AutoML Tables split the data based on that column, putting the oldest 80% as the training set, next more recent 10% as the validation set, and the most recent 10% as the test set. If there is not enough data in your set that is distinct in the time column to split the data as 80/10/10 described above, you will want to not mark it as the Time column and instead manually split the data. If the datasets are not related and are distinct from each other, then you would want to train individual models for each.
doc_23535794
I am coding an app in which this error (from the list: listeCmdes) was issuing sometimes. The list gets it’s values from a provider. When it is empty, I display a message: ’Nothing found in the database’. If an element is founded in the list, it is displayed in a Container() widget. In that widget I have 2 other icons: one for deleting the element, another for editing it. The deleting icon works fine. But the edit icon, when cliked, displays the famous error: RangeError (index): Invalid value: Valid value range is empty: 0. I unsuccessfully searched the solution on the net. I tried many things (for example checking if the index of the wanted element is lower than the lenght of the list, if the list is not empty, etc.). Nothing helped. The last thing I did is to create a temporisation before accessing the list’s element : await Future.delayed(Duration(miliseconds: 1)); The error disapeared: no more trouble of this kind on that place! I tried even a value of 0 for the Duration and it was still ok. I can not explain it, because I am new in DART/FLUTTER, so just try the thing if you have the same trouble. IconButton( onPressed: () async { await Future.delayed( Duration(milliseconds: 1)); await Navigator.of(context).push( MaterialPageRoute( builder: (context) => TraitementCmde( cmde2Edit: listeCmdes[idx], bandeExploitee: bandeEnCours), ), ); }, icon: Icon(Icons.edit), color: Colors.blue, ),
doc_23535795
$("#element").on('click', function(){ alert("clicked!"); }); $("#element").on('click', function(){ alert("clicked!"); }); it is well known that the click event will fire twice. because it was bound with the method on() and no unbinding with off() followed. Now my question is why on this page the click event method is registered only once no matter how many times you click the binding button?? <script> function flash() { $( "div" ).show().fadeOut( "slow" ); } $( "#bind" ).click(function() { $( "body" ) .on( "click", "#theone", flash ) .find( "#theone" ) .text( "Can Click!" ); }); $( "#unbind" ).click(function() { $( "body" ) .off( "click", "#theone", flash ) .find( "#theone" ) .text( "Does nothing..." ); }); </script> I thought that is because the on() method was binding to a named function not anonymous function. but I tested it on jsbin here and it failed ? can any one give me a hint of what am I missing here? A: The click method is actually registered and called several times, but each of the several event handlers does the same thing, namely fading out the button. You visually cannot notice the multiple calls, as the multiple "fadings" happen (quasi-)synchronously (are controlled by an internal timer), i.e. jQuery does not wait until the button has completely disappeared before continuing with the program. The second handler is called while the button is still visible. If there are several identical handlers registered, a single call of off() removes them all at once. If you add $("#b").off ('click', doIt) at the end of your own example, you will see that your button does not do anything anymore. $("#b").on('click', doIt); $("#b").on('click', doIt); $("#b").on('click', doIt); $("#b").on('click', doIt); $("#b").off('click', doIt); // removes all event handlers that are equal (===) to doIt // hence now no event handler is registered to #b anymore A: Look at this example: JSFiddle. The same code as in jQuery docs but with small modification: function flash() { $("div").show().fadeOut("slow"); alert('hi'); } It shows how on works - exactly the same way as you've described. Called by click function in the documentation don't show multiple binding. Then off turns off all assigned click handlers.
doc_23535796
public static double ToDouble(string value, IFormatProvider provider); examples: Console.WriteLine(Convert.ToDouble("3223.2", CultureInfo.InvariantCulture)); // success Console.WriteLine(Convert.ToDouble("3223,2", new CultureInfo("fr-FR"))); // success Console.WriteLine(Convert.ToDouble("3223.2", new CultureInfo("fr-FR"))); // failure But what is an example of using following overload? public static int ToInt32(string value, IFormatProvider provider); Everything fails below: Console.WriteLine(Convert.ToInt32("3223.2", CultureInfo.InvariantCulture)); Console.WriteLine(Convert.ToInt32("3223,2", new CultureInfo("fr-FR"))); Console.WriteLine(Convert.ToInt32("3223.2", new CultureInfo("fr-FR"))); In other words are there any valid string representations of integer (in any culture) which can not be converted to int without specifying IFormatProvider? A: When you use the simple version of Convert.ToInt32 you are still using the overload that takes the readonly CultureInfo.CurrentCulture, as you can see if you look at the reference source of Convert.ToInt32 public static int ToInt32(String value) { if (value == null) return 0; return Int32.Parse(value, CultureInfo.CurrentCulture); } The point is, a lot of cultures, custom made or not, could use different characters also for common operations like a conversion and need a proper support structure. Here an example of an odd use of custom CultureInfo that allow a weird conversion of a string to an integer CultureInfo ci = new CultureInfo("it-IT"); ci.NumberFormat.NegativeSign = "@"; int number = Convert.ToInt32("@10", ci); Console.WriteLine(number);
doc_23535797
For example, given a dataset like this: [ [b, w, +, +], [w, +, w, b], [+, w, b, +], [+, +, +, b], ] It would return another Variable containing: [ [-, -, -, -], [-, w, -, -], [-, -, -, b], [-, -, -, -], ] That is, it replaced all the + which were completely surrounded with b with a b, and the same for those surrounded by a w, and replaced everything else with a -. Can anyone give any ideas on how to build a program to do this? A: This might help: it takes the representation you gave, and gives back a list whose elements are each of the form [ColumnIndex, RowIndex, Value]. You can then use member to find an element at a particular row/column. encodearray( A, AA ) :- ( A, 0, 0, AA ). encodearray( [], _, _, [] ). encodearray( [[]|A], _, R, AA ) :- R1 is R+1, encodeArray( A, 0, R1, AA ). encodearray( [[A|B]|X], C, R, [[C,R,A]|AA] ) :- C1 is C+1, encodeArray( [B|X], C1, R, AA ). A: With this rep/2 predicate rep(L0, L1) :- rep(b, L0, L1) ; rep(w, L0, L1). rep(E, [E|Ps], [-|Rs]) :- rep1(E, Ps, Rs). rep(E, [X|Ps], [-|Rs]) :- E \= X, rep(Ps, Rs). rep1(E, [+|Ps], [E|Rs]) :- rep2(E, Ps, Rs). rep2(E, [+|Ps], [E|Rs]) :- rep2(E, Ps, Rs). rep2(E, [E|Ps], [-|Rs]) :- dash(Ps, Rs). dash([], []). dash([_|Ps], [-|Rs]) :- dash(Ps, Rs). that performs this way ?- rep([b,+,b,b],L). L = [-, b, -, -] ; false. ?- rep([b,+,+,+,+,+,b,+,b],L). L = [-, b, b, b, b, b, -, -, -] . ?- rep([w,+,+,+,+,+,w,+,b],L). L = [-, w, w, w, w, w, -, -, -] . ?- rep([b,+,+,+,+,+,w,+,b],L). false. ?- rep([b,+,+,+,+,+,+,b],L). L = [-, b, b, b, b, b, b, -] . ?- rep([b,+,+,+,+,+,+,+,b],L). L = [-, b, b, b, b, b, b, b, -] . ?- rep([b,+,+,w,+,+,w,+,b],L). L = [-, -, -, -, w, w, -, -, -] . and a transposition predicate to enable rep/2 to work on columns transpose_col_row([], []). transpose_col_row([U], B) :- gen(U, B). transpose_col_row([H|T], R) :- transpose_col_row(T, TC), splash(H, TC, R). gen([H|T], [[H]|RT]) :- gen(T,RT). gen([], []). splash([], [], []). splash([H|T], [R|K], [[H|R]|U]) :- splash(T,K,U). you could combine them to solve your problem. HTH
doc_23535798
Umbraco cannot start. A connection string is configured but Umbraco cannot connect to the database. My connection string is <add name="umbracoDbDSN" connectionString="Server=tcp:myserver.database.windows.net,1433;Database=mysitesdb;User ID=me@myserver;Password=myPassword" providerName="System.Data.SqlClient" /> What's gone wrong? I've tried encasing the password in single quotes as that seemed to help once before when I had connection string problems, but it doesn't help this time. Any ideas? EDIT: It's weird but overnight the problem has gone away. The site is now up. I didn't change anything. Bit of a mystery. Maybe there is some kind of time lag betweeen a database being created and it being accessible from the web app? A: When you restore an Azure SQL Database it's creating a new database. It doesn't have the firewall rules in place. Check that first. A: Please verify the login and password used in the connection string are correct. Use the Admin login provided when you created the Azure SQL Database logical server. Go to the Azure Portal and verify the name of the database is mysitesdb. A: Long shot but... There was a bug in Umbraco a while ago, that if you have a password with certain symbols in it it fails to parse your password correctly... from memory I think it was a combination of / and & that failed... Do you have any of this characters in your password? maybe rest your password to something with no symbols and try again.
doc_23535799
It is a simple function (from functions.php) that reads additional information about productions from the database. However, I do not know if there is such a hook? A: To add a text on selecting a variation you can use the following: add_filter('woocommerce_available_variation', 'variation_custom_text', 10, 3 ); function variation_custom_text( $variation_data, $product, $variation ) { // Here your custom text $custom_text = __("This is my custom text…", "woocommerce"); $variation_data['availability_html'] .= '<p>' . $custom_text . '</p>'; return $variation_data; } Code goes in function.php file of the active child theme (or active theme). Tested and works.