input
stringlengths
51
42.3k
output
stringlengths
18
55k
Can I override the value returned by require() in webpack? <p>For testing purposes, I want to use <code>require('whatever.js')</code> to return an arbitrary content rather than having it actually load the file.</p> <pre><code>// made up code var AAA = {}; require.setFor('./whatever.js', AAA); var BBB = require('./whatever.js'); console.assert(AAA === BBB); </code></pre> <p>Is this possible?</p>
<p>Simply overwrite the <code>require</code> function:</p> <pre><code>var realRequire = require; require = function (what) { return realRequire('mocked-' + what); } </code></pre> <p>You could use a lookup table for your mocks as well and call <code>realRequire()</code> if no mock exists.</p>
Rails 5: Why is javascript executing twice? <p>I am in the process of learning Rails, and am struggling with best practices with respect to page-specific javascript. Even with this simple approach, turbolinks (I believe) is causing javascript to execute twice if I visit a page and then return to it.</p> <p>To simplify the scenario I created a new project with two controller actions, and started a server.</p> <pre><code>rails new jstest cd jstest rails g controller home index index2 rails server </code></pre> <p>Now I updated the views to the following:</p> <p>index.html.erb:</p> <pre><code>&lt;%= link_to "Index2", home_index2_path %&gt; &lt;script&gt; console.log("hi from index!"); &lt;/script&gt; </code></pre> <p>index2.html.erb:</p> <pre><code>&lt;%= link_to "Index", home_index_path %&gt; &lt;script&gt; console.log("hi from index2!"); &lt;/script&gt; </code></pre> <p>By navigating to /home/index, following the link to index2, then the link back to index I would expect to see:</p> <pre><code>hi from index! hi from index2! hi from index! </code></pre> <p>But instead, I get the third message twice:</p> <pre><code>hi from index! hi from index2! hi from index! hi from index! </code></pre> <p>Why is it that my javascript executes twice on the second visit to index, and is there a better way to setup page specific javascript to avoid executing it twice?</p> <p>Thank you for your help.</p>
<p>This was caused by turbolinks displaying a preview when revisiting the page. My understanding is that turbolinks briefly displays a preview, to improve perceived load times, then replaces it. In my example Javascript is executed both when the preview is displayed, and again when it is replaced.</p> <p>In my scenario executing javascript twice was not causing any ill side effects, but if it were it could be stopped by disabling the preview with the following, per their <a href="https://github.com/turbolinks/turbolinks#opting-out-of-caching" rel="nofollow">documentation</a>:</p> <pre><code>&lt;head&gt; ... &lt;meta name="turbolinks-cache-control" content="no-preview"&gt; &lt;/head&gt; </code></pre>
How would one print out a created ascii display multiple times side by side? <p>For example, if I had created a shape:</p> <pre><code>iiiiiiiii i i i i iiiiiiiii </code></pre> <p>and wanted to print that five times side by side, how would I do that? A for loop?</p> <p>I've already tried just manually printing another one over some spaces, but that confused me and didn't quite work the way I wanted.</p>
<p>I had noticed that you had asked this with the "C++ Tag" So here it goes, I also assume this would be for a Console application, I had also attempted this with Visual Studio I have no clue what you're using but this is how I did it!</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { cout &lt;&lt; "iiiiiiiii iiiiiiiii iiiiiiiii iiiiiiiii iiiiiiiii" &lt;&lt; endl; cout &lt;&lt; "i i i i i i i i i i" &lt;&lt; endl; cout &lt;&lt; "i i i i i i i i i i" &lt;&lt; endl; cout &lt;&lt; "iiiiiiiii iiiiiiiii iiiiiiiii iiiiiiiii iiiiiiiii" &lt;&lt; endl; cout &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; "HH HH IIIIIIII" &lt;&lt; endl; cout &lt;&lt; "HH HH III " &lt;&lt; endl; cout &lt;&lt; "HH HH III " &lt;&lt; endl; cout &lt;&lt; " HHHHHHHH III " &lt;&lt; endl; cout &lt;&lt; "HH HH III " &lt;&lt; endl; cout &lt;&lt; "HH HH III " &lt;&lt; endl; cout &lt;&lt; "HH HH IIIIIIII" &lt;&lt; endl; cout &lt;&lt; endl; return 0; } </code></pre> <p>I personally had used spaces as I had noticed that using "TAB" has clearly messed up the spacing of the Console Output, : <a href="https://i.stack.imgur.com/tVwf5.png" rel="nofollow">Example</a> , So basically what you see is what you should do.. just line everything up and use spaces and if you end up using a " \ " make sure you have two of them such as this " \\" because when the code compiles it will only show one of them but basically you just need to line everything up and have it in the most organized way I don't know how else I could explain this to you</p>
histogram and scatter plot on the same graph but the axis overlapped <p>I am plotting a histogram of actual data along with a density plot on the same graph but the x axis and y axis all mixed up. Is there a way to make sure the graph has the same axis e.g set a range to the graph for both the plot.</p> <p>The reason that I put histogram and density plot together is for comparisons. The data range for both plots are similar but they alway produce two labels on the same axis making it unreadable.</p> <pre><code>a &lt;- rnorm(100, 3, 7) x &lt;- c(0:200) plot(0.5 * dpois(x, 4) + ((1 - 0.5) * dpois(x, 2))) lines(0.5 * dpois(x, 4) + ((1 - 0.5) * dpois(x, 2))) par(new = TRUE) hist(a) </code></pre>
<p>Since nobody answers my question. I have figured it out.</p> <p>set the same <code>xlim</code> and <code>ylim</code> to <strong>both</strong> graph which makes aligned the x,y axes.</p>
Where is copy constructor getting called? <p>I wrote a small snippet of C++ code in a main.cpp file and am trying to understand how it's working.</p> <p>First I defined a class "Value":</p> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; using namespace std; class Value { int v; public: Value(int v): v(v) { cout &lt;&lt; "Ctor called" &lt;&lt; endl; } Value(const Value &amp;rhs): v(rhs.v) { cout &lt;&lt; "Copy Ctor called. V = " &lt;&lt; v &lt;&lt; endl; } Value&amp; operator =(const Value &amp;rhs) { cout &lt;&lt; "Assignment called" &lt;&lt; endl; if (this != &amp;rhs) { auto tmp = Value(rhs); swap(v, tmp.v); } return *this; } int rawValue() const { return v; } }; </code></pre> <p>Then I executed main:</p> <pre><code>Value doubleValue(const Value &amp;v) { auto newValue = Value(v.rawValue() * 2); return newValue; } int main() { cout &lt;&lt; "Creating v = 10" &lt;&lt; endl; auto v = Value(10); cout &lt;&lt; "Creating v = 20" &lt;&lt; endl; auto v2 = doubleValue(v); return 0; } </code></pre> <p>I'm using g++ as my compiler and when I run the following code:</p> <pre><code>g++ --std=c++11 -fno-elide-constructors -c main.cpp g++ main.o -o main.exe ./main.exe </code></pre> <p>Which prints the following: </p> <pre><code>Creating v = 10 Ctor called Creating v = 20 Ctor called </code></pre> <p>I compile the code again, but without the copy constructors getting optimized out:</p> <pre><code>g++ --std=c++11 -fno-elide-constructors -c main.cpp g++ main.o -o main.exe ./main.exe </code></pre> <p>And now, it print the following:</p> <pre><code>Creating v = 10 Ctor called Copy Ctor called. V = 10 Creating v = 20 Ctor called Copy Ctor called. V = 20 Copy Ctor called. V = 20 Copy Ctor called. V = 20 </code></pre> <p>Not sure why it's calling the copy constructor so many times. I'm a C++ noob and would like to understand the flow much better. I'm curious to know how this code is running and why the copy constructor is getting called so often.</p>
<p>Here are the copies:</p> <ul> <li><code>auto v = Value(10);</code> initializes <code>v</code> using copy-constructor from <code>Value(10)</code>.</li> <li><code>auto newValue = Value(v.rawValue() * 2);</code> initializes <code>newValue</code> using copy-constructor from <code>Value(v.rawValue()*2)</code>.</li> <li><code>return newValue;</code> initializes the <em>return value</em> using copy-constructor from <code>newValue</code>.</li> <li><code>auto v2 = doubleValue(v);</code> initializes <code>v2</code> using copy-constructor from the <em>return value</em>.</li> </ul> <p>All of these are copy-elision contexts.</p>
Unable to insert data into mysql in node <p>Trying to insert data into mysql with <code>'INSERT INTO users SET ?'</code>, I get 500 error in front end. data is reaching the server but unable to insert into database. Tried even <code>'INSERT INTO users VALUES ?'</code> but still fails. i'm able to retrieve the data from the database('SELECT * FROM users') but not inserting it. </p> <pre><code>router.post('/userstuff', function(req, res, next) { var eachuser = { name: req.body.name, age: req.body.age }; connection.query('INSERT INTO users SET ?',eachuser, function(err, rows){ if(err) console.log('Error selecting: %s ', err); console.log(rows) }); }); </code></pre> <p>edit: added the schema:</p> <pre><code> use 02sqldb; CREATE TABLE IF NOT EXISTS users ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(30), age int(2) ); </code></pre>
<p>And what if you try to first do a dummy query. I don't know for sure you can simply put "?" to insert a value without giving a column like </p> <pre><code>'INSERT INTO table_name (column1,column2,column3,...) VALUES ('?','?','?',...)' </code></pre> <p>If it still isn't working you know it's something else.</p>
SQlite.Net.SQliteCommand ExecuteQuery requires calss <p>I am working on SQlite with Windows Universal App. I have a scenario where the column names are unknown and want to fetch the data from Sqlite table. The method ExecuteQuery in SQlite.Net.SQlite.SQlCommand expects a class name to be passed. I tried with dictionary but no luck it comes as a empty. Anything related this would be helpful. I cant find much document online.</p> <pre><code>SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), sqlpath); SQLiteCommand cmd = conn.CreateCommand(query); List&lt;Dictionary&lt;string, string&gt;&gt; datalist =cmd.ExecuteQuery&lt;Dictionary&lt;string, string&gt;&gt;(); </code></pre>
<p>What you need is actually map it to a list of dynamic objects with SQLite in UWP app, I'm sorry to tell you that SQLite for UWP doesn't support this function.</p> <p>And <a href="https://github.com/StackExchange/dapper-dot-net" rel="nofollow">Dapper.Net</a> is now not available for UWP apps. </p> <p>You can try to use web API/service to solve your problem, for example you can submit your data to the web API, web API uses dapper to get data from your database and pass it back to your app.</p>
How can i consume this webservice with Java? <p>this is a very simple question apparently but i was unavaible to find a certain information searching in google. Let me tell you, i have a jboss running in my computer with only this webservice:</p> <pre><code>import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.springframework.stereotype.Controller; @Controller @Path("/services/test") public class TestController { @POST @Path("/reg") @Consumes(MediaType.APPLICATION_JSON) @Produces({ MediaType.APPLICATION_JSON }) public Response checkMock(String paramx) { return Response.ok("Paramx: " + paramx,MediaType.APPLICATION_JSON).build(); } } </code></pre> <p>Ok, to test it i use "Advance REST Client" chrome plugin and it is very simple, look this picture:</p> <p><a href="https://i.stack.imgur.com/rFB3K.png" rel="nofollow"><img src="https://i.stack.imgur.com/rFB3K.png" alt="enter image description here"></a></p> <p>Well the question is, how can i do the same but with some java code in another program? What objecto do i require?</p> <p>Best regards!</p>
<p>Use <a href="https://spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate" rel="nofollow">Spring RestTemplate</a> to consume a Rest service. </p> <p>You need to first register the <code>RestTesmplate</code> into spring context</p> <pre><code>&lt;bean class="org.springframework.web.client.RestTemplate" id="restTemplate"&gt; &lt;constructor-arg&gt; &lt;bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory"/&gt; &lt;/constructor-arg&gt; &lt;/bean&gt; </code></pre> <p>Once you registered your resttemplete in spring context you can inject that in your service class and call the exchange method</p> <pre><code>HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity&lt;?&gt; httpEntity = new HttpEntity&lt;Object&gt;(payLoad, headers); ResponseEntity&lt;ResponseObject&gt; response = restTemplate.exchange(ENDPOINT, HttpMethod.POST, httpEntity, ResponseObject.class); ResponseObject resObj = response.getBody(); </code></pre> <p>Here <code>payLoad</code> is your request object and <code>ResponseObject</code></p> <p>To unmarshall the response directly into to response object you need to register the message converters </p> <pre><code>List&lt;HttpMessageConverter&lt;?&gt;&gt; messageConverters = new ArrayList&lt;HttpMessageConverter&lt;?&gt;&gt;(); Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setClassesToBeBound(ResponseObject.class); MarshallingHttpMessageConverter marshallingHttpMessageConverter = new MarshallingHttpMessageConverter(marshaller, marshaller); marshallingHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.TEXT_HTML)); messageConverters.add(marshallingHttpMessageConverter); restTemplate.setMessageConverters(messageConverters); </code></pre>
Element Tree find output empty text <p>I have a problem using Element Tree to extract the text.</p> <p>My format of my xml file is</p> <pre><code>&lt;elecs id = 'elecs'&gt; &lt;elec id = "CLM-0001" num = "0001"&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;/elec&gt; &lt;elec id = "CLM-0002" num = "0002"&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;/elec&gt; &lt;/elecs&gt; </code></pre> <p>I want to extract out all the text inside the tag </p> <p>Assume that our xml file is in the variable xml</p> <pre><code>import xml.etree.ElementTree as ET import lxml import etree parser = etree.XMLParser(recover = True) contents = open(xml).read() tree = ET.fromstring(contents, parser = parser) elecsN = tree.find('elecs') for element in elecsN: print element.text </code></pre> <p>The problem is, the code above returns empty strings. I have tried my code above with other tags in my document and it works. I do not know why it returns empty string this time.</p> <p>Is there anyway i can solve this problem.</p> <p>Thank you very much</p>
<p>You can simply find elements that directly contains the text by name i.e <code>elec-text</code> in this case :</p> <pre><code>&gt;&gt;&gt; elec_texts = tree.findall('.//elec-text') &gt;&gt;&gt; for elec_text in elec_texts: ... print elec_text.text ... blah blah blah blah blah blah blah blah blah blah blah blah </code></pre>
selecting properties from other table with Lambda expression <p>I am less experienced with Lambda expression for .NET and trying to get data from SQL using lambda expression. With below query, I am able to get data back, but do not want to use <code>include</code> to get all properties from other tables. </p> <pre><code>public IEnumerable&lt;ResourceGroup&gt; GetAllServersByApplication(string application_name, string environment_name, string status) { var query = _context.ResourceGroup .Include(a =&gt; a.Application) .Include(t =&gt; t.Type) .Include(e =&gt; e.ServersGroup).ThenInclude(e =&gt; e.Environment) .Include(s =&gt; s.ServersGroup).ThenInclude(s =&gt; s.Server) .Include(s =&gt; s.ServersGroup).ThenInclude(s =&gt; s.Server).ThenInclude(s =&gt; s.Status) .Where(a =&gt; a.Application.Name == application_name &amp;&amp; a.ServersGroup.Any(s =&gt; s.Environment.Name == environment_name &amp;&amp; s.Server.Status.Name == status)) .ToList(); return query; } </code></pre> <p>Lets take an example of below include statement.</p> <pre><code>.Include(s =&gt; s.ServersGroup).ThenInclude(s =&gt; s.Server) </code></pre> <p>From <code>s.Server</code>, I only want to select <code>Id,ServerName,Status, and IPAddress</code>. These are the properties from <code>Servers</code> class that I created as a model.</p> <p>What is the easy way to exclude all the includes and only show properties that I am interested in?</p> <p><strong>Here are my tables and its properties:</strong></p> <p><strong>Status</strong> table:</p> <pre><code>Id, Name </code></pre> <p><strong>Application</strong> table:</p> <pre><code>Id, Name </code></pre> <p><strong>Servers</strong> table:</p> <pre><code>Id, ServerName, Status </code></pre> <p><strong>Environments</strong> table:</p> <pre><code>Id, Name </code></pre> <p><strong>ResourceGroup</strong> table:</p> <pre><code>Id, Name, Application_Id, Environment_Id </code></pre> <p><strong>ServersResourceGroup</strong> table:</p> <pre><code>Id, Server_Id, Resource_Id </code></pre> <p><strong>UPDATE 1</strong>:</p> <pre><code>var query = _context.ResourceGroup .SelectMany(rg =&gt; rg.ServersGroup .Select(sg =&gt; new { ResourceName = rg.Name, ApplicationName = rg.Application.Name, ServerName = sg.Server.ServerName, EnvironmentName = sg.Environment.Name, Status = sg.Server.Status.Name })).Where(a =&gt; a.ApplicationName == application_name &amp;&amp; a.EnvironmentName == environment_name &amp;&amp; a.Status == status).ToList(); return query; </code></pre> <p>And error from red line on <code>query</code> variable: <a href="https://i.stack.imgur.com/909pB.png" rel="nofollow"><img src="https://i.stack.imgur.com/909pB.png" alt="enter image description here"></a></p> <p><strong>UPDATE 2</strong>:</p> <p>Here is the query syntax:</p> <pre><code>var query = from rg in _context.ResourceGroup let app = rg.Application from sg in rg.ServersGroup let env = sg.Environment let srv = sg.Server let stat = srv.Status where app.Name == application_name &amp;&amp; rg.ServersGroup.Any(s =&gt; s.Environment.Name == environment_name &amp;&amp; s.Server.Status.Name == status) select new { ResourceGroupName = rg.Name, ApplicationName = app.Name, ServerName = srv.ServerName, Alias = srv.Alias, IPAddress = srv.IPAddress, Type = rg.Type.Name, Status = stat.Name }; return query; </code></pre> <p>Here is the red line error I get in query variable:</p> <p><a href="https://i.stack.imgur.com/MEf9j.png" rel="nofollow"><img src="https://i.stack.imgur.com/MEf9j.png" alt="enter image description here"></a></p> <p>Your help is really appreciated. :)</p> <p>Thanks,</p> <p>Ray</p>
<p>With lambda expressions, you can use <code>SelectMany</code> to flatten 1-n associations into a 1 dimensional list (i.e. parent and child properties side-by-side). In your case, judging from the <code>Where</code> clause, I think only <code>ResourceGroup</code> - <code>ServerGroup</code> is 1 - n, so it should be something like:</p> <pre><code>var query = _context.ResourceGroup .SelectMany ( rg =&gt; rg.ServersGroup .Select(sg =&gt; new { ResourceGroup = rg.Name, Application = rg.Application.Name, Server = sg.Server.ServerName, // etc. }) ) </code></pre> <p>Of course it's good to know how to use lambda expressions, but there's really no point in using them when query syntax makes for much better comprehensible code.</p> <p>The equivalent in query syntax is:</p> <pre><code>var query = from rg in _context.ResourceGroup let app = rg.Application from sg in rg.ServersGroup let env = sg.Environment let srv = sg.Server let stat = srv.Status where app.Name == application_name &amp;&amp; sg.ServersGroup.Any(s =&gt; s.Environment.Name == environment_name &amp;&amp; s.Server.Status.Name == status) select new { ResourceGroup = rg.Name, Application = app.Name, Server = srv.ServerName, // etc. use any property from rg, app, sg, srv, stat }; </code></pre> <p>As you see -</p> <ul> <li>n - 1 associations are represented by a <code>let</code> statement (which really only helps here to shorten the references in the <code>select</code>)</li> <li>1-n associations are represented by the <code>from ... from</code> syntax, which is query syntax for <code>SelectMany</code>.</li> </ul> <p>I didn't change the <code>Where</code> clause in the query syntax. <em>Maybe</em> you can use ...</p> <pre><code> where app.Name == application_name &amp;&amp; env.Name == environment_name &amp;&amp; stat.Name == status) </code></pre> <p>... but note that this is different. The original <code>where</code> returns all <code>ResourceGroup</code> having <em>at least</em> one <code>ServerGroup</code> meeting the condition (and maybe other groups with different environments and statuses). The other <code>where</code> only returns data with environments and statuses equal to the search parameters.</p>
How move a rectangle with arrow keys while clearing the canvas in between every re-draw <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;style&gt; canvas { border: 1px solid black; width: 1200px; height: 600px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;script&gt; var z = document.createElement("CANVAS"); var ctx = z.getContext("2d"); var x = 20; var y = 20; ctx.fillRect(x, y, 5, 5); ctx.stroke(); document.body.appendChild(z); document.onkeydown = checkKey; function checkKey(e) { e = e || window.event; if (e.keyCode == '38') { y--; ctx.fillRect(x, y, 5, 5); } else if (e.keyCode == '40') { // down arrow ctx.fillRect(x, y, 5, 5); } else if (e.keyCode == '37') { // left arrow x--; ctx.fillRect(x, y, 5, 5); } else if (e.keyCode == '39') { // right arrow x++; ctx.fillRect(x, y, 5, 5); } } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Every time I try to clear the canvas with: ctx.clearRect(0, 0, 1200, 600); or ctx.clearCanvas(); nothing happens. The rectangle doesnt even move. I put this between the x++; and the ctx.fillRect();. Thanks.</p>
<p>This is the corrected code:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width"&gt; &lt;title&gt;JS Bin&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;style&gt; canvas { border: 1px solid black; width: 1200px; height: 600px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;script&gt; var z = document.createElement("CANVAS"); var ctx = z.getContext("2d"); var x = 20; var y = 20; ctx.fillRect(x, y, 5, 5); ctx.stroke(); document.body.appendChild(z); document.onkeydown = checkKey; function clear() { ctx.clearRect(0, 0, z.width, z.height); } function checkKey(e) { e.preventDefault(); e = e || window.event; if (e.keyCode == '38') { y--; clear(); ctx.fillRect(x, y, 5, 5); } if (e.keyCode == '40') { // down arrow y++;clear(); ctx.fillRect(x, y, 5, 5); } if (e.keyCode == '37') { // left arrow clear(); x--; ctx.fillRect(x, y, 5, 5); } if (e.keyCode == '39') { // right arrow clear(); x++; ctx.fillRect(x, y, 5, 5); } } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>To clear the whole canvas, you need this:</p> <pre><code>ctx.clearRect(0, 0, z.width, z.height); </code></pre> <p>You put it between the <code>x++</code> and <code>ctx.fillRect()</code>.</p> <p>I also see another error in your code:</p> <blockquote> <p>When you handle the down arrow key event, you don't use <code>y++</code> so the rectangle don't move down. I corrected this for you.<br> Error 2: You don't use <code>e.preventDefault</code> so every time I move the rectangle, the window scroll too (if it is too small).</p> </blockquote>
500 error while deploying asp.net core web api to IIS 7.5 <p>I have a asp.net core web api project which I am trying to host in IIS 7.5.</p> <p>As suggested by below article,</p> <p><a href="http://stackoverflow.com/questions/39157781/the-configuration-file-appsettings-json-was-not-found-and-is-not-optional">The configuration file &#39;appsettings.json&#39; was not found and is not optional</a></p> <p>Below is my "appsettings.json" file,</p> <pre><code>{ "ConnectionStrings": { "SchedulerConnection": "Server=ABC\\SQL2012;Database=SchedulerDb;persist security info=True;Integrated Security=SSPI;" } } </code></pre> <p>And in "startup.cs" I am getting connection string value like below,</p> <pre><code>public void ConfigureServices(IServiceCollection services) { services.AddDbContext&lt;SchedulerContext&gt;(options =&gt; options.UseSqlServer(Configuration.GetConnectionString("SchedulerConnection"), b =&gt; b.MigrationsAssembly("WebTest.API"))); } </code></pre> <p>The code running file in local IISExpress, but throw 500 Server Error while deploying to IIS 7.5.</p> <p><strong>What is wrong here?</strong> please suggest!!</p> <p>Below is my "publishOptions",</p> <pre><code>"publishOptions": { "include": [ "wwwroot", "appsettings.json", "web.config" ] }, </code></pre>
<p>Create a new login "IIS APPPOOL[App Pool Name]" for SQL Server and later assign website/IIS application to "IIS APPPOOL[App Pool Name]" works for me.</p> <p>Thanks,</p>
dropbox says "no preview available" when loading Xcode ipa ad hoc file <p>Yesterday, I was able to load ad hoc build ipa files created in Xcode using dropbox. Today, the file appears to load (progress bar moves to the right) but dropbox finishes with the message "preview not available". I'm afraid I modified a project setting, but I do not know which one.</p>
<p>You can for sure be calm, you have probably not modified and destroyed anything in your project. .ipa files is not supported by Dropbox preview. If you´re not sure how to upload your ipa file to Dropbox, take a look at <a href="https://appsandhacksblog.wordpress.com/2015/05/17/ad-hoc-distribution-over-dropbox/" rel="nofollow">this</a> guide.</p>
Handling impure DOM manipulation after redux state change <p>I have an interface that is a list of <code>&lt;input&gt;</code>s. Pressing enter in one of the inputs should move focus to the next input, and if you're already on the last input, another one should be added and that one focused. The list of items is managed by redux.</p> <p>Here's the code to do the pure part of this, without the focusing:</p> <pre><code>class ListItem extends Component { render() { return ( &lt;li&gt; &lt;input defaultValue={this.props.value} onKeyUp={this.onKeyUp.bind(this)} ref={(input) =&gt; this.input = input} /&gt; &lt;/li&gt; ); } onKeyUp(event) { this.props.onChange(event.target.value, event.keyCode === 13); } focus() { this.input.focus(); } } class List extends Component { render() { return ( &lt;ul&gt; {this.props.items.map((item, i) =&gt; &lt;ListItem key={i} value={item} onChange={(value, enterPressed) =&gt; this.onChange(i, value, enterPressed)} /&gt; )} &lt;/ul&gt; ); } onChange(i, value, enterPressed) { this.props.dispatch({ type: 'UPDATE_ITEM', index: i, value: value }); if (enterPressed &amp;&amp; i === this.props.items.length - 1) { this.props.dispatch({ type: 'ADD_ITEM' }); } } } </code></pre> <p>This seems really tricky, because the next list element might not exist yet when we want to focus it, so we somehow need to wait until the redux state change happens, and the list rerenders with the last item.</p> <p>The only way I can think of to do this is to store an array of refs to each of the list items, then when enter is pressed dispatch the redux event and set the index of the focused list item in component state. Then, in componentDidUpdate (which will get called after the redux state gets updated and the extra input is in the DOM), check state to see which input we should focus, and call the focus method on it.</p> <pre><code>class List extends React.Component { constructor(props) { super(props); this.inputs = []; } render() { return ( &lt;ul&gt; {this.props.items.map((item, i) =&gt; &lt;ListItem key={i} value={item} onChange={(value, enterPressed) =&gt; this.onChange(i, value, enterPressed)} ref={(input) =&gt; this.inputs[i] = input} /&gt; )} &lt;/ul&gt; ); } onChange(i, value, enterPressed) { this.props.dispatch({ type: 'UPDATE_ITEM', index: i, value: value }); if (enterPressed) { this.setState({ inputToFocus: i + 1 }) if (i === this.props.items.length - 1) { this.props.dispatch({ type: 'ADD_ITEM' }); } } } componentDidUpdate() { if (typeof this.state.inputToFocus === 'number') { this.inputs[this.state.inputToFocus].focus(); this.setState({ inputToFocus: null }); } } </code></pre> <p>This feels really fragile and ugly. Is there a better way to do it?</p> <p>The full example is at <a href="https://jsfiddle.net/69z2wepo/59903/" rel="nofollow">https://jsfiddle.net/69z2wepo/59903/</a>.</p>
<p>Rather than focusing programatically and using <code>state</code> in your List like you are doing above, you should pass a prop to the ListItem, and the list item themselves can focus themselves if the prop is true. So you could change your actions slightly as well to include the isFocused or not flag, for example:</p> <pre><code>{ type: 'ADD_ITEM' isFocused: true } { type: 'UPDATE_ITEM', index: i, value: value, isFocused: false/true } </code></pre> <p>It might seem more work, but using props rather than state will make it easier to test and reason about.</p>
Is Parasitic Combination Inheritance really used anymore? <p>I am new to JavaScript. I'm reading the section on "Parasitic Combination Inheritance" in the <em>Professional Javascript for Web Developers</em> 3rd Edition in Chapter 6. With the introduction of <strong>ES6</strong> and a strong push to move away from "new" and deep hierarchies, is there a purpose to use the Parasitic Combination Inheritance pattern anymore?</p> <p>What is used today? I feel like I am learning a bunch of patterns that are useless. I know people just use <code>Object.create()</code> and <code>Object.assign()</code> these days, so why even mention these inheritance patterns?</p>
<p>The most "right" method I know of to do inheritance in Javascript is this:</p> <pre><code>let SubClass = function() { SuperClass.call(this, arguments); /*Do other stuff here*/ } SubClass.prototype = Object.create(SuperClass.prototype); </code></pre> <p><code>Object.create(o)</code> is about the same as <code>{__proto__: o}</code> will will create another object with <code>o</code> as its prototype.</p> <p>However since the world has changed we are live in the ES6 realm now, you would rather use the ES6 standard way of doing inheritance:</p> <pre><code>class SubClass extends SuperClass { constructor() { super(...arguments); /*Do other stuff here*/ } } </code></pre> <p>These are the most widely used methods today, stick with whatever fits with you.</p> <p>Hope this helps.</p>
Searching binary tree of objects for a single class member <p>So I'm working on a program that will use a binary tree template class I've created to hold a set of EmployeeInfo objects which is another class I've created. The EmployeeInfo class has two data members, one to hold the employee's ID number and one to hold the employees name. In the main program, I create the binary tree of 5 employeeinfo objects and I'm now trying to figure out how to search the binary tree for JUST an employee ID number and if the number is there, I must print the number along with the name associated with the number onto the screen. This is where I'm running into trouble. My search function returns a bool, so I'm unsure on how to get it to display the name associated with the ID number if it is found. </p> <p><strong>Here is my Binary Tree template class:</strong></p> <pre><code>// Specification file for the BinaryTree Class #ifndef BINARYTREE_H #define BINARYTREE_H #include &lt;iostream&gt; using namespace std; // BinaryTree template template &lt;class T&gt; class BinaryTree { private: struct TreeNode { T value; TreeNode *left; TreeNode *right; }; TreeNode *root; // Private functions void insert(TreeNode *&amp;, TreeNode *&amp;); void destroySubTree(TreeNode *); void deleteNode(T, TreeNode *&amp;); void makeDeletion(TreeNode *&amp;); void displayInOrder(TreeNode *) const; void displayPreOrder(TreeNode *) const; void displayPostOrder(TreeNode *) const; int findHeight(TreeNode *root); int count1(TreeNode *); int countLeft(TreeNode *); public: // Constructor BinaryTree() { root = nullptr; } // Destructor ~BinaryTree() { destroySubTree(root); } // Binary Tree Operations void insertNode(T); bool searchNode(T); void remove(T); int displayCount() { return count1(root); } int displayLeftCount() { return countLeft(root); } int displayHeight() { return findHeight(root); } void displayInOrder() const { displayInOrder(root); } void displayPreOrder() const { displayPreOrder(root); } void displayPostOrder() const { displayPreOrder(root); } }; template &lt;class T&gt; void BinaryTree&lt;T&gt;::insert(TreeNode *&amp;root, TreeNode *&amp;newNode) { if (root == nullptr) root = newNode; else if (newNode-&gt;value &lt; root-&gt;value) insert(root-&gt;left, newNode); else insert(root-&gt;right, newNode); } template &lt;class T&gt; void BinaryTree&lt;T&gt;::insertNode(T item) { TreeNode *newNode = nullptr; newNode = new TreeNode; newNode-&gt;value = item; newNode-&gt;left = newNode-&gt;right = nullptr; insert(root, newNode); } template &lt;class T&gt; void BinaryTree&lt;T&gt;::destroySubTree(TreeNode *nodePtr) { if (nodePtr) { if (nodePtr-&gt;left) destroySubTree(nodePtr-&gt;left); if (nodePtr-&gt;right) destroySubTree(nodePtr-&gt;right); delete nodePtr; } } template &lt;class T&gt; bool BinaryTree&lt;T&gt;::searchNode(T item) { TreeNode *nodePtr = root; while (nodePtr) { if (nodePtr-&gt;value == item) return true; else if (item &lt; nodePtr-&gt;value) nodePtr = nodePtr-&gt;left; else nodePtr = nodePtr-&gt;right; } return false; } template &lt;class T&gt; void BinaryTree&lt;T&gt;::remove(T item) { deleteNode(item, root); } template &lt;class T&gt; void BinaryTree&lt;T&gt;::deleteNode(T item, TreeNode *&amp;nodePtr) { if (item &lt; nodePtr-&gt;value) deleteNode(item, nodePtr-&gt;left); else if (item &gt; nodePtr-&gt;value) deleteNode(item, nodePtr-&gt;right); else makeDeleteion(nodePtr); } template &lt;class T&gt; void BinaryTree&lt;T&gt;::makeDeletion(TreeNode *&amp;nodePtr) { TreeNode *tempNodePtr = nullptr; if (nodePtr == nullptr) cout &lt;&lt; "Cannot delete empty node." &lt;&lt; endl; else if (nodePtr-&gt;right == nullptr) { tempNodePtr = nodePtr; nodePtr = nodePtr-&gt;left; delete tempNodePtr; } else if (nodePtr-&gt;left == nullptr) { tempNodePtr = nodePtr; nodePtr = nodePtr-&gt;right; delete tempNodePtr; } else { tempNodePtr = nodePtr-&gt;right; while (tempNodePtr-&gt;left) tempNodePtr = tempNodePtr-&gt;left; tempNodePtr-&gt;left = nodePtr-&gt;left; tempNodePtr = nodePtr; nodePtr = nodePtr-&gt;right; delete tempNodePtr; } } template &lt;class T&gt; void BinaryTree&lt;T&gt;::displayInOrder(TreeNode *nodePtr) const { if (nodePtr) { displayInOrder(nodePtr-&gt;left); cout &lt;&lt; nodePtr-&gt;value &lt;&lt; endl; displayInOrder(nodePtr-&gt;right); } } template &lt;class T&gt; void BinaryTree&lt;T&gt;::displayPreOrder(TreeNode *nodePtr) const { if (nodePtr) { cout &lt;&lt; nodePtr-&gt;value &lt;&lt; endl; displayPreOrder(nodePtr-&gt;left); displayPreOrder(nodePtr-&gt;right); } } template &lt;class T&gt; void BinaryTree&lt;T&gt;::displayPostOrder(TreeNode *nodePtr) const { if (nodePtr) { displayPostOrder(nodePtr-&gt;left); displayPostOrder(nodePtr-&gt;right); cout &lt;&lt; nodePtr-&gt;value &lt;&lt; endl; } } template &lt;class T&gt; int BinaryTree&lt;T&gt;::count1(TreeNode *root) { int count = 1; if (root-&gt;left != nullptr) { count += count1(root-&gt;left); } if (root-&gt;right != nullptr) { count += count1(root-&gt;right); } return count; } template &lt;class T&gt; int BinaryTree&lt;T&gt;::countLeft(TreeNode *root) { int count = 1; if (root-&gt;left != nullptr) count += countLeft(root-&gt;left); return count; } template &lt;class T&gt; int BinaryTree&lt;T&gt;::findHeight(TreeNode *nodePtr) { if (nodePtr == NULL) { return 0; } int left = findHeight(nodePtr-&gt;left); int right = findHeight(nodePtr-&gt;right); if (left &gt; right) return 1 + left; else return 1 + right; } #endif </code></pre> <p><strong>Here is my EmployeeInfo class header and cpp:</strong></p> <pre><code>/* Specification file for the EmployeeInfo class which will hold two private data members, one which is an integer called empID and another which will be a string called empName.*/ #include "BinaryTree.h" #include &lt;iostream&gt; #include &lt;string&gt; #ifndef EMPLOYEEINFO_H #define EMPLOYEEINFO_H class EmployeeInfo { private: int empID; string empName; public: // Default Constructor EmployeeInfo(); // Constructor EmployeeInfo(int, string); // Mutator functions void setEmpID(int); void setEmpName(string); // Accessor functions int getEmpID() const; string getEmpName() const; // Overloaded operators bool operator &lt; (const EmployeeInfo &amp;right); bool operator &gt; (const EmployeeInfo &amp;right); bool operator == (const EmployeeInfo &amp;right); }; #endif // Declaration file for the EmployeeInfo class #include "BinaryTree.h" #include "EmployeeInfo.h" #include &lt;iostream&gt; #include &lt;string&gt; // Default Constructor EmployeeInfo::EmployeeInfo() { empID = 0; empName = ""; } // Constructor EmployeeInfo::EmployeeInfo(int i, string n) { empID = i; empName = n; } // Mutators void EmployeeInfo::setEmpID(int i) { empID = i; } void EmployeeInfo::setEmpName(string n) { empName = n; } // Accessors int EmployeeInfo::getEmpID() const { return empID; } string EmployeeInfo::getEmpName() const { return empName; } // Overloaded operators bool EmployeeInfo::operator &gt; (const EmployeeInfo &amp;right) { bool status; if (empID &gt; right.empID) status = true; else status = false; return status; } bool EmployeeInfo::operator &lt; (const EmployeeInfo &amp;right) { bool status; if (empID &lt; right.empID) status = true; else status = false; return status; } bool EmployeeInfo::operator == (const EmployeeInfo &amp;right) { bool status; if (empID == right.empID) status = true; else status = false; return status; } </code></pre> <p><strong>And here is the main program:</strong></p> <pre><code>#include "BinaryTree.h" #include "EmployeeInfo.h" #include &lt;iostream&gt; #include &lt;string&gt; using namespace std; const int NUM_EMPS = 5; int main() { BinaryTree&lt;EmployeeInfo&gt; staff; int ID; string name; // Fill up the tree for (int count = 0; count &lt; NUM_EMPS; count++) { cout &lt;&lt; "Enter the ID number for Employee " &lt;&lt; count + 1 &lt;&lt; ": "; cin &gt;&gt; ID; cout &lt;&lt; "Name: "; cin &gt;&gt; name; EmployeeInfo newEmp(ID, name); staff.insertNode(newEmp); } // NEED HELP WITH THIS PART!!! do { int search; cout &lt;&lt; "Enter the ID number you'd like to search for: "; cin &gt;&gt; search; system("pause"); return 0; } </code></pre> <p>I'm able to fill up the tree fine with the objects, but when it comes to searching the tree I'm lost! Any help will be appreciated. </p>
<p>Display the info using the binary tree class.</p> <p>Edit your <code>searchNode</code> function in the Binary Tree class</p> <pre><code>template &lt;class T&gt; bool BinaryTree&lt;T&gt;::searchNode(T item) { TreeNode *nodePtr = root; while (nodePtr) { if (nodePtr-&gt;value == item) { cout &lt;&lt; nodePtr-&gt;value &lt;&lt; endl; return true; } else if (item &lt; nodePtr-&gt;value) nodePtr = nodePtr-&gt;left; else nodePtr = nodePtr-&gt;right; } return false; } </code></pre> <p>Then create an EmployeeInfo object, assign it the ID to search for, and search your tree:</p> <pre><code>int search; cout &lt;&lt; "Enter the ID number you'd like to search for: "; cin &gt;&gt; search; EmployeeInfo tempEmp; tempEmp.setEmpID(search); if (!staff.searchNode(tempEmp)) cout &lt;&lt; "Employee ID not found.\n"; // else if staff.searchNode(tempEmp) == true, employee info will // be displayed from Binary Tree searchNode method </code></pre>
counting missing values in a time series using R <p>I have a large time series dataset taken from a rain station with hourly intervals. To assess the quality of the data I'll like to know which days don't have the 24 measurements they should.</p> <p>This is the structure of my dataframe where the Date column is already in POSIXct format:</p> <pre><code> Date Time Rain 1 2014-12-05 10:00 AM 0 2 2014-12-05 12:00 PM 0 3 2014-12-05 1:00 PM 0 4 2014-12-05 2:00 PM 0 5 2014-12-05 3:00 PM 0 6 2014-12-05 4:00 PM 0 7 2014-12-05 5:00 PM 0 8 2014-12-05 6:00 PM 0 9 2014-12-05 7:00 PM 0 10 2014-12-05 8:00 PM 0 </code></pre> <p>Is there a way in which I can count the number of rows each day has and then create a table showing the date and the number of measurements if these were less than 24 per day?</p> <p>Thanks!</p>
<p>you can try this</p> <pre><code>tab = table(df$Date) tab[which(tab&lt;24)] </code></pre>
Execute a command from a variable inside a while loop or export variable out of while loop <p>I've written a script with a while loop, not realising the difficulty of getting a variable out of said while loop.</p> <p>What I want to do is to run the command the while loop saves in the 'stream' variable (see code below) after the while loop has completed as many loops as needed. I'm using this script to detect which game controllers are connected and creating a command to initialize moonlight, a program for the raspberry pi which lets me stream through Nvidia Game Stream, with different controller types.</p> <pre><code>#!/bin/bash stream="moonlight stream -1080 -app Steam" device=none event=0 Player="-input /dev/input/event" XbElite="-mapping /opt/retropie/configs/moonlight/XboxOne.map" PlSt3="-mapping /opt/retropie/configs/moonlight/PS3.map" XboxElite="N\:\ Name\=\"Microsoft\ X\-Box\ One\ Elite\ pad\"" PS3="N\:\ Name\=\"PLAYSTATION\(R\)3\ Controller\"" cat /proc/bus/input/devices | \ while read CMD; do line=$(echo "$CMD" | sed 's/ /\\ /g; s/:/\\:/g; s/(/\\(/g; s/)/\\)/g; s/-/\\-/g; s/=/\\=/g') if [ "$line" = "$XboxElite" ]; then echo Xbox device=xboxElite if [ "$device" = "xboxElite" ]; then stream="$stream $XbElite $Player$event" event=$((event+1)) device=none fi elif [ "$line" = "$PS3" ]; then echo PS3 device=ps3 if [ "$device" = "ps3" ]; then stream="$stream $PlSt3 $Player$event" event=$((event+1)) device=none fi fi done echo $stream #put here as a placeholder to see the final command in the variable. Currently printing: 'moonlight stream -1080 -app Steam' </code></pre> <p>I realise this probably isn't the cleanest way of doing this or that the code is even close to as well written as it could be, but as I have little previous experience with coding of any sort, this is what I could manage for the time being.</p> <p>Any help would be greatly appreciated!</p>
<p>Well, the way to run it as a command would be to just remove the <code>echo</code>:</p> <pre><code>done $stream </code></pre> <p>... except that you can't, because the <code>while</code> loop is on the right side of a pipe. That means it runs in a "subshell" and can't have side effects back in its parent shell (outside of the loop); after the loop exits, <code>$stream</code> will be back to what it was before the loop.</p> <p>In order to keep the loop in the same environment as the surrounding code instead of its own subshell, you need to read from the file directly rather than using a pipe:</p> <pre><code># no `cat` command here. No pipe. while read CMD; do ... done &lt;/proc/bus/input/devices #this replaces the `cat |`. $stream </code></pre> <p>In the general case, when building a command dynamically to run later, you are going to run into problems with quoting or spaces or other special characters. It's easiest to avoid those issues if you build the command in an array instead of a string. The syntax for building and running a command inside an array looks like this:</p> <pre><code>stream=(moonlight stream -1080 -app Steam) ... while read CMD; do ... stream+=("$XbElite" "$Player$event") ... stream+=("$PlSt3" "$Player$event") ... done &lt;/proc/bus/input/devices "${stream[@]}" </code></pre>
how to pick data by key from dictionary array? <p>I try to pick data from array dictionary by key.<br>I can do it index number.<br> but here is my dictionary <code>[[String : AnyObject]]</code> what is the <strong>key</strong> store each element when i Deserializing from json to dictionary.<br>because dictionary set <strong>key value</strong> pair and Each value from the dictionary is associated with a <strong>unique key</strong>. </p> <p>Here is my Json :</p> <pre><code>{ "photos": { "page": 1, "pages": 1, "perpage": 500, "total": 36, "photo": [ { "id": "9671201784", "owner": "34507951@N07", "secret": "fb55a848bc", "server": "5494", "farm": 6, "title": "Burning Man 2013", "ispublic": 1, "isfriend": 0, "isfamily": 0, "url_m": "https://farm6.staticflickr.com/5494/9671201784_fb55a848bc.jpg", "height_m": "333", "width_m": "500", "is_primary": 1, "has_comment": 0 }, { "id": "16553346708", "owner": "116399434@N04", "secret": "092f304f0e", "server": "7630", "farm": 8, "title": "Burning Man", "ispublic": 1, "isfriend": 0, "isfamily": 0, "url_m": "https://farm8.staticflickr.com/7630/16553346708_092f304f0e.jpg", "height_m": "244", "width_m": "500", "is_primary": 0, "has_comment": 0 }], "stat": "ok" } </code></pre> <p>Deserializing swift code ;</p> <pre><code>if let photos = parsedResult[Constants.FlickerResponseKeys.Photos] as?[String : AnyObject ]{ // print(photos[Constants.FlickerResponseKeys.Photo]) if let photo = photos[Constants.FlickerResponseKeys.Photo] as? [[String : AnyObject]] { print(photo[0]) } } </code></pre>
<p>Place this inside photo</p> <pre><code>for (key, value) in photo { print(key) print(value) } </code></pre>
Parse post data with punctuation incorrectly in golang <p>I know how to parse post data in golang</p> <pre><code>r.ParseForm() pid := r.PostFormValue("pid") code := r.PostFormValue("code") lang := r.PostFormValue("lang") author := r.PostFormValue("author") </code></pre> <p>But the post data is <code>pid=1&amp;code=#include &lt;stdio.h&gt;\x0Aint main()\x0A{\x0A\x09printf(\x223\x5Cn\x22);\x0A\x09return 0;\x0A}&amp;lang=c&amp;author=11</code>(this is obtained from nginx log)</p> <p>So when I parse the data, it could be wrong. The parsed data of <code>code</code> is </p> <pre><code>#include &lt;stdio.h&gt; int main() { printf("3\n") </code></pre> <p>instead of</p> <pre><code>#include &lt;stdio.h&gt; int main() { printf("3\n"); return 0; } </code></pre> <p>So how can I fix this problem?</p>
<p>You're passing the raw code, which could be <strong>unsafe</strong>, your problem is because of this:</p> <p><a href="https://golang.org/src/net/url/url.go?s=21047:21092#L761" rel="nofollow">https://golang.org/src/net/url/url.go?s=21047:21092#L761</a></p> <p><a href="https://i.stack.imgur.com/bi8vF.png" rel="nofollow"><img src="https://i.stack.imgur.com/bi8vF.png" alt="enter image description here"></a></p> <p>I would suggest that you base64encode your log code and then decode it in your handler.</p> <pre class="lang-go prettyprint-override"><code>import "encoding/base64" ... code, err := base64.RawURLEncoding.DecodeString(r.PostFormValue("code")) if err != nil { // handle error } </code></pre> <p>Then your request should look like this:</p> <pre><code>curl --data "pid=1&amp;code=I2luY2x1ZGUgPHN0ZGlvLmg-XHgwQWludCBtYWluKClceDBBe1x4MEFceDA5cHJpbnRmKFx4MjIzXHg1Q25ceDIyKTtceDBBXHgwOXJldHVybiAwO1x4MEF9&amp;lang=c&amp;author=11" http://localhost:8080 </code></pre>
Java retrieving array and printing it in a for each loop <p>I am trying to make a program where it retrieves a set of arrays from a different class</p> <pre><code>int barHeights[] = new int[] { 1, 2, 3, 4, 5, 6, 7 }; </code></pre> <p>then calling it in a method and printing it out</p> <pre><code>public void init(int[] barHeights) { Bar[] barArray = new Bar[barHeights.length]; for (Bar bar : barArray){ System.out.println(bar); } </code></pre> <p>i'm unsure why it is printing out 'null' 7 times in a row in the console. Shouldn't it be:</p> <pre><code>1 2 3 4 5 6 7 </code></pre>
<p>In line:</p> <pre><code>Bar[] barArray = new Bar[barHeights.length]; </code></pre> <p>You are creating an instance of array of Bar class references instead of int. <br>This array is automaticly initialized with null values, and in line:</p> <pre><code>for (Bar bar : barArray){ System.out.println(bar); </code></pre> <p>You are interating those null values.<br> If you want to retrive the array, which you passed as an argument to method, you should use:</p> <pre><code>public void init(int[] barHeights) { for (int i : barHeights) { System.out.println(i); } } </code></pre>
Jade sets it's own style tag to every p element <p>In my website, I wondered why I couldn't set a font size for my p elements, and it turns out jade has been adding style="font-size: 12px" to all my p elements as if I did it. Any way to fix this? It's probably my fault but I don't know what I did.</p>
<p>I'm really stupid, sorry about that, it was my own js file adding it on.</p>
In Ruby, how do I add multiple user input in f.number_field? <p>I'm a complete Ruby noob so please explain things to me like I'm 5. I have a form that has seven f.number_fields. I would like to add them and store them in :total. Here is an example of what I'm talking about:</p> <pre><code> &lt;%= f.label :icecream %&gt;&lt;br&gt; &lt;%= f.number_field :icecream %&gt; &lt;%= f.label :cake %&gt;&lt;br&gt; &lt;%= f.number_field :cake %&gt; </code></pre> <p>So in this case I would like to take the user input from :icecream and :cake and add them and store it in :total, but how would I do that? This would then be stored in the database.</p>
<p>Ok you have your form in your view your model and your controller. What is going to happen is you are going to fill out your form that is in the new view for totals. Hit the submit button, that is going to make a request to your controller action <code>create</code>. In the <code>create</code> action it is going to make a call to the <code>total_params</code> method which is just going to check the <code>params</code> hash (which contains all the information that was just in you form in the view) to make sure it has values for the <code>:total</code> key and it will allow <code>:cake</code> and <code>:icecream</code> to be passed in (this is call strong parameters or white listing parameters), the <code>private</code> keyword is just so the <code>total_params</code> action is not directly accessed from outside the controller. Then in the <code>create</code> method the <code>each</code> look is going to iterate over the values in the hash returned by the call to <code>total_params</code> then add it to the variable total_value. One the each loop has finished a <code>Total</code> record will be created in they database with a <code>total</code> column value that is the sum of <code>icecream</code> and <code>cake</code>. This is approximately how you would go about storing a value.</p> <p>View</p> <pre><code> #app/views/totals/new.html.erb &lt;%= form_for @total, url: {action: "create"} do |f| %&gt; &lt;%= f.label :icecream %&gt;&lt;br&gt; &lt;%= f.number_field :icecream %&gt; &lt;%= f.label :cake %&gt;&lt;br&gt; &lt;%= f.number_field :cake %&gt; &lt;%= f.submit %&gt; </code></pre> <p>Controller</p> <pre><code> #app/controllers/totals_controller.rb class TotalsController &lt;&lt; ApplicationController def create total_value = 0 total_params.each do |k, v| total_value += v end Total.create(total: total_value) end private def total_params params.require(:total).permit(:cake, :icecream) end end </code></pre> <p>Model</p> <pre><code> #app/models/total.rb class Total &lt;&lt; ActiveRecord::Base end </code></pre>
Keep All Characters Before Backslash R <p>I have a list of 10 chr called data and am trying to remove everything that occurs after the first backslash but am having difficulty.</p> <p>For example, here is the first string:</p> <p><code>Nov. 3, 2016\n\t\t\t\n\t\t\t\n\t\t\t\tBO</code></p> <p>I only want to keep Nov. 3, 2016</p> <p>I am trying:</p> <pre><code>gsub('\\\\\.*', '', data) </code></pre> <p>But it is not doing the trick.</p> <p>Please copy and paste the below in R to recreate the list.</p> <pre><code>data &lt;- c("Nov. 3, 2016\n\t\t\t\n\t\t\t\n\t\t\t\tBO", "July 21, 2016\n\t\t\t\n\t\t\t\n\t\t\t\tBO", "May 3, 2016\n\t\t\t\n\t\t\t\n\t\t\t\tBO", "Feb. 24, 2016\n\t\t\t\n\t\t\t\n\t\t\t\tBO", "Nov. 12, 2015\n\t\t\t\n\t\t\t\n\t\t\t\tBO", "July 24, 2015\n\t\t\t\n\t\t\t\n\t\t\t\tBO", "May 12, 2015\n\t\t\t\n\t\t\t\n\t\t\t\tBO", "Feb. 25, 2015\n\t\t\t\n\t\t\t\n\t\t\t\tBO", "Nov. 12, 2014\n\t\t\t\n\t\t\t\n\t\t\t\tBO", "July 24, 2014\n\t\t\t\n\t\t\t\n\t\t\t\tBO") </code></pre> <p>Thanks for your help.</p>
<p><code>sub</code> function would be enough for this case since the replacement would occur only once.,</p> <pre><code>sub("\\n[\\s\\S]*", "", x) </code></pre> <p><a href="https://regex101.com/r/SxRKe6/1" rel="nofollow">DEMO</a></p>
String to numeric conversion using regex in scala <p>Hi have an array of numbers as string: </p> <p><code>val original_array = Array("-0,1234567",......)</code> which is a string and I want to convert to a numeric Array.</p> <pre><code>val new_array = Array("1234567", ........) </code></pre> <p>How can I aheive this in scala?</p> <p>Using original_array.toDouble is giving error</p>
<p>The simple answer is ...</p> <pre><code>val arrNums = Array("123", "432", "99").map(_.toDouble) </code></pre> <p>... but this a little dangerous because it will throw if any of the strings are not proper numbers.</p> <p>This is safer...</p> <pre><code>val arrNums = Array("123", "432", "99").collect{ case n if n matches """\d+""" =&gt; n.toDouble } </code></pre> <p>... but you'll want to use a regex pattern that covers all cases. This example won't recognize floating point numbers ("1.1") or negatives ("-4"). Something like <code>"""-?\d*\.?\d+"""</code> might fit your requirements.</p>
Hadoop Mutlicluster installation on Amazon ubuntu instances <p>In all the explanations of installation of hadoop on linux, the mention of folders like : hadoop/etc or hadoop/bin occurs. However, after I downloaded, extracted and renamed hadoop, my hadoop folder contains the following subfolders: !<a href="https://s13.postimg.org/kvhy23r47/capture32.png" rel="nofollow">https://s13.postimg.org/kvhy23r47/capture32.png</a></p> <p>So my hadoop folder does not contain the folders etc and bin</p> <p>The other files that are referred to in the installation guides (which are expected to be present in hadoop/conf) such as core-sie.xml, hadoop-env.sh, yarn-site.xml and mapred-site.xml are all present in one subfolder or the other, and i have individually accessed the files to edit them.</p> <p>But I am sure that I'm doing something wrong. Can anyone help me know where am I doing it wrong?</p>
<p>I understood my mistake</p> <p>I was downloading src file from the release page of hadoop. I should download the binaries</p>
How to hide number of comments text in Wordpress website <p>I'm creating a website by using Wordpress CMS (wordpress.org). My question is how to hide or remove number of comments text above the comments elements. See below image.</p> <p><a href="https://i.stack.imgur.com/NJq9q.png" rel="nofollow"><img src="https://i.stack.imgur.com/NJq9q.png" alt="enter image description here"></a></p> <p>Any help would be much appreciated.</p>
<p>You can hide number of comments text by css like.</p> <pre><code>.comments-area .comments-title{ display: none; } </code></pre> <p>Or you can remove code from <code>comment.php</code> file.</p> <pre><code> &lt;h2 class="comments-title"&gt; &lt;?php printf( _nx( 'One thought on &amp;ldquo;%2$s&amp;rdquo;', '%1$s thoughts on &amp;ldquo;%2$s&amp;rdquo;', get_comments_number(), 'comments title', 'twentyfifteen' ), number_format_i18n( get_comments_number() ), get_the_title() ); ?&gt; &lt;/h2&gt; </code></pre> <p>Find the line something like it depends on your theme developer which tag his used. try to find out <code>h1</code>,<code>h2</code>,<code>h3</code>,<code>h4</code>,<code>h5</code>,<code>h6</code> and remove it.</p> <p>if you can't find any line with this tag. please put your <code>comment.php</code> file code so i can give a exact solution.</p> <p>Thanks</p>
Why is my webpage load time more than 10 secs even with 98% speed performance score? <p>Is there any way to identify why this <a href="http://eamcetexams.com" rel="nofollow">website</a> initial loading is very slow? I have checked in my each and every part of the HTML structure and code (Requests, Response).</p> <p>It’s loading very fast after first time loading completes. I have performed page speed optimization then followed <a href="https://developers.google.com/speed/docs/insights/rules" rel="nofollow">page speed rules</a>. After that my page speed score in GTMetrix as below picture. But still initial loading is very slow. </p> <p>What would be the reason? How can we resolve this type of speed issues? <a href="https://i.stack.imgur.com/KnusU.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/KnusU.jpg" alt="enter image description here"></a></p>
<p>It seems to me that there is an issue with your subdomain. Possibly with DNS resolution maybe.</p>
Java Programming: Turtle not moving in desired direction <p>I'm writing a Java program in which I have to get the turtle to move West, but what I have so far isn't getting the turtle to move in the desired direction.</p> <pre><code>public static void moveTurtleWest(Turtle t, int n) { for(; n &gt; t.getX();n-- ){ t.moveWest(); } } </code></pre> <p>Here is the rest of my code:</p> <pre><code>package assignment; import java.text.MessageFormat; import java.util.Scanner; import java.awt.Point; import java.awt.Dimension; import java.awt.Rectangle; import java.time.LocalDate; /** * This class represents a turtle, like a Logo-like turtle, which keeps its position. * The turtle keeps its x and y position, and has methods moveNorth() etc which change it * Assume normal math coordinates and map convention, so as you move up (North) y increases, and as you move East x increases. * */ class Turtle { // HINT - you may want to have variables to keep the position. Keep these variables private, private int x,y; // TODO - The empty constructor initializes position to 10,10 public Turtle() { this.x = 10; this.y = 10; } public int getX() { // TODO - implement this return this.x; } public int getY() { // TODO - implement this return this.y; } public void moveNorth() { // TODO - implement this. this increments the y coordinate by one unit this.y += 1; } public void moveSouth() { // TODO - implement this. this decrements the y coordinate by one unit this.y -=1; } public void moveEast() { // TODO - this increments the x coordinate by one unit this.x +=1; } public void moveWest() { // TODO - this decrements the x coordinate by one unit this.x -=1; } public String toString() { return "Turtle[x="+getX()+", y="+getY()+"]"; } public boolean equals(Turtle t) { // TODO - you need to implement this // two turtles are equal if their X and Y coordinates are equal. if (t == null) { return false; } if (!(t instanceof Turtle)) { return false; } return (x == ((Turtle) t).x &amp;&amp; y == ((Turtle) t).y); } public void move(String direction) { // TODO - you need to implement this // move to the right direction; direction can be North, South, East, West moveEast(); } } public class Assignment7 { // TODO - you need to implement this. Move the given turtle to the West, n times public static void moveTurtleWest(Turtle t, int n) { for(; n &gt; t.getY();n-- ){ t.moveWest(); } } // TODO - you need to implement this. Move the given turtle to the East, n times public static void moveTurtleEast(Turtle t, int n) { } // TODO - you need to implement this. Move the given turtle to the North, n times public static void moveTurtleNorth(Turtle t, int n) { } // TODO - you need to implement this. Move the given turtle to the South, n times public static void moveTurtleSouth(Turtle t, int n) { } // TODO - you need to implement this. Move the turtle to the asked position, by calling MoveXXX etc public static void moveTurtleTo(Turtle t, int x, int y) { } public static void main(String[] args) { // you can use this as you wish to test or exercise your function. Not graded. Turtle t=new Turtle(); moveTurtleTo(t,15,16); System.out.println(t); } } </code></pre> <p>Here is the code that is executing when I run this method in git Bash:</p> <pre><code>public void testMoveWest() { Turtle t=new Turtle(); t.moveWest(); t.moveWest(); t.moveWest(); t.moveWest(); Assert.assertEquals(6, t.getX()); } @Grade(points=10) @Test </code></pre> <p>Any help is appreciated and points will be rewarded. Thanks in advance!</p>
<p>Possibly correct for loop:</p> <pre><code> public static void moveTurtleWest(Turtle t, int n) { for(int i=0; i &lt;n;i++ ){ t.moveWest(); } } </code></pre>
C ++ simple function returning huge value - always the same value no matter the inputs - 4309838 <p>I am learning to code and this is a very simple function but it keeps returning the same answer every time, 4309838, and I don't know why. It is meant to calculate a paycheck, adding 50 whenever there is overtime. Any help is appreciated.</p> <pre><code>float payCheck(int ratePar, float hoursPar) { if (hoursPar&gt;40) payCheck = ratePar*hoursPar + 50; else payCheck = ratePar*hoursPar; return payCheck; } int main() { int rate; float hours, pay; cout&lt;&lt;"Enter hours worked and pay rate "&lt;&lt;endl; cin&gt;&gt;hours&gt;&gt;rate; pay = payCheck(rate, hours); cout&lt;&lt;"Your paycheck is "&lt;&lt;pay&lt;&lt;endl; } </code></pre>
<p>You have not declared payCheck variable in payCheck method. This works:</p> <pre><code>float payCheck(int ratePar, float hoursPar) { float payCheck; if (hoursPar&gt;40) payCheck = ratePar*hoursPar + 50; else payCheck = ratePar*hoursPar; return payCheck; } </code></pre>
Why do i get this error "TypeError: 'int' object is not callable"? <pre><code>def diameter(Points): '''Given a list of 2d points, returns the pair that's farthest apart.''' diam,pair = max([((p[0]-q[0])**2 + (p[1]-q[1])**2, (p,q)) for p,q in rotatingCalipers(Points)]) return pair n=int(input()) a=[] max=0 for i in xrange(n): m,n=map(int,raw_input().split()) a.append((m,n)) diameter(a) </code></pre> <p>Traceback</p> <pre><code>Traceback (most recent call last): File "geocheat1.py", line 56, in &lt;module&gt; diameter(a) File "geocheat1.py", line 43, in diameter for p,q in rotatingCalipers(Points)]) TypeError: 'int' object is not callable </code></pre>
<p>From the Traceback it's clear than you are trying to call <code>int</code> object, So <code>rotatingCalipers</code> may be declared as integer in your code. </p> <p>See this example you will understand the error,</p> <pre><code>In [1]: a = (1,2,3) In [2]: list(a) Out[1]: [1, 2, 3] In [3]: list = 5 In [4]: list(a) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-20-61edcfee5862&gt; in &lt;module&gt;() ----&gt; 1 list(a) TypeError: 'int' object is not callable </code></pre>
Querying across multiple tables avoiding a union all <p>I have the following DB tables that I am trying to query:</p> <pre><code>t_shared_users user_id user_category folder_id expiry t_documents id folder_id user_id user_category description created updated t_folder id type user_id user_category created updated </code></pre> <p>I would like to find all the documents you own and have shared access to. ie. search for all documents in t_documents where user_id = 1 AND user_category = 100 but also include those documents in the folder you have access to in t_shared_users. Here is my attempt at the query:</p> <pre><code> SELECT id, folder_id, user_id, user_category, description, created, updated FROM t_documents WHERE user_category = 100 AND user_id = 1 UNION ALL SELECT d.id, d.folder_id, d.user_id, d.user_category, d.description, d.created, d.updated FROM t_documents d JOIN t_shared_users s ON d.folder_id = s.folder_id WHERE d.user_category = 100 d.AND user_id = 1 ORDER BY created ASC LIMIT 10 </code></pre> <p>Is there any better/more performant/concise way to write this query? The above seems a little verbose and slow.</p> <p>edit:</p> <pre><code>CREATE TABLE t_folder ( id SERIAL NOT NULL, user_category SMALLINT NOT NULL, user_id INTEGER NOT NULL, type INTEGER NOT NULL, description TEXT, created TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), updated TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), PRIMARY KEY (id) ); CREATE TABLE t_documents ( id BIGSERIAL NOT NULL, folder_id INTEGER, user_category SMALLINT NOT NULL, user_id INTEGER NOT NULL, description TEXT NOT NULL, created TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), updated TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), PRIMARY KEY (id) ); CREATE TABLE t_shared_users ( id SERIAL, folder_id INTEGER NOT NULL, user_category INTEGER NOT NULL, user_id INTEGER NOT NULL, expiry TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), PRIMARY KEY (id) ); </code></pre>
<p>This is your query:</p> <pre><code> SELECT id, folder_id, user_id, user_category, description, created, updated FROM t_documents WHERE user_category = 100 AND user_id = 1 UNION ALL SELECT d.id, d.folder_id, d.user_id, d.user_category, d.description, d.created, d.updated FROM t_documents d JOIN t_shared_users s ON d.folder_id = s.folder_id WHERE d.user_category = 100 AND d.user_id = 1 -- your query actually has a typo here </code></pre> <p>What I don't understand about the above query is why you are filtering on <code>d.user_category</code> and <code>d.user_id</code> (<code>t_documents</code> table) in the bottom part of the query. Are you sure you didn't mean <code>s.user_category</code> and <code>s.user_id</code> (<code>t_shared_users</code>)? If not, what is the point of joining with <code>t_shared_users</code>?</p> <p>Assuming that I am correct that your query is in error, this is how I would rewrite it:</p> <pre><code>select d.* from t_documents d where d.user_category = 100 and d.user_id = 1 union select d.* from t_shared_users s join t_documents d on d.folder_id = s.folder_id where s.user_category = 100 and s.user_id = 1 </code></pre> <p>Notice that I use <code>union</code> instead of <code>union all</code>, as I believe it's technically possible to get possibly unwanted duplicate documents otherwise.</p> <p>Also, just as a rough approximation, these are the indexes I would define for good performance:</p> <ul> <li><code>t_documents (user_id, user_category)</code></li> <li><code>t_documents (folder_id)</code></li> <li><code>t_shared_users (user_id, user_category, folder_id)</code></li> </ul>
ionic - login page not redirecting to main page <p>This is happening only when login page is used as fallback. Same login page is working fine when main page is used as fallback. I'm very new to this framework and any help for fixing this would be much appreciated. Please feel free to ask if you need any other code for solving this. Thanks in advance!</p> <p>Here is my config,</p> <pre><code>.config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('app', { url: '/app', abstract: true, templateUrl: 'templates/menu.html' }) .state('app.login', { url: '/login', views: { 'menuContent': { templateUrl: 'templates/login.html', controller: 'AppCtrl' } }, authenticate: false }) .state('app.search', { url: '/search', views: { 'menuContent': { templateUrl: 'templates/search.html', controller: 'mainCtrl' } } }) .state('app.browse', { url: '/browse', views: { 'menuContent': { templateUrl: 'templates/browse.html', controller: 'mainCtrl' } } }) .state('app.playlists', { url: '/playlists', views: { 'menuContent': { templateUrl: 'templates/playlists.html', controller: 'PlaylistsCtrl' } } }) .state('app.snapshot', { url: '/snapshot', views: { 'menuContent': { templateUrl: 'templates/snapshot.html' } } }) .state('app.callqueues', { url: '/callqueues', views: { 'menuContent': { templateUrl: 'templates/callqueues.html' } } }) .state('app.single', { url: '/playlists/:playlistId', views: { 'menuContent': { templateUrl: 'templates/playlist.html', controller: 'PlaylistCtrl' } } }); // if none of the above states are matched, use this as the fallback // $urlRouterProvider.otherwise('/app/search'); $urlRouterProvider.otherwise('/app/login'); }); </code></pre> <p>This is my loginCtrl(login controller),</p> <pre><code>angular.module('starter.controllers', []) .controller('AppCtrl', function($scope, $ionicModal, $timeout, $location, $http, $log, $state) { // With the new view caching in Ionic, Controllers are only called // when they are recreated or on app start, instead of every page change. // To listen for when this page is active (for example, to refresh data), // listen for the $ionicView.enter event: //$scope.$on('$ionicView.enter', function(e) { //}); // Form data for the login modal $scope.loginData = {}; // Create the login modal that we will use later // $ionicModal.fromTemplateUrl('templates/login.html', { // scope: $scope // }).then(function(modal) { // $scope.modal = modal; // }); // Triggered in the login modal to close it // $scope.closeLogin = function() { // $scope.modal.hide(); // }; // Open the login modal // $scope.login = function() { // $scope.modal.show(); // }; $scope.chartConfig = { options: { chart: { type: 'bar' } }, series: [{ data: [10, 15, 12, 8, 7] }], title: { text: 'Hello' }, loading: false }; // Perform the login action when the user submits the login form $scope.doLogin = function() { console.log('Doing login', $scope.loginData); var username = $scope.loginData.name; var password = $scope.loginData.password; console.log("username" + $scope.loginData.name); if (username == "admin@as" &amp;&amp; password == "admin") { console.log("if part"); $location.path("#/app/search"); } else { console.log("error"); // $("#errorpwd").css({"display":"block"}); // $scope.message = "Error"; // $scope.messagecolor = "alert alert-danger"; } // Simulate a login delay. Remove this and replace with your login // code if using a login system // $timeout(function() { // $scope.closeLogin(); // }, 1000); }; }) </code></pre> <p>and finally this is my login html code,</p> <pre><code>&lt;ion-view view-title="Login" name="login-view"&gt; &lt;ion-header-bar class="bar bar-header bar-positive"&gt; &lt;h1 class="title"&gt;Login&lt;/h1&gt; &lt;!--&lt;button class="button button-clear button-primary icon-left ion-close-circled" ng-click="modal.hide()"&gt;&lt;/button&gt;--&gt; &lt;/ion-header-bar&gt; &lt;ion-content&gt; &lt;form ng-submit="doLogin()"&gt; &lt;div class="list"&gt; &lt;label class="item item-input"&gt; &lt;span class="input-label"&gt;Username&lt;/span&gt; &lt;input type="text" ng-model="loginData.name"&gt; &lt;/label&gt; &lt;label class="item item-input"&gt; &lt;span class="input-label"&gt;Password&lt;/span&gt; &lt;input type="password" ng-model="loginData.password"&gt; &lt;/label&gt; &lt;label class="item"&gt; &lt;button nav-clear class="button button-block button-positive" type="submit"&gt;Log in&lt;/button&gt; &lt;/label&gt; &lt;/div&gt; &lt;/form&gt; &lt;/ion-content&gt; </code></pre> <p></p>
<p>You have not injected ui-router as a dependency to the module,</p> <pre><code>angular.module('starter.controllers', ['ui.router']); </code></pre> <p>also refer the js for the ui.router</p> <pre><code> &lt;!-- Angular --&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"&gt;&lt;/script&gt; &lt;!-- UI-Router --&gt; &lt;script src="//angular-ui.github.io/ui-router/release/angular-ui-router.js"&gt;&lt;/script&gt; </code></pre>
check number falls between range <p><a href="https://i.stack.imgur.com/09V43.png" rel="nofollow"><img src="https://i.stack.imgur.com/09V43.png" alt="This is the format how i want"></a></p> <p>column A and Column C is the range and column B is the reference value which I have to compare with Column A and Column C . Eg: (B>A) and (B <p>Basically I want to check whether column B falls between Column A and column C</p> <p>Here is the code which I have prepared but this is not working and this is for single cell:</p> <pre><code>Sub a() Dim x As Integer Dim y As Integer x = Worksheets("Sheet1").Range("A1").Value y = Worksheets("Sheet1").Range("B1").Value Z = Worksheets("Sheet1").Range("C1").Value If Z &gt; x Then Worksheets("Sheet1").Range("D1") = "Correct" End If End Sub </code></pre>
<p>you can do this way:</p> <pre><code>Sub main() With Worksheets("Sheet1") With .Range("D1:D" &amp; .Cells(.Rows.Count, 1).End(xlUp).row) .FormulaR1C1 = "=IF(AND(RC2&gt;=RC1,RC2&lt;=RC3),""Correct"",""Wrong"")" .Value = .Value End With End With End Sub </code></pre>
In A-Frame how do I change an entity's attributes from a raycaster intersection event? <p>I've attached a raycaster to a vive controller entity using <a href="https://aframe.io/" rel="nofollow">Mozilla's A-Frame</a>. I'd like some intersected objects to change opacity while they're being intersected. These objects should be invisible (0 opacity) while not intersected and 0.5 opacity while intersected.</p> <p>I managed to create a component that triggers a function upon the raycaster-intersected event. However, I'm having a hard time trying to figure out how to change the intersected object's attribute from this function.</p> <p><a href="https://aframe.io/docs/0.3.0/components/raycaster.html" rel="nofollow">The a-frame raycaster docs</a> says raycaster-intersected event detail "will contain el, the raycasting entity, and intersection, an object containing detailed data about the intersection." How do I access those? I tried the below and got an error "Uncaught TypeError: Cannot read property 'setAttribute' of undefined"</p> <pre><code>AFRAME.registerComponent('grid-cube-collider', { dependencies: ['raycaster'], init: function () { this.el.addEventListener('raycaster-intersected', function () { this.el.setAttribute('material', 'opacity', '0.5'); }); } }); </code></pre>
<p>this.el is referring to your raycaster entity, not the target entity. The target entity is contained within the event detail, passed in through the event handler callback. Try:</p> <pre><code>this.el.addEventListener('raycaster-intersected', function (evt) { evt.detail.el.setAttribute('material', 'opacity', '0.5'); }); </code></pre>
App Crashed when device time is in 24 hour format <p>In my App if IPhone device time is in 12 hour formate then date formatter works correctly but if device time is in 24 hour formate then app crashed.</p> <pre><code> let dateFormatter = NSDateFormatter(); dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle; dateFormatter.dateFormat = "hh:mm a"; var dt1 = dateFormatter.dateFromString(arrSecond.objectAtIndex(n) as! String) </code></pre>
<p>Assuming that you are using Swift 2.x version after seeing your code.</p> <p>The problem is because your <code>dateFormatter</code> contains <code>a</code> and for the 24 Hour Format time we don't have <code>a</code></p> <p>So in order to fix your problem, you have to check whether your device is in 24-Hour format or 12 Hour format</p> <p>Taking your array's index object in a variable <code>time</code> and keep that as <code>var</code> because we will change that later.</p> <pre><code>var time = arrSecond.objectAtIndex(n) as! String //this contains 07:45 AM //Now create your Date Formatter let dateFormatter = NSDateFormatter(); dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle; //Now check whether your phone is in 12 hour or 24 hour format let locale = NSLocale.currentLocale() let formatter : String = NSDateFormatter.dateFormatFromTemplate("j", options:0, locale:locale)! //we have to change our dateFormatter as per the hour format if formatter.containsString("a") { print("phone is in 12 Hour Format") dateFormatter.dateFormat = "hh:mm a"; } else { print("phone is in 24 Hour Format") time = convertTo24HourFormat(time) //time changed to 24 Hour format and AM/PM removed from string dateFormatter.dateFormat = "HH:mm"; } let finalDate = dateFormatter.dateFromString(time) print(finalDate!) </code></pre> <p>And we need a function to make your time string converted to 24 hour format if your phone is in 24 Hour Format.<br>Function defination of <code>convertTo24HourFormat</code> is</p> <pre><code>//Example 08:45 PM to 20:45 func convertTo24HourFormat(time:String) -&gt; String { var formattedTime = time if formattedTime.containsString("PM") { var hour = Int(formattedTime.substringToIndex(formattedTime.startIndex.advancedBy(2))) if hour != 12 { hour = hour! + 12 formattedTime.removeRange(Range&lt;String.Index&gt;(start: formattedTime.startIndex, end: formattedTime.startIndex.advancedBy(2))) formattedTime = "\(hour!)\(formattedTime)" } } else { // For AM time var hour = Int(formattedTime.substringToIndex(formattedTime.startIndex.advancedBy(2))) //case for 12 AM if hour == 12 { formattedTime.removeRange(Range&lt;String.Index&gt;(start: formattedTime.startIndex, end: formattedTime.startIndex.advancedBy(2))) formattedTime = "00\(formattedTime)" } } formattedTime = formattedTime.substringToIndex(time.startIndex.advancedBy(5)) return formattedTime } </code></pre> <p>But converting only the time to date object don't make any sense as it will give a wrong date.</p> <p><strong>NOTE:-</strong><br> The <code>convertTo24HourFormat</code> function will only work fine if you send the time in the format <code>hh:mm a</code>. For example <strong>07:45 AM</strong></p>
How to access checkboxes which are not yet visible on the screen in a Recycler view <p>I am new to Android and pretty much learning as I go. Hence this query maybe very basic</p> <p>I am displaying a list of checkboxes through a RecyclerViewAdapter. Some of the checkboxes are to select entire group of checkboxes. What I want to do is that if one of the group checkboxes is checked, I want to check all the checkboxes in that group.</p> <p>Everything works fine till I am checking boxes which are already visible, but the moment the iterator goes beyond what is visible, I get a null return.</p> <p>I have used findViewHolderForAdapterPosition and getChildAt. Both have the same issue. Is there anyway I can access boxes which are not yet visible on screen?</p> <p>The relevant part of onCheckedChangedListener is given below</p> <pre><code> private CompoundButton.OnCheckedChangeListener checkChangedListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { final HeaderListStructure structure = (HeaderListStructure) buttonView.getTag(); if (isChecked) { if (structure != null) { selectedRules.add(structure); if (structure.type != Constants.TYPE_ITEM){ ArrayList&lt;Object&gt; temp = (ArrayList) structure.additionalInfo; for (Object obj : temp){ int itr = (int) obj; Log.d(TAG, "onCheckedChanged: Print out int" + itr); RecyclerView checkbox = (RecyclerView) buttonView.getParent().getParent(); LinearLayout linearLay = (LinearLayout) checkbox.findViewHolderForAdapterPosition(itr).itemView; CompoundButton buttonToSet= (CompoundButton) linearLay.getChildAt(0); buttonToSet.setChecked(true); } } } } else { </code></pre> <p>The Oncreate adapter code is here</p> <pre><code>@Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_add_mode_smart_rule, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { final HeaderListStructure structure = rulesListing.get(position); if (structure.type == Constants.TYPE_ITEM) { holder.itemView.setPadding(80, 20, 20, 20); holder.itemView.setVisibility(View.VISIBLE); if (Build.VERSION.SDK_INT &gt;= 23) { holder.itemView.setBackgroundColor(holder.itemView.getContext().getResources().getColor(R.color.white, null)); } else { holder.itemView.setBackgroundColor(holder.itemView.getContext().getResources().getColor(R.color.white)); } }else if(structure.type==Constants.TYPE_SUBHEADER2){ holder.itemView.setPadding(60, 20, 20, 20); holder.itemView.setVisibility(View.VISIBLE); if (Build.VERSION.SDK_INT &gt;= 23) { holder.itemView.setBackgroundColor(holder.itemView.getContext().getResources().getColor(R.color.background_color, null)); } else { holder.itemView.setBackgroundColor(holder.itemView.getContext().getResources().getColor(R.color.background_color)); } } else if(structure.type==Constants.TYPE_SUBHEADER) { holder.itemView.setPadding(40, 20, 20, 20); holder.itemView.setVisibility(View.VISIBLE); if (Build.VERSION.SDK_INT &gt;= 23) { holder.itemView.setBackgroundColor(holder.itemView.getContext().getResources().getColor(R.color.light_cyan, null)); } else { holder.itemView.setBackgroundColor(holder.itemView.getContext().getResources().getColor(R.color.light_cyan)); } } else { holder.itemView.setPadding(20, 20, 20, 20); holder.itemView.setVisibility(View.VISIBLE); if (Build.VERSION.SDK_INT &gt;= 23) { holder.itemView.setBackgroundColor(holder.itemView.getContext().getResources().getColor(R.color.light_pink, null)); } else { holder.itemView.setBackgroundColor(holder.itemView.getContext().getResources().getColor(R.color.light_pink)); } } final String rule = structure.name; holder.cbRule.setText(rule); holder.cbRule.setTag(structure); holder.cbRule.setVisibility(View.VISIBLE); holder.cbRule.setOnCheckedChangeListener(checkChangedListener); } </code></pre>
<p>Just figured out a way to handle this situation. Sharing it in case someone else has a similar query in future.</p> <p>For views that are not yet visible, I just marked them in the array that the adapter is using. The each element of the array has a name and type. Used type to store status of the checkbox and each time the recycler view creates the view, the status is in accordance to the value stored in type.</p> <p>Thanks</p>
golang server: how to retrieve multiple files continuously <p>I have implemented a http server based on <code>gin</code> (golang web framework).</p> <p>I post 2 pictures to server with <code>curl multipart/form-data</code>:</p> <p><code>curl -X POST -F upload0=@jpg -F upload1=@jpg -H "Content-Type: multipart/form-data" "http://server:port/path"</code></p> <p>Server code looks like this:</p> <pre><code>func extractImgs(c *gin.Context) { prefix := "prefix" for ix := 0; ix &lt; 2; ix++ { file, _, err := c.Request.FormFile(prefix + strconv.Itoa(ix)) if err != nil { // do sth. return } face_recognize_async(file) } } </code></pre> <p>You know, face recognition is time-consuming, I hope the work-flow is:</p> <pre><code>get_1st_img -&gt; recognize_face -&gt; get_2nd_img -&gt; recognize_face -&gt; ... </code></pre> <p>I print <code>c.Request.FormFile()</code> execution time, it returns after retrieved <strong>all 2 files</strong>.</p> <p>My questions:</p> <p>1) how to retrieve these files continuously, just like traverse linked list;</p> <p>2) Is http multipart a good choice, should I implement it with TCP/STCP?</p>
<p>Since <code>FormFile</code> indexes the files from the posted form, it requires that the entire form already be parsed. From the <code>FormFile</code> docs:</p> <blockquote> <p>FormFile calls ParseMultipartForm and ParseForm if necessary.</p> </blockquote> <p>If you want to stream the the multipart form one part at a time, use <a href="https://golang.org/pkg/net/http/#Request.MultipartReader" rel="nofollow"><code>Request.MultipartReader</code></a></p>
Angular2 Webpack and Express <p>I've installed Angular 2 Webpack which includes a sample app and demonstrates routing. What I want to look into is using Angular2 for the front end routing but to the use ExpressJS for a RESTful API backend, but on the same server i.e.</p> <p><a href="http://localhost:3000/#/" rel="nofollow">http://localhost:3000/#/</a> will serve the front end in Angular <a href="http://localhost:3000/api" rel="nofollow">http://localhost:3000/api</a> will serve the back end API in Express</p> <p>If I create a api/index.html I can see this shows the api home page but I haven't got a clue how to create the 'app.js' for express to get the express routing working.</p> <p>I appreciate I could easily do it by running two instances but I was trying to keep it all self contained.</p> <p>Regards</p>
<p>I couldn't find a way to do it on the same port so I went with placing this in config/webpack.common.js. (I had thought I would need to start a separate 'npm' process for the API but clearly not!)</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var express = require('express'); var app2 = express(); app2.get('/', function (req, res) { res.send('API'); }); app2.listen(3001, function () { });</code></pre> </div> </div> </p>
In PHP, what does this block of code do in forms required field? <p><strong>What does this block of PHP code do?</strong></p> <pre><code>function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } </code></pre> <p><strong>This is the entire PHP Program</strong></p> <p><em>It is taken from w3schools.com <a href="http://www.w3schools.com/php/showphp.asp?filename=demo_form_validation_required" rel="nofollow">http://www.w3schools.com/php/showphp.asp?filename=demo_form_validation_required</a></em></p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; .error {color: #FF0000;} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;?php // define variables and set to empty values $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?&gt; &lt;h2&gt;PHP Form Validation Example&lt;/h2&gt; &lt;p&gt;&lt;span class="error"&gt;* required field.&lt;/span&gt;&lt;/p&gt; &lt;form method="post" action="&lt;?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?&gt;"&gt; Name: &lt;input type="text" name="name"&gt; &lt;span class="error"&gt;* &lt;?php echo $nameErr;?&gt;&lt;/span&gt; &lt;br&gt;&lt;br&gt; E-mail: &lt;input type="text" name="email"&gt; &lt;span class="error"&gt;* &lt;?php echo $emailErr;?&gt;&lt;/span&gt; &lt;br&gt;&lt;br&gt; Website: &lt;input type="text" name="website"&gt; &lt;span class="error"&gt;&lt;?php echo $websiteErr;?&gt;&lt;/span&gt; &lt;br&gt;&lt;br&gt; Comment: &lt;textarea name="comment" rows="5" cols="40"&gt;&lt;/textarea&gt; &lt;br&gt;&lt;br&gt; Gender: &lt;input type="radio" name="gender" value="female"&gt;Female &lt;input type="radio" name="gender" value="male"&gt;Male &lt;span class="error"&gt;* &lt;?php echo $genderErr;?&gt;&lt;/span&gt; &lt;br&gt;&lt;br&gt; &lt;input type="submit" name="submit" value="Submit"&gt; &lt;/form&gt; &lt;?php echo "&lt;h2&gt;Your Input:&lt;/h2&gt;"; echo $name; echo "&lt;br&gt;"; echo $email; echo "&lt;br&gt;"; echo $website; echo "&lt;br&gt;"; echo $comment; echo "&lt;br&gt;"; echo $gender; ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p><em>What it does</em></p> <p><code>trim()</code> removes whitespace from the beginning and end, <code>stripslashes()</code> any slash that might be added if magic_quotes is active (which depends on your PHP configuration&amp;version), and <code>htmlspecialchars()</code> adds slashes again.</p> <p><em>Why</em></p> <p>The theme here is <strong>XSS Prevention</strong>. However, there is more to learn about this than simply applying <code>htmlspecialchars()</code> before outputting it with <code>echo</code>. You can <a href="http://stackoverflow.com/search?q=xss%20prevention%20html%20php">search for this topic on SO</a>.</p> <p>Also, a fun way to learn about this is <a href="https://google-gruyere.appspot.com/" rel="nofollow">this website</a> that presents challenges where you try to play the hacker's part.</p>
Why I am getting error with my activity in android? <p>I declare both of my activity class in AndroidManifest.xml file them when I run my application it stop unfortunately with this error message:-</p> <pre><code> android.content.ActivityNotFoundException: Unable to find explicit activity class {com.androidtutorialpoint.androidobservablescrollview/com.androidtutorialpoint.androidobservablescrollview.ParallaxToolbarScrollViewActivity}; have you declared this activity in your AndroidManifest.xml? </code></pre> <p>This is my manifest file:-</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="in.doctormobileapps.androidobservablescrollview"&gt; &lt;application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"&gt; &lt;activity android:name=".MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN"/&gt; &lt;category android:name="android.intent.category.LAUNCHER"/&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".ParallaxToolbarScrollViewActivity" android:label="@string/title_activity_parallaxtoolbarscrollview" android:theme="@style/AppTheme.Toolbar"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="com.androidtutorialpoint.androidobservablescrollview" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>My Activity class names are:-</p> <ol> <li>MainActivity</li> <li>ParallaxToolbarScrollViewActivity</li> </ol>
<p>You placed it in the wrong location it should be inside the application tag. All your <code>&lt;activity... /&gt;</code> tags should be placed under the <code>&lt;application.. /&gt;</code> tag.</p> <p>Hope this helps!</p>
Retrieving running totals from two separate tables <p>I'm trying to perform a running total query based on two tables and I'm a bit stumped. Here is what I have thus far. Firstly let me provide you guys with a DDL of the table and the sample data that I'm using. Table 1</p> <pre><code>create table Actuals ( f_year varchar(02), f_period varchar(02), f_fund varchar(06), f_org varchar(06), f_pror varchar(06), f_trans_amt decimal ); </code></pre> <p>Table 2</p> <pre><code>create table Actuals ( f_year varchar(02), f_period varchar(02), f_fund varchar(06), f_org varchar(06), f_pror varchar(06), f_trans_amt decimal ); GO SET ANSI_PADDING OFF GO INSERT [dbo].[Actuals] ([f_year], [f_period], [f_fund], [f_org], [f_pror], [f_trans_amt]) VALUES (N'07', N'01', N'aaa', N'bbb', N'ccc', CAST(20 AS Decimal(18, 0))) GO INSERT [dbo].[Actuals] ([f_year], [f_period], [f_fund], [f_org], [f_pror], [f_trans_amt]) VALUES (N'07', N'02', N'aaa', N'bbb', N'ccc', CAST(30 AS Decimal(18, 0))) GO INSERT [dbo].[Actuals] ([f_year], [f_period], [f_fund], [f_org], [f_pror], [f_trans_amt]) VALUES (N'07', N'03', N'aaa', N'bbb', N'ccc', CAST(50 AS Decimal(18, 0))) GO INSERT [dbo].[Actuals] ([f_year], [f_period], [f_fund], [f_org], [f_pror], [f_trans_amt]) VALUES (N'07', N'04', N'aaa', N'bbb', N'ccc', CAST(150 AS Decimal(18, 0))) GO GO SET ANSI_PADDING OFF GO INSERT [dbo].[budget] ([f_year], [f_period], [f_fund], [f_org], [f_pror], [f_trans_amt]) VALUES (N'07', N'03', N'aaa', N'bbb', N'ccc', CAST(150 AS Decimal(18, 0))) GO INSERT [dbo].[budget] ([f_year], [f_period], [f_fund], [f_org], [f_pror], [f_trans_amt]) VALUES (N'07', N'06', N'aaa', N'bbb', N'ccc', CAST(150 AS Decimal(18, 0))) GO </code></pre> <p>These are my current results using the following query.</p> <pre><code>with cte_actuals( totalActual, f_year, f_period, f_fund, f_org, f_pror ) as ( select sum(f_trans_amt) over (partition by f_fund,f_org,f_pror order by f_period, f_year ) totalActual, f_year, f_period, f_fund, f_org, f_pror from Actuals), cte_budget ( totalBudget, f_year, f_period, f_fund, f_org, f_pror ) as ( select sum(f_trans_amt) over (partition by f_fund,f_org,f_pror order by f_period, f_year ) totalBudget, f_year, f_period, f_fund, f_org, f_pror from budget) select b.totalBudget, a.totalActual, a.f_year, a.f_period, a.f_fund, a.f_org, a.f_pror From cte_actuals a full outer join cte_budget b on( a.f_fund = b.f_fund and a.f_org = b.f_org and a.f_pror = b.f_pror and a.f_year = b.f_year and a.f_period = b.f_period and a.f_year = b.f_year); </code></pre> <p><a href="https://i.stack.imgur.com/iaSkL.png" rel="nofollow"><img src="https://i.stack.imgur.com/iaSkL.png" alt="enter image description here"></a></p> <p>I'm trying to get these results but I'm having a hard time conceptualizing the solution. <a href="https://i.stack.imgur.com/jSSrf.png" rel="nofollow"><img src="https://i.stack.imgur.com/jSSrf.png" alt="enter image description here"></a></p> <p>My end goal is to join the two running totals into one query but the tables are not are exact match. In other words not every f_period and f_year are in both tables, so I'm left to fill the blanks with the running total from the last period. The picture above shows the end result of what I'm trying to accomplish.</p>
<p>please try this, I joined the tables in cte first, then calculate the running total.</p> <pre><code>;with cte as( select Coalesce(a.f_year, b.f_year) as f_year ,coalesce(a.f_period, b.f_period) as f_period ,coalesce(a.f_fund, b.f_fund) as f_fund ,coalesce(a.f_org, b.f_org) as f_org ,coalesce(a.f_pror, b.f_pror) as f_pror , Coalesce(a.f_trans_amt, 0) as ActualAmount ,coalesce(b.f_trans_amt, 0) as BudgetAmount from Actuals as a full outer join Budget as b on ( a.f_fund = b.f_fund and a.f_org = b.f_org and a.f_pror = b.f_pror and a.f_year = b.f_year and a.f_period = b.f_period and a.f_year = b.f_year) ) select * ,sum(ActualAmount) over (partition by f_fund,f_org,f_pror order by f_period, f_year ) as ActualAmount ,sum(BudgetAmount) over (partition by f_fund,f_org,f_pror order by f_period, f_year ) as BudgetAmount from cte </code></pre>
Arduino mega + esp 8266 sending get request <p>i have a php script which help to store data into google firebase.</p> <p>i am using this url to access my php scipt and input the data: arduino.byethost22.com/FirebaseTest.php?slot1_data=empty&amp;slot2_data=occupied</p> <p>i have tried it and it is able to store slot1_data as empty and slot2_data as occupied. However i need to use arduino to send this url. i am using this code currently</p> <pre><code>#include "SoftwareSerial.h" #define DEBUG false // turn debug message on or off in serial String server = "arduino.byethost22.com"; String uri = "/FirebaseTest.php?slot1_data=empty&amp;slot2_data=occupied"; void setup() { Serial3.begin(115200); //serial3 for esp8266 Serial.begin(115200); sendData("AT+RST\r\n",2000,DEBUG); // reset module sendData("AT+CWMODE=3\r\n",1000,DEBUG); // configure as access point //sendData("AT+CWJAP=\"WifiName\",\"Password\"\r\n",3000,DEBUG); //delay(20000); sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address sendData("AT+CIPMUX=0\r\n",1000,DEBUG); // configure for single connections } void loop() { Serial3.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection. if( Serial3.find("OK")) { Serial.println("TCP connection ready"); } delay(1000); String getRequest = "GET " + uri + " HTTP/1.1\r\n" + "Host: " + server + "\r\n\r\n"; String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent. Serial3.print(sendCmd); Serial3.println(getRequest.length() ); delay(500); if(Serial3.find("&gt;")) { Serial.println("Sending.."); } Serial3.print(getRequest); if( Serial3.find("SEND OK")) { Serial.println("Packet sent"); } while (Serial3.available()) { String tmpResp = Serial3.readString(); Serial.println(tmpResp); } delay(20000); } String sendData(String command, const int timeout, boolean debug) { String response = ""; Serial3.print(command); // send the read character to the esp8266 long int time = millis(); while( (time+timeout) &gt; millis()) { while(Serial3.available()) { // The esp has data so display its output to the serial window char c = Serial3.read(); // read the next character. response+=c; } } //if(debug) //{ Serial.print(response); //} return response; } </code></pre> <p>it seems that it have problem sending the get request to the php script.</p> <p>i am getting packet sent in the serial monitor but nothing changed in the firebase data</p> <p>i am also getting </p> <pre><code>+IPD,1104:HTTP/1.1 200 OK Server: nginx Date: Sat, 15 Oct 2016 09:21:34 GMT Content-Type: text/html Content-Length: 875 Connection: keep-alive Vary: Accept-Encoding Expires: Thu, 01 Jan 1970 00:00:01 GMT Cache-Control: no-cache &lt;html&gt;&lt;body&gt;&lt;script type="text/javascript" src="/aes.js" &gt;&lt;/script&gt;&lt;script&gt;function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&amp;&amp;arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f&lt;d.length;f++)e+=(16&gt;d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("b5ebc3b806c39a4a7fc1e4cecb45feab");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://arduino.byethost22.com/FirebaseTest.php?slot1_data=0&amp;slot2_data=1&amp;i=1";&lt;/script&gt;&lt;noscript&gt;This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support&lt;/noscript&gt;&lt;/body&gt;&lt;/html&gt; </code></pre> <p>It asked me to enable javascript in my browser, but i am using arduino, how do i do it? When i key in the same uri in google chrome, the data can be updated</p> <p>how do i solve this problem?</p>
<p>My code finally can work and send data online. i change to use 000webhost as my host server instead of byethost and the data manage to be updated. </p> <p>i dont really know why but i guess that byethost dont support javascript.</p>
i am creating a canvas drawing apps but i got stock <p>i am creating a canvas drawing apps but i got stock in my code.I am new at javascript so it seems difficult for me to code</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var input = document.getElementById('chColor'); input.onkeyup = function() { document.getElementById('color_check').style.background = input.value; } var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); canvas.addEventListener('mousedown',painting,false); function painting() { canvas.onmousemove = function(e) { var mouseX = e.pageX - canvas.offsetLeft; var mouseY = e.pageY - canvas.offsetTop; ctx.fillStyle = input.value; ctx.fillRect(mouseX,mouseY,10,10); } canvas.onmouseup = function() { canvas.onmousemove = ''; } } var erase = document.getElementById('clear'); erase.onclick = function() { ctx.clearRect(0,0,canvas.width,canvas.height); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background: #dfdfdf; } .colorplate { position: relative; width: 100%; height: 50px; background: #fff; box-shadow: 0px 0px 2px 2px rgba(0,0,0,.3); } #chColor { width: 250px; border:none; background: none; line-height: 50px; font-size: 20px; } #chColor:focus { outline: none; } ::-webkit-input-placeholder { color:#333; } #color_check { position: absolute; width: 250px; height: 100%; background: #fff; box-shadow: 0px 0px 2px 2px rgba(0,0,0,0.3); top:0; left:50%; } canvas { background: #fff; box-shadow: 0px 0px 2px 2px rgba(0,0,0,0.3); } #clear { padding: 10px; border:none; background-color: #fff; box-shadow: 0px 0px 2px 2px rgba(0,0,0,0.3); cursor: pointer; } #clear:hover { background: #333; color:#fff; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="colorplate"&gt; &lt;input type="text" id="chColor" placeholder="type your color name or hex"&gt; &lt;div id="color_check"&gt;&lt;/div&gt; &lt;/div&gt;bbb &lt;canvas id="canvas" width="300" height="300"&gt;&lt;/canvas&gt; &lt;button id="clear"&gt;Erase all&lt;/button&gt;</code></pre> </div> </div> </p> <blockquote> <p>please update some code and make to much beautiful than mine. I hope you will help me for my problem. </p> </blockquote>
<p>You should go this this <a href="http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/" rel="nofollow">link</a>. It will help you.</p> <p>And you just specify that what type of output you should and which types of function you want to use in canvas.</p>
Remove label section from paper-textarea <p>I'd like to remove the extra space that the label takes up in a polymer text-area. Is this possible? Thank you.</p>
<p>I guess there are some default margin on padding. Without code it's hard to say.</p>
Using a integer flag to save radio button status like a boolean <p>I'm using this code to "convert" the status of a Radio Button to a integer in "boolean way"</p> <pre><code>If MyRadioButton.Checked Then cmdConnection.Parameters.AddWithValue("@paramMychoice", 1) Else cmdConnection.Parameters.AddWithValue("@paramMychoice", 0) End If </code></pre> <p>The code works fine</p> <p>Reading the answer of Muhammad Nabeel Arif in this link <a href="http://stackoverflow.com/questions/843780/store-boolean-value-in-sqlite">Store boolean value in SQLite</a></p> <p>he uses</p> <pre><code>int flag = (boolValue)? 1 : 0; </code></pre> <p>But if I try something like</p> <pre><code>Dim flag As Integer flag = (MyRadioButton.Checked)? 1 : 0 </code></pre> <p>I get "option strict on disallows implicit conversions from 'boolean' to 'integer'"</p> <p>Right, I understand and Visual Studio suggest something like flag = CInt((ProtocoloAutorizadaNoRadioButton.Checked))? 1 : 0</p> <p>But I also get the error "The ? character cannot be used here"</p> <p><strong>How can I use the solution of int flag = (boolValue)? 1 : 0 on VB.net?</strong> </p>
<p>Using If</p> <pre><code>Dim flag As Integer flag = if(MyRadioButton.Checked,1, 0) </code></pre> <p><a href="https://msdn.microsoft.com/en-us/library/bb513985.aspx" rel="nofollow">If Operator (Visual Basic)</a></p> <p>Also set explicit and strict to on to your project. (I recommend to set those two default to on in Visual Studio)</p>
Why javascript does not return rounded number <p>```</p> <pre><code>function addTwoDigits(n) { var result; result = Math.floor(n/10) + 10*(n/10-Math.floor(n/10)); console.log(result); return result; } addTwoDigits(29); </code></pre> <p>``` the output was 10.9999999999999999999999999999999 I wonder why it was not 11 since according to normal way of calculation it should be rounded already but it's not. Is there any hidden computer science thoery behind this?</p>
<p>put <strong>Math.round()</strong></p> <pre><code>function addTwoDigits(n) { var result; result = Math.floor(n/10) + 10*(n/10-Math.floor(n/10)); console.log(Math.round(result)); return result; } addTwoDigits(29); </code></pre> <p>Hope this helps.</p>
A strange ConcurrentModificationException on iteration <p><a href="http://stackoverflow.com/questions/16245587/concurrentmodificationexception-on-iterator-next">this</a> is probably the closest case to mine, but that didn't help either.</p> <p>I'm getting the ConcurrentModificationException here:</p> <pre><code>for (Iterator&lt;ProjectileBase&gt; iterator = projectiles.iterator(); iterator.hasNext();) { ProjectileBase proj = iterator.next(); &lt; here if (proj == null || !proj.isValid()) { iterator.remove(); continue; } if (((!proj.ignoreRange()) ? proj.lived &lt;= proj.data.getRange() : true)){ proj.lived++; proj.onTick(); } else { MissileHitEvent event = new MissileHitEvent(proj.shooter, proj.wand, proj, false, null); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { iterator.remove(); continue; } else { proj.lived = 0; } } } </code></pre> <p>Even though I did as suggested <a href="http://stackoverflow.com/a/223929/5498032">here</a> ?</p> <p>The list is specified like this:</p> <pre><code>private List&lt;ProjectileBase&gt; projectiles = new ArrayList&lt;ProjectileBase&gt;(); </code></pre> <p>which is intialized on the class construction. What's the problem?</p> <p><strong>EDIT:</strong> console log:</p> <pre class="lang-none prettyprint-override"><code>[10:01:58] [Craft Scheduler Thread - 3754/WARN]: Exception in thread "Craft Scheduler Thread - 3754" [10:01:58] [Craft Scheduler Thread - 3754/WARN]: org.apache.commons.lang.UnhandledException: Plugin MagicWands v1.0 generated an exception while executing task 247 at org.bukkit.craftbukkit.v1_9_R2.scheduler.CraftAsyncTask.run(CraftAsyncTask.java:57) at com.destroystokyo.paper.ServerSchedulerReportingWrapper.run(ServerSchedulerReportingWrapper.java:22) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.util.ArrayList$Itr.next(Unknown Source) at io.jettymc.DataHolders.ProjectileManager.iterate(ProjectileManager.java:117) at io.jettymc.DataHolders.ProjectileManager$1.run(ProjectileManager.java:232) at org.bukkit.craftbukkit.v1_9_R2.scheduler.CraftTask.run(CraftTask.java:58) at org.bukkit.craftbukkit.v1_9_R2.scheduler.CraftAsyncTask.run(CraftAsyncTask.java:53) ... 4 more </code></pre> <p><strong>EDIT 2:</strong> Well, I guess it's worth telling, I'm building this project on Bukkit/Spigot (Minecraft server &amp; API).. but I doubt it's the cause of this error?</p>
<p>To help narrow down the problem, there is a trick that might help.</p> <p>Assuming <code>projectiles</code> is the only reference to the <code>ArrayList</code>, you can temporarily replace it with an immutable list, while you're iterating, so only the <code>Iterator</code> can modify the list. If some other code tries to modify the list, an exception will occur, which should let you know where it happens, assuming your error handling is not messed up.</p> <p>Example:</p> <pre><code>List&lt;ProjectileBase&gt; projectilesHold = projectiles; projectiles = Collections.unmodifiableList(projectiles); try { for (Iterator&lt;ProjectileBase&gt; iterator = projectilesHold.iterator(); iterator.hasNext();) { // other code here is unchanged } } finally { projectiles = projectilesHold; } </code></pre> <p>The code saves the modifiable list in the "hold" variable, then wraps the list to make it unmodifiable. The <code>finally</code> block will ensure that the modifiable list is restored, no matter what.</p> <p>The <code>for</code> loop iterator was then modified to use the modifiable list in "hold", so its <code>remove()</code> method works, but anywhere else the <code>projectiles</code> field is now unmodifiable for the duration of the iteration.</p> <p>This is for debug only. Once you identify the problem and correct it, remove the logic again.</p>
Array of object is always null in MVC core controller <p>I am trying to post array of a simple object to my MVC core controller with the Frombody attribute, but for some reason it coming as null. If I post just a single object it is working fine here is my code: </p> <pre><code>$(document).ready(function() { var tk = new Array(); $("#calendar").fullCalendar({ header: { left: 'prevYear,prev,next,nextYear', center: 'title', right: 'month,agendaWeek,agendaDay', }, defaultView: 'month', editable: true, alldayslot: false, selectable: true, slotminutes: 15, nextDayThreshold: "00:00:00", events: "/Home/FullCalendar", eventDrop: function(event, delta, revertFunc) { Update(event); }, }); function Update(event) { var datarow = { "id": event.id, "start": event.start, "end": event.end, } tk.push(datarow); debugger; confirm(("Save changes?")) console.log(JSON.stringify(datarow)); $.ajax({ type: "post", dataType: 'json', cache: false, contentType: "application/json; charset=utf-8", data: JSON.stringify(tk), url: '@Url.Action("JSON", "Home")', success: function (data) { debugger; }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); debugger; } }); } }); </code></pre> <p>My Controller class </p> <pre><code>[HttpPost] public IActionResult UpdateTask([FromBody] List&lt;Task_fullcal&gt; td) { // Do something // td is always null if passed as an array //td working fine if passed as single value } </code></pre>
<p>remove FromBody in your action, for complex types the Request will contain complex types in Request body. try use PostMan and try different options.</p> <p>1 pass object in URL , use [FromUri] </p> <p>2 pass object in body ,remove FromBody</p> <p>3 pass simple values like string ,use [FromUri] if you want to access from URL</p> <p>4 pass simple values like string in Request body ,use [FromBody] </p>
save edit text value on changing radio button <p>I have two radio buttons in a radio group and three text edit fields in one layout.</p> <p>Now when I switch radio button I would able to save data of edit text for pervious selected radio button and vice versa </p> <p>Please help me.</p>
<p>You can do using radio group.</p> <pre><code> RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup); radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // checkedId is the RadioButton selected if(checkedId == R.id.radiobutton1) { //get data from edittext and save then clear edit text }else { //get data from edittext and save then clear edit text } } }); </code></pre>
Is there any best practice for packaging MVP layers? <p>I have done some Android applications using MVP methodology,</p> <p>But I am not so sure if it is better to place different layers objects of the same feature in a same package? or package all layers items of different features in the same package with layer name on it?</p> <p>(Which I mean something like this)</p> <p><a href="https://i.stack.imgur.com/AVzF3.png" rel="nofollow"><img src="https://i.stack.imgur.com/AVzF3.png" alt="Packages Screenshot"></a></p> <p>Currently, I am following the second rule, but is this the best practice?</p> <p><strong>Edit</strong>: This is my project's whole packages! :)</p> <p><a href="https://i.stack.imgur.com/xXgxh.png" rel="nofollow"><img src="https://i.stack.imgur.com/xXgxh.png" alt="Packages bigger screenshot"></a></p>
<p>Just to throw my thoughts into the mix. I have worked on projects with each of these approaches. My preference now is to package by feature. There are two main reasons I prefer this approach:</p> <p><strong>Ease of Induction</strong></p> <p>Increased visibility of project structure for developers new to the codebase. When classes which relate to a single feature are grouped together it is much easier for a new team member to quickly see how everything fits together.</p> <p><strong>Restricting Class access</strong></p> <p>This is probably more important. When you package by type (all Presenters together, etc) you have to give many methods in these classes <code>public</code> access. This can lead to these functions being used inappropriately from various areas of the codebase.</p> <p>If you package by feature then these classes are all in the same package and as such you can give the methods package level access. This ensures that methods don't leak.</p>
SQL query to get all rows when there is no matching row in left join <p>I have a table structure like this:</p> <pre><code>person (pid, pname) personSamples(sid,pid,sampleName) groups(gid,groupName) groupPersons(gpid,gid,pid) grouppersonSamples(gpsid,gid,sid) </code></pre> <p>Whenever a person is added to a group (i.e. in <code>groupPersons</code> table), I add some selected samples of person in <code>grouppersonSamples</code> table. </p> <p>The requirement is, if I do not insert any row in <code>grouppersonSamples</code> then select all from <code>personSamples</code> for a given person and group.</p> <p>What I have to do is <em>left join</em> with <code>grouppersonSamples</code> and check if there is no matching row in <code>grouppersonSamples</code> then execute another query to select all from <code>personSamples</code> for given pid.</p> <p>Is there any way to get all in single query?</p>
<p>The following query will give you group-person-samples(gid, sid) for a given person(pid) which are not already present in grouppersonSamples table: </p> <p>Assume pid of the given person is 3. I've not considered the gid of the group in which this person is added. If you wish to consider a specific group, add the gid filter in the following query similar to pid = 3 condition.</p> <pre><code>select T1.gid, T1.sid from (select gid, sid from groupPersons, personSamples where groupPersons.pid = personSamples.pid and groupPersons.pid = 3) as T1 LEFT JOIN (select grouppersonSamples.gid, grouppersonSamples.sid from personSamples, groupPersons, grouppersonSamples where personSamples.pid = 3 and personSamples.pid = groupPersons.pid and grouppersonSamples.gid = groupPersons.gid and grouppersonSamples.sid = personSamples.sid) as T2 ON T1.gid = T2.gid and T1.sid = T2.sid where T2.gid IS NULL; </code></pre> <p>The first query extracts all possible group-person-samples(gid, sid) for given person (say pid = 3) and the second query extracts all group-person-samples(gid, sid) present in grouppersonSamples table for given person.</p> <p>Then the LEFT JOIN works as MINUS operation and gives the group-person-samples(gid, sid) for given person which are not already present in grouppersonSamples table.</p> <p>Also you can use the above query in insert statement as follows:</p> <pre><code>insert into grouppersonSamples(gid, sid) (&lt;above query&gt;); </code></pre> <p>P.S.: I've used LEFT JOIN to perform minus operation as Mysql does not support MINUS operator. You can directly use MINUS operator if your DBS supports it.</p>
How can I exclude package private class using Class Diagram Options? <p>I trying to generate UML Graph with Javadoc using <a href="http://www.spinellis.gr/umlgraph/" rel="nofollow">UMLGraph</a>.</p> <p>I'm searching an option on <a href="http://www.spinellis.gr/umlgraph/doc/cd-opt.html" rel="nofollow">here</a> for excluding my package-private class from being visualized.</p> <pre><code>// package-private // javadoc excludes it. that's ok. // umlgraph keeps it. that's not ok. class SomeBase { } </code></pre> <p>The class is excluded from the Javadoc. But UMLGraph keeps it.</p> <p>How can I, with what option, exclude the class?</p>
<p>I don't see UMLGraph having such an option. Consider adding the <code>@hidden</code> tag to the class's Javadoc comment as documented <a href="http://www.spinellis.gr/umlgraph/doc/cd-opt-spec.html" rel="nofollow">here</a>.</p>
grayscale - how to disable it automatically <p>Many websites in Thailand are now in grayscale, mostly using -webkit-filter: grayscale(100%), filter: grayscale(100%) and so on.</p> <p>I know we can see them in colors as usual, "manually" (in Chrome) by pressing/clicking the F12 > elements > styles and uncheck grayscale filter check-boxes. But this is not a good way if we need to do the procedure on every webpage. </p> <p>So, I tried extensions like CustomBlocker, stylish, stylebot, etc,... with no success. They can css-select but cannot correctly edit/inject/insert/remove on the grayscale filters.</p> <p>I have tried most thing found in google for almost 4 hours with little results. Please help me:</p> <p>How to automatically disable the grayscale filters on any webpages which are using them ?</p> <p>Thank you very much for your helpful insights in advance.</p> <p>p.s. you may try on a website like <a href="http://www.bangkokpost.com/" rel="nofollow">http://www.bangkokpost.com/</a></p>
<p>Though it appears you have already tried this you should create a custom CSS stylesheet that Chrome will use with a plugin like <a href="https://chrome.google.com/webstore/detail/stylish/fjnbnpbmkenffdnngjfgmeleoegfcffe?hl=en" rel="nofollow">Stylish</a> (not sure if there is a built in feature in Chrome).</p> <p>Then you override the <code>filter</code> in the custom stylesheet.</p> <pre><code>* { -webkit-filter: none !important; filter: none !important; } </code></pre> <p>However with the site that you referenced, the whole site is being greyscaled via JavaScript, so in this case all I could do was disable JavaScript in my browser. This makes everything colourful again.</p>
javascript/jquery - hide/show table row if radio buttons checked <p>I am very new to js and jQuery. </p> <p>I have a simple bootstrap table. In two rows, I have radio buttons, one for item 1a and another for item 2a. I have another two rows with classes of price-1 and price-2. I am hiding price-2 initially (class="hidden"), so the only visible row is price-1. </p> <p>I would like to use js or jQuery to show/hide .price-1 and .price-2 depending on which radio is selected. So, if the radio for Item 1a (id="radioItem1) is selected, I want .price-1 (Item 1 row) to be visible and .price-2 (Item 2 row) hidden. If the radio for Item 2a (id="radioitem2) is selected, I want .price-2 (Item 2 row) to become visible and hide .price-1 (Item 1 row). Only one of them should be visible at a time</p> <p>Eventually, I will be making the bootstrap table rows clickable, so if someone clicks on the row (not the radio) it will select the radio. Because of this, if possible, I want the js to look if the radios are actually "checked" (not clicked), as I want to remove any possible human error component where a user can accidentally click twice on a row which will essentially toggle a click event twice. I think the on.click function works great for checkboxes, but not necessarily for radios.</p> <p>How can I accomplish this?</p> <p>HTML:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="selects-1 col-xs-5"&gt; &lt;select id="licenseRegs" class="form-control selectPCs" name="licenseRegs" style="width: 50%;"&gt; &lt;option value="5" selected="selected" prodid="43" price="49.99" productname="product1"&gt;5 &lt;/option&gt; &lt;option value="10" prodid="44" price="99.99" productname="product1"&gt;10 &lt;/option&gt; &lt;option value="15" prodid="56" price="149.99" productname="product1"&gt;15 &lt;/option&gt; &lt;option value="20" prodid="68" price="199.99" productname="product1"&gt;20 &lt;/option&gt; &lt;option value="25" prodid="54" price="299.99" productname="product1"&gt;25 &lt;/option&gt; &lt;option value="50" prodid="45" price="599.99" productname="product1"&gt;50 &lt;/option&gt; &lt;option value="75" prodid="62" price="899.99" productname="product1"&gt;75 &lt;/option&gt; &lt;option value="100" prodid="53" price="1199.99" productname="product1"&gt;100 &lt;/option&gt; &lt;option value="125" prodid="78" price="1499.99" productname="product1"&gt;125 &lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="orderTotal"&gt; &lt;h4&gt;Order Total:&lt;/h4&gt; &lt;table id="tableOrderTotal" class="table tableTotal"&gt; &lt;tbody&gt; &lt;tr class="rowAnnual"&gt; &lt;td&gt;&lt;label class="active"&gt;&lt;input type="radio" id="radioItem1" name="productOptionItem" value="oneYear" checked&gt;&lt;/label&gt;&lt;/td&gt; &lt;td&gt;Item 1a &lt;/td&gt; &lt;/tr&gt; &lt;tr class="row2Annual"&gt; &lt;td&gt;&lt;label&gt;&lt;input type="radio" id="radioItem2" name="productOptionItem" value="twoYear" &gt;&lt;/label&gt;&lt;/td&gt; &lt;td&gt;Item 2a &lt;/td&gt; &lt;/tr&gt; &lt;tr id="addItem1"&gt; &lt;td&gt;Item 1 row&lt;/td&gt; &lt;td class="price-1"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr id="additem2" class="hidden"&gt; &lt;td&gt;Item 2 row&lt;/td&gt; &lt;td class="price-2"&gt;&lt;span class="dollars"&gt;13&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Here is a link to my jsfiddle where I am playing with what I am trying to do. <a href="https://jsfiddle.net/dhs3gphz/6/" rel="nofollow">https://jsfiddle.net/dhs3gphz/6/</a></p>
<p>Here is your solution:<a href="https://jsfiddle.net/dhs3gphz/7/" rel="nofollow">jsFiddle</a></p> <pre><code>$(document).ready(function() { var pricePerRegUnder = 10; var pricePerRegAbove = 12; var licenseRegsSelect = $('#licenseRegs'); function updateTotalPrice() { licenseRegs = parseInt(licenseRegsSelect.val(), 10); var total; if (licenseRegs &lt; 25) { total = licenseRegs * pricePerRegUnder; } else { total = licenseRegs * pricePerRegAbove; } $('.price-1').html(total); } licenseRegsSelect.change(function() { updateTotalPrice(); }); $('.rowAnnual').click(function(){ $(this).find('input').prop('checked', true); if($(this).find('input').attr('id')=='radioItem1'){ $('#addItem1').removeClass('hidden'); $('#addItem2').removeClass().addClass('hidden'); } else{ $('#addItem1').removeClass().addClass('hidden'); $('#addItem2').removeClass('hidden'); } }); updateTotalPrice(); }); </code></pre>
adding validations to data that is imported through excel file <p>I want to import excel sheet data which contains fields like Employee Id,Employee Name,Gender,Phone No in first column and their respective value in second column ,and save the data to database. I used oledb connection to import the excel sheet and then put it in a data table. Now i want to add validation in all the fields like Employee ID should be the required field,Employee Name should be alphabet,phone no should be number before saving it to the database.</p> <p>how can i do the validation??</p>
<p>It's a bit of process. So I am not writing anything for this. The following shows a step by step process to validate and how to import data from spreadsheet:</p> <p><a href="http://stackoverflow.com/questions/6464601/how-to-validate-a-csv-file-before-importing-into-the-database-using-ssis">Validate Data While Importing in Sql Server</a> </p> <p>In this case, you have to create a class to check upon the fields of the spreadsheet. The following should help you to start: </p> <p><a href="http://stackoverflow.com/questions/17840189/importing-an-excel-sheet-and-validate-the-imported-data-with-loosely-coupled">Validate Spreadsheet With C# 1</a></p> <p>This one would be perfect:</p> <p><a href="http://www.dotnetfox.com/articles/import-records-from-excel-sheet-to-sql-server-with-validations-in-Asp-Net-using-C-Sharp-1052.aspx" rel="nofollow">Validate Spreadsheet With C# 2</a></p>
How can i create border box arround dynamic div? <p>I'm using bootstrap 3.</p> <p>here is my html code</p> <pre><code>&lt;div class="border-box"&gt; &lt;div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"&gt; &lt;div class="padding-top"&gt;Record&lt;/div&gt; &lt;div&gt;Record&lt;/div&gt; &lt;div&gt;Record&lt;/div&gt; &lt;div&gt;Record&lt;/div&gt; &lt;div&gt;Record&lt;/div&gt; &lt;/div&gt; &lt;div class="col-lg-9 col-md-9 col-sm-9 col-xs-9"&gt; &lt;div&gt;record1&lt;/div&gt; &lt;div&gt;record2&lt;/div&gt; &lt;div&gt;record3&lt;/div&gt; &lt;div&gt;record4&lt;/div&gt; &lt;div&gt;record5&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>css:</p> <pre><code>.border-box{ border-bottom: 1px solid #ddd; border-top: 1px solid #ddd; border-right: 1px solid #ddd; border-left: 1px solid #ddd; margin-left: 15px; margin-right: 15px; height: 150px; margin-bottom: 15px; margin-top: 30px; </code></pre> <p>}</p> <p>Here I set fix height to the box, but when the content of record5 increases, it goes out of the box. I want to make it work dynamically.</p>
<p>html</p> <pre><code>&lt;div class="border-box"&gt; &lt;div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"&gt; &lt;div class="padding-top"&gt;Record&lt;/div&gt; &lt;div&gt;Record&lt;/div&gt; &lt;div&gt;Record&lt;/div&gt; &lt;div&gt;Record&lt;/div&gt; &lt;div&gt;Record&lt;/div&gt; &lt;/div&gt; &lt;div class="col-lg-9 col-md-9 col-sm-9 col-xs-9"&gt; &lt;div&gt;record1&lt;/div&gt; &lt;div&gt;record2&lt;/div&gt; &lt;div&gt;record3&lt;/div&gt; &lt;div&gt;record4&lt;/div&gt; &lt;div&gt;record5&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>css</p> <pre><code>.border-box{ border-bottom: 1px solid #ddd; border-top: 1px solid #ddd; border-right: 1px solid #ddd; border-left: 1px solid #ddd; margin-left: 15px; margin-right: 15px; height: 150px; margin-bottom: 15px; margin-top: 30px; //this will trigger the overflow overflow-y: scroll; } </code></pre>
Loopback - one-to-many relation between 3 models <p>I'm using IBM API Connect for a Loopback application. I've 3 models - owner, home and room. The relationship is described as follows:</p> <p>OWNER:</p> <ul> <li>an owner might have one or more than one home(s)</li> <li>a home or all of the homes belong to a particular owner</li> </ul> <p>HOME:</p> <ul> <li>a home would have more than one rooms</li> <li>all of the rooms belongs to a particular home</li> </ul> <p>In my case, through API Connect CLI, Owner is an REST exposed model (REST resource) and is supposed to be directly related to the Home model via one-to-many relationship. Home &amp; Room are two models which are not exposed to REST. Home is directly related to Room via one-to-many relationship. Owner and Room are not directly related to each other but is related via Home model.</p> <p>I want to get the HTTP URL in these forms:</p> <pre><code>/owners/{id}/homes/{id}/rooms/{id} </code></pre> <p>to get details of a room for a particular home of the owner</p> <p>I've chosed one-to-many relationship for Owner-Home and Home-Room with respective foreign key. Since its not a many-to-many relationship, I did not use any through model.</p> <p>The URLs that I'm getting doesn't have any Room counterpart :</p> <pre><code>/owners/{id}/homes/{id} </code></pre> <p>Any ideas how can I do that?</p>
<p>I believe you are looking for a function called <code>nestRemoting()</code>.</p> <p>Take your case as an example, you need to call <code>Owner.nestRemoting('homes')</code> in the boot file to enable nest endpoints</p> <p>Details please see our doc: <a href="http://loopback.io/doc/en/lb2/Nested-queries.html" rel="nofollow">http://loopback.io/doc/en/lb2/Nested-queries.html</a></p> <p>In loopback-example-relations I created a branch contains your models and relations, and how to get nest remote apis work, please check: <a href="https://github.com/strongloop/loopback-example-relations/blob/example/nest-relation/server/boot/initNestRelation.js#L3-L4" rel="nofollow">https://github.com/strongloop/loopback-example-relations/blob/example/nest-relation/server/boot/initNestRelation.js#L3-L4</a></p>
Exception Details java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library <blockquote> <p>Exception Details java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library.   at android.support.design.widget.ThemeUtils.checkAppCompatTheme(ThemeUtils.java:34)   at android.support.design.widget.CoordinatorLayout.(CoordinatorLayout.java:184)   at android.support.design.widget.CoordinatorLayout.(CoordinatorLayout.java:178)   at java.lang.reflect.Constructor.newInstance(Constructor.java:422)   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)   at android.view.LayoutInflater.inflate(LayoutInflater.java:492)   at android.view.LayoutInflater.inflate(LayoutInflater.java:394) Copy stack to clipboard</p> </blockquote> <p><strong>My acivity_main.xml is :</strong> </p> <pre><code>&lt;android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;include layout="@layout/content_main" /&gt; &lt;android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" android:src="@android:drawable/ic_dialog_email" /&gt; </code></pre> <p></p> <p>my styles.xml is </p> <pre><code>&lt;!-- Base application theme. --&gt; &lt;style name="AppTheme" parent="Theme.AppCompat"&gt; &lt;!-- Customize your theme here. --&gt; &lt;item name="colorPrimary"&gt;@color/colorPrimary&lt;/item&gt; &lt;item name="colorPrimaryDark"&gt;@color/colorPrimaryDark&lt;/item&gt; &lt;item name="colorAccent"&gt;@color/colorAccent&lt;/item&gt; &lt;/style&gt; &lt;style name="AppTheme.NoActionBar"&gt; &lt;item name="windowActionBar"&gt;false&lt;/item&gt; &lt;item name="windowNoTitle"&gt;true&lt;/item&gt; &lt;/style&gt; &lt;style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /&gt; &lt;style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /&gt; </code></pre> <p></p>
<p>Logcat output is clear, Set your <code>AppTheme</code> to inherit from <code>Theme.AppCompat</code>.</p> <pre><code>&lt;style name="AppTheme" parent="@style/Theme.AppCompat&gt; &lt;/style&gt; </code></pre> <p>You can find this in values file and you can also check manifest file to see what theme your are imposing.</p>
Linux C Network communication program works in debugger but not outside <p>I have two files, server.c and client.c. The server listens for a client request and then replies appropriately (right now just LIST with a static directory is implemented). When the server receives the LIST command, it counts the amount of regular files in the directory specified (which is a static value right now), then sends the client the amount so that it keeps listening until n elements have been received. The server then starts sending the file names to the listening client.</p> <p>This works in theory and when debugging the server but not when I am running both applications normally through the terminal. The client just gets stuck after typing in the LIST command and while the server receives it, it does not continue with sending the amount of items and the names. When, however, running the server in debugging mode in CodeBlocks (though I guess IDE does not matter) and going through the code line by line, everything works exactly as intended. It may be some sort of race condition, but I am unable to resolve it on my own.</p> <p>client.c</p> <pre><code>#include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netinet/in.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;unistd.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #define BUF 1024 #define PORT 8543 int main (int argc, char **argv) { int create_socket; char buffer[BUF]; struct sockaddr_in address; int size; if ((create_socket = socket (AF_INET, SOCK_STREAM, 0)) == -1) { perror("Socket error"); return EXIT_FAILURE; } memset(&amp;address,0,sizeof(address)); address.sin_family = AF_INET; address.sin_port = htons (PORT); const char *addr = "localhost"; inet_aton (addr, &amp;address.sin_addr); if (connect ( create_socket, (struct sockaddr *) &amp;address, sizeof (address)) == 0) { printf ("Connection with server (%s) established\n", inet_ntoa (address.sin_addr)); size=recv(create_socket,buffer,BUF-1, 0); if (size&gt;0) { buffer[size]= '\0'; printf("%s",buffer); bzero(buffer, BUF); } } else { perror("Connect error - no server available"); return EXIT_FAILURE; } do { printf ("Send message: "); fgets (buffer, BUF, stdin); send(create_socket, buffer, strlen (buffer), 0); if(strcmp(buffer, "LIST\n")){ bzero(buffer, BUF); size=recv(create_socket,buffer,BUF-1, 0); if(size &gt;0){ buffer[size] = '\0'; int items = atoi(buffer); printf("%d", items); bzero(buffer, BUF); for(int i = 0; i &lt; items; i++){ size=recv(create_socket,buffer,BUF-1, 0); if(size &gt;0){ buffer[size] = '\0'; printf("%s\n", buffer); } bzero(buffer, BUF); } } } } while (strcmp (buffer, "QUIT\n") != 0); close (create_socket); return EXIT_SUCCESS; } </code></pre> <p>server.c</p> <pre><code>#include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netinet/in.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;unistd.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;dirent.h&gt; #include &lt;errno.h&gt; #include &lt;string&gt; #include &lt;iostream&gt; #define BUF 1024 #define PORT 8543 using namespace std; int main (void) { int create_socket, new_socket; socklen_t addrlen; char buffer[BUF]; int size; struct sockaddr_in address, cliaddress; struct dirent *direntp; DIR *dirp; create_socket = socket (AF_INET, SOCK_STREAM, 0); memset(&amp;address,0,sizeof(address)); address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons (PORT); int yes = 1; if (setsockopt(create_socket, SOL_SOCKET, SO_REUSEADDR, &amp;yes, sizeof(yes)) == -1) { perror("setsockopt"); exit(1); } if (bind ( create_socket, (struct sockaddr *) &amp;address, sizeof (address)) != 0) { perror("bind error"); return EXIT_FAILURE; } listen (create_socket, 5); addrlen = sizeof (struct sockaddr_in); int file_count = 0; struct dirent * entry; dirp = opendir("/home"); while ((entry = readdir(dirp)) != NULL) { /* Only increment counter if item selected is a regular file */ if (entry-&gt;d_type == DT_REG) { file_count++; } } closedir(dirp); while (1) { printf("Waiting for connections...\n"); new_socket = accept ( create_socket, (struct sockaddr *) &amp;cliaddress, &amp;addrlen ); if (new_socket &gt; 0) { printf ("Client connected from %s:%d...\n", inet_ntoa (cliaddress.sin_addr),ntohs(cliaddress.sin_port)); strcpy(buffer,"Welcome, please enter your command:\n"); send(new_socket, buffer, strlen(buffer),0); bzero(buffer, BUF); } do { size = recv (new_socket, buffer, BUF-1, 0); if( size &gt; 0) { if(strcmp(buffer, "LIST\n") == 0){ if ((dirp = opendir("/home")) == NULL) { perror ("Failed to open directory"); return 1; } bzero(buffer, BUF); sprintf(buffer, "%d", file_count); /* Send client the amount of items he is to receive */ send(new_socket, buffer, strlen(buffer),0); bzero(buffer, BUF); while ((direntp = readdir(dirp)) != NULL) /* Check if item is a file and if yes, send client its name */ if (direntp-&gt;d_type == DT_REG){ strcpy(buffer,direntp-&gt;d_name); send(new_socket, buffer, strlen(buffer),0); bzero(buffer, BUF); } while ((closedir(dirp) == -1) &amp;&amp; (errno == EINTR)) ; } } else if (size == 0) { printf("Client closed remote socket\n"); break; } else { perror("recv error"); return EXIT_FAILURE; } } while (strncmp (buffer, "quit", 4) != 0); close (new_socket); } close (create_socket); return EXIT_SUCCESS; } </code></pre>
<p>As <a href="https://stackoverflow.com/users/106104/immibis">immibis</a> pointed out, your code assumes that each individual <code>send</code> corresponds to an individual <code>recv</code>. When you <strong>slowly</strong> step through the code, this assumption turns out to be (accidentally) correct, but when the program runs, multiple <code>send</code>s can be read by a single <code>recv</code>.</p> <p>This is a very common mistake. Thing is, TCP works with streams of data, not individual packets or messages. It's just like reading or writing data to/from a file (as <a href="https://stackoverflow.com/users/106104/immibis">immibis</a> pointed out). The <code>send</code> call puts data in the send buffer, and TCP can decide for itself when to send it. The timing of the arrival at the receiving end depends on when the data was sent and on (often unpredictable) network conditions.</p> <p>The solution is to divide the data stream into chunks (messages) <strong>yourself</strong>. Here are a few ways of doing that:</p> <ul> <li><p>Use fixed length messages - if all messages have a fixed length, the receiver just has to <code>recv</code> the right number of bytes. If there's anything left in the receive buffer after those bytes, then that data already belongs to the next message.</p></li> <li><p>Send the length of the message before each message. If you want to send the string "blah", encode it as "0004blah" or something similar. The receiver will always read the first four bytes (which are 0004) to figure out the number of remaining bytes to read. It will then read the required number of bytes, process the message, and then wait for the next one. It's a robust solution that's also easy to implement.</p></li> <li><p>Use a delimiter. Lines in text files are divided by newline characters (<code>\n</code>). Similarly, you can add a special delimiter byte (or bytes) between messages. For example, you can define that messages always end with a dollar sign ($). Then all the receiver has to do is <code>recv</code> from the socket byte by byte until it receives a dollar sign. Of course if you take this approach, you have to make sure that the body of the messages doesn't contain the delimiter character.</p></li> </ul>
How to use a variable as input for the alignment in JLabel, Java <p>I want to know how to pass variables through the JLabel alignment parameter. For example:</p> <pre><code>String myString = "CENTER"; JLabel label = new JLabel("text", JLabel.myString); </code></pre>
<p>Check the documentation of javax.swing.SwingConstants <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/javax/swing/SwingConstants.java#SwingConstants.0LEFT" rel="nofollow">here</a> and below are the respective values for LEFT, RIGHT, CENTER</p> <pre><code>public static final int LEFT = 2; public static final int RIGHT = 4; public static final int CENTER = 0; </code></pre> <p>You can either take input as integer or convert your string input to these numbers using switch case of if and pass as second parameter to your JLabel constructor <code>JLabel(String text, int horizontalAlignment)</code></p>
Unable to move Unity launcher or Menu Bar in Ubuntu? <p>I have just upgraded my Ubuntu to 16.04 LTS, I want my launcher to be displayed in Mac style i.e. in the bottom of the screen. I tried changing couple of settings but nothing worked for me. Is it possible to achieve it? How? Thanks.</p>
<p>Install <strong>Unity Tweak Tool</strong> in Ubuntu - 16.04 by typing the commands given below (one-by-one) in the terminal :-</p> <pre><code>sudo apt update sudo apt install unity-tweak-tool </code></pre> <p>Then open the Unity Tweak Tool. And click on <strong>Launcher</strong> which is under <strong>Unity</strong> part. Then change <strong>Position</strong> under <strong>Appearance</strong> to <em>Bottom</em> instead of <em>Left</em>. This will change the launcher's position from left to bottom(just like Mac). Another advantage of <strong>Unity Tweak Tool</strong> is that you can use it for doing other customisations/tweaks in Ubuntu. <strong>Unity Tweak Tool</strong> is a great configuration tool for Unity Desktop Environment !</p>
Oracle SQL Case with Condition <p>I have a question regarding Oracle SQL case statement.</p> <p>in the where condition I would like to apply the following condition. if salary_date is null then effective_date should be greater than 01-Jan-2016</p> <p>I have the tried as</p> <pre><code>case when salary_date is null then trunc(effective_date) &gt;= '01-JAN-2016' else null end </code></pre> <p>However the above resulted in </p> <blockquote> <p>ORA-00933: SQL command not properly ended</p> </blockquote> <p>How can I resolve this?</p>
<p>The problem with your code is that SQL interpreter expects to see the value after 'then' keyword, whereas you have a condition clause.</p> <p>Try something like this maybe:</p> <pre><code>case when salary_date is null and trunc(effective_date) &gt;= '01-JAN-2016' then &lt;value you need&gt; else null </code></pre>
paragraph inside a full height flexbox column with wrapping <p>I tried to create a flexbox layout with sticky header and footer. Everything works fine until I turn on the flex-wrap: wrap mode and put a lot of long texts inside my container.</p> <p>Here is the html:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="head"&gt;head&lt;/div&gt; &lt;div class="main"&gt; &lt;h1&gt;Main&lt;/h1&gt; &lt;p&gt;very long text...&lt;/p&gt; &lt;p&gt;very long text...&lt;/p&gt; &lt;p&gt;very long text...&lt;/p&gt; &lt;p&gt;very long text...&lt;/p&gt; &lt;p&gt;very long text...&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here is the css:</p> <pre><code>html, body { margin: 0; padding: 0; overflow: hidden; } .container { display: flex; flex-wrap: wrap; /* &lt; REMOVE THIS AND EVERYTHING WORKS FINE */ flex-direction: column; height: 100vh; border: 1px solid red; } .container &gt; * { border: 1px solid silver; } .container &gt; .main { flex-grow: 1; overflow-y: auto; } </code></pre> <p>Here is the codepen example:</p> <p><a href="http://codepen.io/anon/pen/JRBzdo" rel="nofollow">http://codepen.io/anon/pen/JRBzdo</a></p> <p>I need the auto-wrap ability because I would like to use this css for another parts where the column layout content should be wrapped horizontally. </p> <p>BTW I'm very curious why this happens? Is there any 'official' explanation for this issue? Is it a known bug?</p> <p><em>Edit: I tested with Chrome v53.0.2785.143</em></p>
<p>Set height on main container. It will work fine.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body { margin: 0; padding: 0; width: 100%; overflow: hidden; box-sizing: border-box; } .container { display: flex; flex-wrap: wrap; flex-direction: column; height: 100vh; } .head, .foot { width: 100%; } .container &gt; * { border: 1px solid silver; } .container &gt; .main { width: 100%; height: calc(100vh - 42px); overflow-y: auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="head"&gt;head&lt;/div&gt; &lt;div class="main"&gt; &lt;h1&gt;Main&lt;/h1&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse venenatis, turpis ac dignissim eleifend, sem metus egestas quam, sit amet dictum nulla nulla vel diam. Nunc quam arcu, bibendum sit amet mollis et, suscipit ut erat. Nulla molestie id augue eu tempor. Sed mollis pulvinar libero sed efficitur. Phasellus ullamcorper sit amet elit non rutrum. Vivamus urna ipsum, elementum sed velit et, rhoncus convallis enim. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque vestibulum dapibus nisi, malesuada ultricies lorem tincidunt et. Pellentesque ultrices varius eleifend. Sed tempus sapien in tempor consequat. Aenean suscipit nunc vitae volutpat bibendum. Duis efficitur fermentum justo, sit amet sollicitudin tortor rutrum at. Praesent sit amet feugiat enim.&lt;/p&gt; &lt;p&gt;Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam ut lacus mattis, porttitor est vitae, feugiat felis. In quis volutpat justo. Mauris sed vulputate neque, a accumsan felis. Nunc in mollis nunc, ac feugiat nisl. Mauris tortor ipsum, tristique in lobortis vitae, luctus ut diam. Duis eleifend vel ipsum id finibus. Praesent porttitor et ante a euismod. Phasellus sit amet orci ac purus blandit aliquet. Pellentesque porta mauris ac tortor iaculis pellentesque. Donec in eros in justo pellentesque lobortis. Sed at commodo leo. Mauris a molestie ante. Sed auctor feugiat ante, eget ultrices ex scelerisque eu. Vestibulum sed elit mattis, egestas quam eget, fringilla enim.&lt;/p&gt; &lt;p&gt;Vestibulum mattis posuere dui vel gravida. Cras vestibulum consectetur lorem sit amet rutrum. Proin porttitor, elit a mattis varius, mi lectus sodales ante, quis lobortis nisl nunc accumsan elit. Mauris ac justo nec mi finibus semper. Suspendisse leo diam, venenatis non cursus hendrerit, interdum ac turpis. Interdum et malesuada fames ac ante ipsum primis in faucibus. In dictum non lorem a imperdiet.&lt;/p&gt; &lt;p&gt;Phasellus et imperdiet erat, a semper turpis. Nam accumsan, enim sed egestas pulvinar, neque est suscipit velit, vitae fringilla augue est eget arcu. Fusce laoreet egestas urna venenatis scelerisque. Proin ac ex suscipit, pretium felis eu, dignissim erat. Quisque et metus pellentesque ligula vestibulum feugiat id sit amet purus. Etiam commodo ultricies eros eget consequat. Donec vitae accumsan sapien. Etiam commodo lectus iaculis leo blandit, sed volutpat tortor porttitor. Nunc sit amet imperdiet nunc. Donec est lectus, pharetra eget leo id, sagittis lacinia neque. Fusce finibus ex felis, tristique convallis lacus sodales eget. Ut ornare gravida tristique. Aenean aliquet nisi et auctor egestas.&lt;/p&gt; &lt;p&gt;Suspendisse commodo, mauris nec facilisis porttitor, arcu eros rhoncus dui, scelerisque fringilla tortor eros et mauris. Pellentesque vel justo convallis, posuere justo et, tempor ligula. Curabitur eros urna, lacinia at commodo non, ultrices vitae purus. Donec pellentesque quis ante vitae finibus. Aliquam nec tempor urna. Duis pulvinar enim efficitur mi dictum, rhoncus eleifend dui congue. Fusce auctor mattis neque, eu viverra nisl ultricies ac. Aenean et nisi vulputate quam rutrum faucibus.&lt;/p&gt; &lt;/div&gt; &lt;div class="foot"&gt;foot&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>42px is from head + foot height. (including border)</p> <p>Hope this helps. Cheers</p>
multiple select conditions in php mysqli <p><a href="https://i.stack.imgur.com/1zP0p.png" rel="nofollow">i have table like above</a></p> <p>I want to select and display cost when pickup and droplocation are same as that selected by user from a dropdown having above options.</p> <pre><code>$result = mysqli_query($conn,"SELECT * FROM location WHERE Pickup='". $pick. "' "); while($row = mysqli_fetch_array($result)) { echo "You have to pay " . $row['Cost']; echo "&lt;br&gt;"; } </code></pre> <p>above code will give me 4 options since i haven't checked equality of <code>dropLocation</code>. </p> <pre><code>SELECT * FROM location WHERE Pickup='". $pick. "' AND DropLocation='". $drop. "' " </code></pre> <p>It is not working. How to handle multiple conditions?</p>
<p>Try this </p> <p>your code looks have sql attack vulnerability try to use mysqli prepared statement.</p> <pre><code> &lt;?php $stmt = $conn-&gt;prepare("SELECT * FROM location WHERE Pickup=? AND DropLocation=?"); $stmt-&gt;bind_param('ss',$pick,$drop); //The argument may be one of four types: //i - integer //d - double //s - string //b - BLOB //change it by respectively $stmt-&gt;execute(); $get_result =$stmt-&gt;get_result(); $row_count= $get_result-&gt;num_rows; if($row_count&gt;0) { while($row = mysqli_fetch_array($get_result)) { echo "You have to pay " . $row['Cost']; echo "&lt;br&gt;"; } } else { echo "result set empty"; } $stmt-&gt;close(); $conn-&gt;close(); ?&gt; </code></pre>
python calling variables from another script into current script <p>I'm trying to call a variable from another script into my current script but running into "variable not defined" issues.</p> <p>botoGetTags.py</p> <pre><code>20 def findLargestIP(): 21 for i in tagList: 22 #remove all the spacing in the tags 23 ec2Tags = i.strip() 24 #seperate any multiple tags 25 ec2SingleTag = ec2Tags.split(',') 26 #find the last octect of the ip address 27 fullIPTag = ec2SingleTag[1].split('.') 28 #remove the CIDR from ip to get the last octect 29 lastIPsTag = fullIPTag[3].split('/') 30 lastOctect = lastIPsTag[0] 31 ipList.append(lastOctect) 32 largestIP = int(ipList[0]) 33 for latestIP in ipList: 34 if int(latestIP) &gt; largestIP: 35 largestIP = latestIP 36 return largestIP 37 #print largestIP 38 39 if __name__ == '__main__': 40 getec2Tags() 41 largestIP = findLargestIP() 42 print largestIP </code></pre> <p>So this script ^ correctly returns the value of <code>largestIP</code> but in my other script </p> <p>terraform.py</p> <pre><code> 1 import botoGetTags 8 largestIP = findLargestIP() </code></pre> <p>before I execute any of the functions in my script, terraTFgen.py, I get:</p> <pre><code>Traceback (most recent call last): File "terraTFgen.py", line 8, in &lt;module&gt; largestIP = findLargestIP() NameError: name 'findLargestIP' is not defined </code></pre> <p>I thought that if I import another script I could use those variables in my current script is there another step I should take?</p> <p>Thanks</p>
<p>You imported the module, not the function. So you need to refer to the function via the module:</p> <pre><code>import botoGetTags largestIP = botoGetTags.findLargestIP() </code></pre> <p>Alternatively you could import the function directly:</p> <pre><code>from botoGetTags import findLargestIP largestIP = findLargestIP() </code></pre>
How to join 3 column based on one coumn <p>I would like to compare the first column of three files. if matched, i would like to print the output as 4th column from file2 and 5th column from 2nd column of fil3. If no matches 0 will be added into the 4th and 5th column of the output.</p> <pre><code> file1.txt 123,apple,goodquality 456,orange,mediumquality 678,grape,lowquality 786,kiwi,goodquality file2.txt 123,55 678,2 file3.txt 456,10 output.txt 123,apple,goodquality,55,0 456,orange,mediumquality,0,10 678,grape,lowquality,2,0 </code></pre> <p>I was using join command it works well if the column1 value is availble in all 3 files.</p>
<p>You'll need to join the first 2 files, and then join that output with the 3rd file. You'll need several extra options for join to do an outer join, with 0 as the default field value. Assuming your files are already sorted <em>lexicographically</em> by the first field, then:</p> <pre><code>join -t , -a 1 -a 2 -e 0 -o 0,1.2,2.1 file1.txt file2.txt | join -t , -a 1 -a 2 -e 0 -o 0,1.2,1.3,2.1 - file3.txt </code></pre> <p>outputs</p> <pre><code>123,apple,123,0 456,orange,0,456 678,grape,678,0 786,kiwi,0,0 </code></pre> <p>And if you want to exclude the last line for having 2 zero values, then </p> <pre><code>join -t, -a 1 -a 2 -e 0 -o 0,1.2,2.1 file1.txt file2.txt | join -t, -a 1 -a 2 -e 0 -o 0,1.2,1.3,2.1 - file3.txt | sed '/,0,0$/d' </code></pre>
Push items into array using eventlistener <p>I'm trying to update the array with values once the user clicks on an element in the DOM. The elements seem to be pushed into the array inside the anonymous function but outside the function the array is still empty. How can I fix that? Here is the javascript code:</p> <pre><code>function getSelection() { var selections = []; var container = document.getElementById("main-container"); var choices = document.querySelectorAll('li'); choicesLength = choices.length; for(var i = 0; i &lt; choicesLength; i++) { choices[i].addEventListener("click", function(){ var position = this.getAttribute("value"); selections.push(position); // logs array and updates with each click console.log(selections); }); } // logs empty array console.log(selections); } </code></pre> <p>Basically, after the items are clicked, the main array needs to be updated with what they clicked. </p> <p>Any help would be appreciated. </p> <p>Thanks </p>
<p>The function you pass to <code>addEventListener</code> won't run until the event happens.</p> <p>It isn't possible for you to click any of the list items before the <code>console.log</code> that runs immediately after the assignment fires.</p> <blockquote> <p>Basically, after the items are clicked, the main array needs to be updated with what they clicked.</p> </blockquote> <p>… and that is what will happen. Look at the results of the <code>console.log</code> inside the click handler.</p>
How to increase the width of "float:left"-elements when an element goes down to next line? <p>I want to create a footer with 4 columns (sections). Each section has these styles:</p> <pre><code>.footer-sections { width:24%; min-width: 140px; float:left; } </code></pre> <p><a href="https://i.stack.imgur.com/Lu8cn.png" rel="nofollow"><img src="https://i.stack.imgur.com/Lu8cn.png" alt="grey=browser-window;black=footer;blue=sections"></a></p> <p>As you can see, it is a responsive design I want to do. When the width of the browser window becomes small, the rightmost section will get down to the next line. <a href="https://i.stack.imgur.com/PJ81l.png" rel="nofollow"><img src="https://i.stack.imgur.com/PJ81l.png" alt="when width decreases - 1"></a> <a href="https://i.stack.imgur.com/7CS0l.png" rel="nofollow"><img src="https://i.stack.imgur.com/7CS0l.png" alt="when width decreases - 2"></a></p> <p>This is what will happen, but this is NOT what I want to accomplish.</p> <p>My goal is to make the width of the sections as large as possible. What I want is:<a href="https://i.stack.imgur.com/KAj25.png" rel="nofollow"><img src="https://i.stack.imgur.com/KAj25.png" alt="enter image description here"></a></p> <p>The problem is that I don't find any way to do this without using JavaScript. I want to accomplish this with only HTML and CSS. </p> <p>I've tried the <code>width:auto</code>, but it doesn't work as desired.</p> <p>I can't think of any way around. Could you please lend me a helping hand on this? Any suggestions for solutions?</p>
<p>I think a media query will be needed here. Here is what I would do:</p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="footer-sections"&gt; &lt;p&gt;SECTION1&lt;/p&gt; &lt;/div&gt; &lt;div class="footer-sections"&gt; &lt;p&gt;SECTION2&lt;/p&gt; &lt;/div&gt; &lt;div class="footer-sections"&gt; &lt;p&gt;SECTION3&lt;/p&gt; &lt;/div&gt; &lt;div class="footer-sections footer-sections-special"&gt; &lt;p&gt;SECTION4&lt;/p&gt; &lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.footer-sections { width:25%; float:left; } @media only screen and (max-width: 800px) { .footer-sections { width: 33.33%; } .footer-sections-special { width: 100%; } } </code></pre> <p>First of all I would set the initial width to 25% instead of 24%. The trick is to add an additional class to the right column to make it full width due to a media query. In my case I chose a breakpoint at 800px (of course that's up to you) to span the right column to <code>width: 100%</code> and the other columns to <code>width: 33,33%</code> to evenly split the screen as soon as it gets smaller. In my CSS I removed your style <code>min-width: 140px</code> of class "footer-sections" because this will destroy the markup at really small screen sizes.</p> <p>Hope I could help :)</p>
rdd to json in spark and scala <p>I take a Json file with spark/scala and i save it in a rdd.</p> <pre><code> val dataFile = "resources/tweet-json/hello.json" lazy val rdd = SparkCommons.sqlContext.read.format("json").load(dataFile) </code></pre> <p>After quering rdd, i want to generate again a Json output file (that i will send with a get Http request). How can i convert this rdd in json?</p> <pre><code>[ { "label": [ "fattacq_an_eser_facq", "eu_tot_doc", "fattacq_prot_facq", "id_sogg", "eu_tot_man" ], "values": [ { "label": "Prima Fattura 2016", "values": [ 2016, 956.48, 691, 44633, 956.48 ] }, { "label": "Seconda Fattura 2016", "values": [ 2016, 190, 982, 38127, 190 ] }, { "label": "Terza Fattura 2016", "values": [ 2016, 140.3, 1088, 59381, 140.3 ] }, { "label": "Quarta Fattura 2016", "values": [ 2016, 488, 1091, 59382, 488 ] }, { "label": "Quinta Fattura 2016", "values": [ 2016, 11365.95, 1154, 57526, 11365.95 ] }, { "label": "Sesta Fattura 2016", "values": [ 2016, 44440.01, 1276, 5555, 44440.01 ] } ] } </code></pre> <p>]</p>
<p>You can simply use the write function to write out the Json Example:</p> <pre><code>dfTobeSaved.write.format("json").save("/root/data.json") </code></pre> <p>I think this should work fine !</p>
Go to Definition (jump to CSS file) <p>I am using Visual Studio Code and I really love this editor for working on HTML pages. Nevertheless I am looking for a way to jump to the corresponding CSS file when I select the class or id node. Did I miss something or is this still not working?</p>
<p>Features like this are implemented in extensions. So if the HTML support extension you have installed supports providing locations of CSS rules to Visual Studio then it will allow you to jump to that location. If not then not.</p> <p>I haven't looked for HTML extensions, but it could be there are several in the VS code market place. See if if one of them supports CSS as well (which makes it likely that they also report CSS rule locations to VS code).</p>
Calculating Exponential Moving Average (EMA) using javascript <p>Hi Is possible to calculate EMA in javascript?</p> <p>The formula for EMA that I'm trying to apply is this</p> <blockquote> <p>EMA = array[i] * K + EMA(previous) * (1 – K)</p> </blockquote> <p>Where K is the smooth factor:</p> <blockquote> <p>K = 2/(N + 1)</p> </blockquote> <p>And N is the Range of value that I wanna consider</p> <p>So if I've an array of value like this, and this value grow during the times:</p> <pre><code>var data = [15,18,12,14,16,11,6,18,15,16]; </code></pre> <p>the goal is to have a function, that return the array of the EMA, because any of this value, expect the very fist "Range" value, have this EMA, for each item on data, I've the related EMA value. In that way I can use all or use only the last one to "predict" the next one.</p> <pre><code>function EMACalc(Array,Range) { var k = 2/(Range + 1); ... } </code></pre> <p>I can't figure out how to achieve this, any help would be apreciated</p>
<p>I don't know if I completely understood what you need, but I will give you the code for a function that returns an array with the EMA computed for each index > 0 (the first index doesn't have any previous EMA computed, and will return the first value of the input).</p> <pre><code>function EMACalc(mArray,mRange) { var k = 2/(mRange + 1); // first item is just the same as the first item in the input emaArray = [mArray[0]]; // for the rest of the items, they are computed with the previous one for (var i = 1; i &lt; mArray.length; i++) { emaArray.push(mArray[i] * k + emaArray[i - 1] * (1 - k)); } return emaArray; } </code></pre> <p>This should do it.</p>
Spring Batch process XMl message from MQ (IBM Websphere) <p>I am new to spring batch. I have a message xml in MQ i want to process this message through Spring batch. can we integrate spring batch to MQ directly? or with the help of Camel ?</p>
<p>Take a look at the <a href="http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/item/jms/JmsItemReader.html" rel="nofollow"><code>JmsItemReader</code></a>. It will read via JMS Template.</p>
How to Digitalley sign a pdf document in the server using USB token in the client's system? <p>I need to digitally sign the PDF document in our server using digital certificate in the usb token. How this can be achieved? Is there any library/api for this? I tried to access the certificates in the browser as suggested in this <a href="https://developer.ibm.com/answers/questions/171601/how-do-i-code-an-application-to-pull-the-client-ce.html" rel="nofollow">link</a></p> <pre><code> java.security.cert.X509Certificate certChain [] = (java.security.cert.X509Certificate [])request.getAttribute ("javax.net.ssl.peer_certificates"); </code></pre> <p>But it is not giving any result. I'm using java. I tried accessing key-store,but it is returning the servers certificates instead of client's certificates. How can i access the client's certificates? </p>
<p>The link is for SSL authentication, not digital signature. You need a local java application to access USB token and a PDF library like itext or pdfbox. </p> <p>Itis not possible from browser (except using applets with IE / firefox and old versions of JRE plugin. I do not recommend it). See <a href="http://stackoverflow.com/questions/38605661/javascript-key-certificate-from-usb-token/38607119#38607119">this</a> and some alternatives <a href="http://stackoverflow.com/a/40014020/6371459">here</a></p>
Django, viewing models from different app <p>I am super new to python programming and django and i got the basics out of the way. I created a project with two apps, home and video. In my video models.py i have the following data:</p> <pre><code>class Video(models.Model): name = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) </code></pre> <p>I want to do something with this in my home app in the views.py, such as display the data in an html page and currently it is set up as followed:</p> <pre><code>from video.models import Video def display_video(request): video_list = Video.objects.all() context = {'video_list': video_list} return render(request, 'home/home.html', context) </code></pre> <p>in my home.html</p> <pre><code>{% if video_list %} {% for video in video_list %} &lt;p&gt;{{ video.name }}&lt;/p&gt; &lt;p&gt;{{ video.description }}&lt;/p&gt; {% endfor %} {% else %} &lt;p&gt;no videos to display&lt;/p&gt; {% endif %} </code></pre> <p>my home.html always returns "no videos to display"</p> <p>But when i query Video.objects.all() in my video app it finds 2 objects. any help is appreciated.</p>
<p>In settings, check the following is there.</p> <pre><code>TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] </code></pre>
About inheritance of java <p>/** * Created by zhangzhongzheng on 2016/10/15. */</p> <p>public class ExtendsTest {</p> <pre><code>static Dog d = new Dog(); public static void main(String[] args) { Animal a = d; System.out.println(a instanceof Animal);//true System.out.println(a instanceof Dog);//true System.out.println(d instanceof Animal);//true System.out.println(d instanceof Dog);//true } static class Animal { } static class Dog extends Animal { } </code></pre> <p>}</p> <p>why all true??????</p>
<p>Here Animal is a Parent and Dog is a child.</p> <p>Parent class reference can hold child class object.</p> <p>Animal animal = new Dog();</p> <p>So all above conditions are true.</p>
Automation of Windows Phone Application with Selenium and Appium <p>I have an android application. I have automated it with Selenium and Appium. I wrote the scripts in Java language.</p> <p>Now I want to automate the same application in Windows Phone platform. AFAIK, <em>Appium supports Android and IOS platform only.</em> </p> <p>Is there any way I can automate Windows Phone application so that I can reuse the same test automation suite I built for Android application? Specifically I want one test suite that will test both android and windows phone application by changing only properties or something else those are concerned. </p> <p><strong>Note:</strong> I found an open source framework <a href="https://github.com/2gis/Winium" rel="nofollow">Winium</a>. Though it automates windows application, I would not prefer it because I can not reuse my test automation suite I built for Android application. I just don't want to write same scripts again, rather reusing the scripts.</p>
<p>You can not automate Windows Phone application with Appium. You can try Xamarin (not open source).</p>
Regex to match everything except image name and extension <p>I have this regex <code>((?:https?\:\/\/)(?:[a-zA-Z]{1}(?:[\w\-]+\.)+(?:[\w]{2,5}))(?:\:[\d]{1,5})?\/(?:[^\s\/]+\/)*(?:[^\s]+\.(?:png|jpe?g|gif|svg|PNG|JPE?G|GIF|SVG))(?:\?\w+=\w+(?:&amp;\w+=\w+)*)?)</code></p> <p>to select these image urls from a string</p> <p><code>http://my.a.example.com/kf/urjlsjjsXVXXq6xXFXXX6/20jaa/jajc1agiCJFXXXXb8XVXXq6xXFXXX6.jpg?size=158385&amp;height=79&amp;width=50&amp;hash=13e12eaa837ae8341e35cbde5ea544a</code></p> <p><code>https://example.com/imhgegg.png</code></p> <p>What I wanted is to match everything except <code>jajc1agiCJFXXXXb8XVXXq6xXFXXX6.jpg</code> and <code>mhgegg.png</code> ie image name and extension.</p> <p>Please can that be achieved?</p> <h2>EDIT</h2> <p>I actually get this link from a json file I fetch online. What I really want to do is :</p> <pre><code>String regex; //regex to match everything except image name and extension. String imageName = IMAGEURL.replaceAll(regex, "") </code></pre> <p>So if I log <code>imageName</code>, I want to get <code>jajc1agiCJFXXXXb8XVXXq6xXFXXX6.jpg</code> and <code>mhgegg.png</code></p>
<p>Or if you just don't care whether or not you use RegEx:</p> <p><strong>Required imports:</strong></p> <pre><code>import java.io.File import java.net.MalformedURLException; import java.net.URL; </code></pre> <p>The code:</p> <pre><code>URL url = new URL("http://my.a.example.com/kf/urjlsjjsXVXXq6xXFXXX6/20jaa/jajc1agiCJFXXXXb8XVXXq6xXFXXX6.jpg?size=158385&amp;height=79&amp;width=50&amp;hash=13e12eaa837ae8341e35cbde5ea544a"); try { String fileName = new File(url.getPath()).getName(); String urlWithNoFileName = url.toString().replace(fileName, ""); System.out.println("File Name within URL is: " + fileName); System.out.println("URL with File Name removed:\n" + urlWithNoFileName); } catch (MalformedURLException ex) { //Do what you want with Exception. } </code></pre> <p>A bit more overhead but it does work and it works for file names with no extension.</p>
Java: return previous value of field <p>i start learn java and i have a little problem:</p> <p>I have a class <code>Point</code>:</p> <pre><code>public class Point { int x; int y; void setX(Point point){ x=point.x; } void setY(Point point){ y=point.y; } } </code></pre> <p>Now i have a task:</p> <p>" change method <code>setX()</code> and <code>setY()</code> that these methods return previous values of <code>x</code> and <code>y</code>. "</p> <p>Can You help me with understanding of this task? Totally dont get it.</p>
<p>You'd have to change from <code>void</code> to <code>int</code> return type(s) and then store the old value to return after you set it. Something like,</p> <pre><code>int setX(Point point) { int old = this.x; this.x = point.x; return old; } int setY(Point point) { int old = this.y; this.y = point.y; return old; } </code></pre> <p><strong>or</strong> you <em>might</em> perform the assignment in a <code>finally</code> block, and return the value in a <code>try</code> like</p> <pre><code>int setX(Point point) { try { return this.x; } finally { this.x = point.x; } } </code></pre>
Java Array Loop to Display different noCourse <p>I already writing a coding to accept noSem and noCourse from users. Each semester there will be a different noCourse. My problem is, I only can display data if users enter the same value of noCourse. I want it to show different between the Semester. </p> <p>Here some output : <a href="https://i.stack.imgur.com/HplSQ.png" rel="nofollow">I seems the loop is working, but the data is null because cant access the specific course between semester</a></p> <p>Here some of my coding : </p> <pre><code>class studentCourse { int noCourse, noSem; void course() { BufferedReader inData = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("Enter no of semester : "); noSem = Integer.parseInt(inData.readLine()); String[][] sbjName = new String[noSem][]; String[][] courseCode = new String[noSem][]; int[][] CHour = new int[noSem][]; int[][] Marks = new int[noSem][]; // Semester loop for(int i = 0; i &lt; noSem; i++) { System.out.println("\n\tSemester" + (i + 1)); System.out.print("Enter number of course : "); noCourse = Integer.parseInt(inData.readLine()); sbjName[i] = new String[noCourse]; courseCode[i] = new String[noCourse]; CHour[i] = new int[noCourse]; Marks[i] = new int[noCourse]; // course details loop for(int u = 0; u &lt; noCourse; u++) { System.out.print("Enter Course Code : "); courseCode[i][u] = inData.readLine(); System.out.print("Enter Course Name : "); sbjName[i][u] = inData.readLine(); System.out.print("Enter Credit Hour : "); CHour[i][u] = Integer.parseInt(inData.readLine()); System.out.print("Enter Marks : "); Marks[i][u] = Integer.parseInt(inData.readLine()); System.out.println("\n"); } } for(int row = 0; row &lt; noSem; row++) { System.out.println("\nResult Semester " + (row + 1)); System.out.println("Course Code\t Course Name\t Credit Hour\t Marks\n"); courseCode[row] = new String[noCourse]; for(int col = 0; col &lt; noCourse; col++) { // display course code System.out.print("Value row = " + row); System.out.print("Value of col = " + col); System.out.print(courseCode[row][col] + "\t"); System.out.print("\n"); } /* // display subject name for(int x = 0; x &lt; 1; x++) { for(int y = 0; y &lt; sbjName[x].length; y++) { System.out.print(sbjName[x][y] + "\t"); } } // display credit hour for(int x = 0; x &lt; CHour.length; x++) { for(int y = 0; y &lt; CHour[x].length; y++) { System.out.print(CHour[x][y] + "\t"); } } // display marks for(int x = 0; x &lt; Marks.length; x++) { for(int y = 0; y &lt; Marks[x].length; y++) { System.out.print(Marks[x][y]); } } */ } } catch (ArrayIndexOutOfBoundsException Aobj) { System.out.println("Could not access the index!" ); } catch (Exception Eobj) {} } } </code></pre>
<ol> <li><p>You have re-initialized <code>courseCode</code> before displaying the results from it. Remove this line of code</p> <p>courseCode[row] = new String[noCourse];</p></li> </ol> <p>before displaying your results and everything will work fine.</p> <ol start="2"> <li>The variable noCourse might different for each of the semesters. This means using the variable to get your results is error prone. Instead, use the length of any of arrays, e.g. courseCode to fetch your result:</li> </ol> <blockquote> <pre><code>for(int row = 0; row &lt; courseCode.length; row++) { System.out.println("\nResult Semester " + (row + 1)); System.out.println("Course Code\t Course Name\t Credit Hour\t Marks\n"); for(int col = 0; col &lt; courseCode[row].length; col++) { System.out.print(courseCode[row][col] + "\t"); System.out.print(sbjName[row][col] + "\t"); System.out.print(CHour[row][col] + "\t"); System.out.print(Marks[row][col] + "\t"); System.out.print("\n"); } } </code></pre> </blockquote>
Set last tableView cell as constant cell among variable cells in Swift <p>As the title says, I would like to create a cell which is constant in a tableView where cells are variable. I want this cell to be the last. Actually, all my cells are created with data from Firbase. The last constant cell should be always there. Thx for the help.</p>
<p>Yes, you can achieve it many ways.</p> <p>This is my approach for it. I will create new tableview section for it. Where I will keep the number of rows as one always. In cell for row at indexpath I will check the condition for that section and will return the corresponding constant cell.</p>
Is it good practice to insert blank lines into HTML code? <p>For example, to break up code into chunks for readability/maintainability, or is there a better method? e.g: </p> <pre><code>&lt;div class="list"&gt; &lt;p class="list-item"&gt;Lorem ipsum&lt;/p&gt; &lt;p class="list-author"&gt;Jane Doe&lt;/p&gt; &lt;p class="list-item"&gt;Another lorem ipsum&lt;/p&gt; &lt;p class="list-author"&gt;John doe&lt;/p&gt; &lt;/div&gt; </code></pre>
<p>If you want to follow Coding Conventions, you can follow this link... <a href="http://www.w3schools.com/html/html5_syntax.asp" rel="nofollow">From WcSchool</a></p> <p>So don't put unnecessary blank space and as well as put necessary space to improve readability and maintainability. </p>
How to use service in angular2 NgModule <p>I have written I service and send get request.But working good with angular2 rc4.I am using angular2 rc5.It is giving error.I am using rc5 NgModule.</p> <p>I am getting the following error.Please help me</p> <pre><code>"Error: DI Exception↵ originalStack: "Error: DI Exception↵ at NoProviderError.BaseException [as constructor] </code></pre> <p><a href="https://i.stack.imgur.com/mAssb.png" rel="nofollow"><img src="https://i.stack.imgur.com/mAssb.png" alt="enter image description here"></a></p> <h2>gridview.service.ts</h2> <pre><code>import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { HTTP_PROVIDERS } from '@angular/http'; import { HttpClient } from '../../shared/http/base.http'; import { URL_CONFIG } from '../../base/app.config'; import 'rxjs/add/operator/map'; @Injectable() export class ItemService { constructor (private httpClient: HttpClient) { this.loadItems(); } loadItems() { return this.httpClient.get('url') .map(res =&gt; res.json()); } } </code></pre> <h2>gridview.module.ts</h2> <pre><code>import { NgModule } from '@angular/core'; import { disableDeprecatedForms, provideForms } from '@angular/forms/index'; import { CommonModule } from '@angular/common'; import { bootstrap } from '@angular/platform-browser-dynamic'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { routing } from './gridview.routes' import { GridViewComponent } from './gridview.component' import { HttpClient } from '../../shared/http/base.http'; import { ItemService } from './gridview.service' import { HTTP_PROVIDERS, HttpModule } from '@angular/http'; import { EventService } from '../../shared/service/event-service'; import {RouterModule, provideRouter} from "@angular/router"; import { URL_CONFIG } from '../../base/app.config'; @NgModule({ imports: [ BrowserModule,CommonModule, FormsModule,HttpModule,routing ], declarations: [ GridViewComponent,], exports: [ GridViewComponent ], providers: [ ItemService ] }) export class GridviewModule { } </code></pre> <h2>gridview.component.ts</h2> <pre><code>import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { ItemService } from './gridview.service'; import { FieldFilter } from '../../shared/pipes/fieldfilter.pipe'; import { ROUTER_DIRECTIVES } from '@angular/router'; import { GridviewModule } from './gridview.module' @Component({ moduleId: module.id, selector: 'blank-page', templateUrl: 'gridview.component.html', styleUrls: ['gridview.component.css'], encapsulation: ViewEncapsulation.None, directives: [ ROUTER_DIRECTIVES ] }) export class GridViewComponent implements OnInit { items:string[] = []; constructor(private itemService:ItemService) { // breaks when removed from here. // Also breaks when declared as a class variable } ngOnInit() { this.itemService.loadItems() .subscribe((resp) =&gt; { this.items = resp.data; console.log("This is NgModule Data",this.items) }); } } </code></pre>
<p>import HttpClient in your gridview.module.ts</p> <pre><code>import { HttpClient } from '../../shared/http/base.http'; </code></pre> <p>and define HttpClient in providers of gridview.module.ts</p> <pre><code>providers: [ ItemService, HttpClient ] </code></pre> <p>See if this helps.</p>
HOW TO DISABLE SUBPAGE LISTING IN GOOGLE SEARCH <p>Google search page:</p> <p><img src="https://i.stack.imgur.com/IuhIl.png" alt="Google search page"></p> <p>How to hide the sub page (sitelinks) listing in google search results website.. that is shown in the above picture </p>
<p>By default Google shows sitelink, we have very little control over it but we always have the permission to block sitelinks which we don’t want to show in search result. Make sure to check if there is any unwanted pages are shown in your sitelink. </p> <ul> <li>Login to your Google Search console tool dashboard</li> <li>Click on Search Appearance > Sitelinks</li> <li>Add link to page which you want to remove from sitelink index</li> <li>Click on Demote and your sitelink will be removed in some time.</li> </ul> <p>Always remember this demotion is temporory and after few months, depending on your site structure Google may re-add that link and you need to refollow the above procedure to get rid of unwanted sitelinks from search.</p> <p>Follow below link for demoting/removing sitelinks:</p> <ul> <li><a href="https://support.google.com/webmasters/answer/47334?hl=en" rel="nofollow">Demote sitelinks google search results</a></li> <li><a href="https://youtu.be/9PIqkWPXU2M" rel="nofollow">How to remove google sitelinks fora domain</a></li> </ul>
Neon intrinsic code not boosting performance compared to C code <p>I have a simple C code that subtracts 'num' no. of values from two different pointers and writes back into a third pointer. I tried the same code using neon intrinsics to boost the performance, but am unable to see any reduction in the code execution time. I am using ARM Cortex-A9 processor. </p> <p>Below is my C code:</p> <pre><code>int code_c(uint8_t *in1, uint8_t *in2, uint8_t *out, uint32_t num) { uint32_t i; for(i = 0; i &lt; (num); i++) { out[i] = in1[i] - in2[i]; } return 0; } </code></pre> <p>The corresponding neon intrinisic code is as follows:</p> <pre><code>#include &lt;arm_neon.h&gt; int code_neon(uint8_t * __restrict in1, uint8_t * __restrict in2, uint8_t * __restrict y, uint32_t num) { uint32_t i; uint8x8_t s1, s2; uint8x8_t out; num = num/8; for (i = num; i != 0; i--) { s1 = vld1_u8(in1); s2 = vld1_u8(in2); out = vsub_u8(s1, s2); vst1_u8(y, out); in1+=8; in2+=8;y+=8; __builtin_prefetch(in1+8); __builtin_prefetch(in2+8); } return 0; } </code></pre> <p>What's going wrong here?</p> <p>The generated assembly code for Neon :</p> <pre><code>00000000 &lt;code_neon(unsigned char*, unsigned char*, unsigned char*, unsigned int)&gt;: 0: e92d4008 push {r3, lr} 4: e52de004 push {lr} ; (str lr, [sp, #-4]!) 8: ebfffffe bl 0 &lt;__gnu_mcount_nc&gt; 8: R_ARM_CALL __gnu_mcount_nc c: e1b031a3 lsrs r3, r3, #3 10: 0a00000d beq 4c &lt;code_neon(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x4c&gt; 14: e280e008 add lr, r0, #8 18: e281c008 add ip, r1, #8 1c: f460070f vld1.8 {d16}, [r0] 20: e2533001 subs r3, r3, #1 24: e1a0000e mov r0, lr 28: e28ee008 add lr, lr, #8 2c: f461170f vld1.8 {d17}, [r1] 30: e1a0100c mov r1, ip 34: e28cc008 add ip, ip, #8 38: f5def000 pld [lr] 3c: f34008a1 vsub.i8 d16, d16, d17 40: f5dcf000 pld [ip] 44: f442070d vst1.8 {d16}, [r2]! 48: 1afffff3 bne 1c &lt;code_neon(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1c&gt; 4c: e3a00000 mov r0, #0 50: e8bd8008 pop {r3, pc} </code></pre> <p>The assembly code for C :</p> <pre><code>00000000 &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)&gt;: 0: e92d43f8 push {r3, r4, r5, r6, r7, r8, r9, lr} 4: e52de004 push {lr} ; (str lr, [sp, #-4]!) 8: ebfffffe bl 0 &lt;__gnu_mcount_nc&gt; 8: R_ARM_CALL __gnu_mcount_nc c: e3530000 cmp r3, #0 10: 0a0000f1 beq 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 14: e282c010 add ip, r2, #16 18: e280e010 add lr, r0, #16 1c: e152000e cmp r2, lr 20: 3150000c cmpcc r0, ip 24: e2814010 add r4, r1, #16 28: 23a0e001 movcs lr, #1 2c: 33a0e000 movcc lr, #0 30: e1520004 cmp r2, r4 34: 3151000c cmpcc r1, ip 38: 23a0c001 movcs ip, #1 3c: 33a0c000 movcc ip, #0 40: e00cc00e and ip, ip, lr 44: e3530013 cmp r3, #19 48: 93a0c000 movls ip, #0 4c: 820cc001 andhi ip, ip, #1 50: e35c0000 cmp ip, #0 54: 0a0000e2 beq 3e4 &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3e4&gt; 58: e200c007 and ip, r0, #7 5c: e26cc000 rsb ip, ip, #0 60: e20cc00f and ip, ip, #15 64: e15c0003 cmp ip, r3 68: 21a0c003 movcs ip, r3 6c: e35c0000 cmp ip, #0 70: 0a000059 beq 1dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1dc&gt; 74: e5d0e000 ldrb lr, [r0] 78: e35c0001 cmp ip, #1 7c: e5d14000 ldrb r4, [r1] 80: e064e00e rsb lr, r4, lr 84: e5c2e000 strb lr, [r2] 88: 0a000053 beq 1dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1dc&gt; 8c: e5d0e001 ldrb lr, [r0, #1] 90: e35c0002 cmp ip, #2 94: e5d14001 ldrb r4, [r1, #1] 98: e064e00e rsb lr, r4, lr 9c: e5c2e001 strb lr, [r2, #1] a0: 0a00004d beq 1dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1dc&gt; a4: e5d0e002 ldrb lr, [r0, #2] a8: e35c0003 cmp ip, #3 ac: e5d14002 ldrb r4, [r1, #2] b0: e064e00e rsb lr, r4, lr b4: e5c2e002 strb lr, [r2, #2] b8: 0a000047 beq 1dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1dc&gt; bc: e5d0e003 ldrb lr, [r0, #3] c0: e35c0004 cmp ip, #4 c4: e5d14003 ldrb r4, [r1, #3] c8: e064e00e rsb lr, r4, lr cc: e5c2e003 strb lr, [r2, #3] d0: 0a000041 beq 1dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1dc&gt; d4: e5d0e004 ldrb lr, [r0, #4] d8: e35c0005 cmp ip, #5 dc: e5d14004 ldrb r4, [r1, #4] e0: e064e00e rsb lr, r4, lr e4: e5c2e004 strb lr, [r2, #4] e8: 0a00003b beq 1dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1dc&gt; ec: e5d0e005 ldrb lr, [r0, #5] f0: e35c0006 cmp ip, #6 f4: e5d14005 ldrb r4, [r1, #5] f8: e064e00e rsb lr, r4, lr fc: e5c2e005 strb lr, [r2, #5] 100: 0a000035 beq 1dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1dc&gt; 104: e5d0e006 ldrb lr, [r0, #6] 108: e35c0007 cmp ip, #7 10c: e5d14006 ldrb r4, [r1, #6] 110: e064e00e rsb lr, r4, lr 114: e5c2e006 strb lr, [r2, #6] 118: 0a0000be beq 418 &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x418&gt; 11c: e5d0e007 ldrb lr, [r0, #7] 120: e35c0008 cmp ip, #8 124: e5d14007 ldrb r4, [r1, #7] 128: e064e00e rsb lr, r4, lr 12c: e5c2e007 strb lr, [r2, #7] 130: 0a000029 beq 1dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1dc&gt; 134: e5d0e008 ldrb lr, [r0, #8] 138: e35c0009 cmp ip, #9 13c: e5d14008 ldrb r4, [r1, #8] 140: e064e00e rsb lr, r4, lr 144: e5c2e008 strb lr, [r2, #8] 148: 0a000023 beq 1dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1dc&gt; 14c: e5d0e009 ldrb lr, [r0, #9] 150: e35c000a cmp ip, #10 154: e5d14009 ldrb r4, [r1, #9] 158: e064e00e rsb lr, r4, lr 15c: e5c2e009 strb lr, [r2, #9] 160: 0a00001d beq 1dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1dc&gt; 164: e5d0e00a ldrb lr, [r0, #10] 168: e35c000b cmp ip, #11 16c: e5d1400a ldrb r4, [r1, #10] 170: e064e00e rsb lr, r4, lr 174: e5c2e00a strb lr, [r2, #10] 178: 0a000017 beq 1dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1dc&gt; 17c: e5d0e00b ldrb lr, [r0, #11] 180: e35c000c cmp ip, #12 184: e5d1400b ldrb r4, [r1, #11] 188: e064e00e rsb lr, r4, lr 18c: e5c2e00b strb lr, [r2, #11] 190: 0a000011 beq 1dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1dc&gt; 194: e5d0e00c ldrb lr, [r0, #12] 198: e35c000d cmp ip, #13 19c: e5d1400c ldrb r4, [r1, #12] 1a0: e064e00e rsb lr, r4, lr 1a4: e5c2e00c strb lr, [r2, #12] 1a8: 0a00000b beq 1dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1dc&gt; 1ac: e5d0e00d ldrb lr, [r0, #13] 1b0: e35c000f cmp ip, #15 1b4: e5d1400d ldrb r4, [r1, #13] 1b8: e064e00e rsb lr, r4, lr 1bc: e5c2e00d strb lr, [r2, #13] 1c0: 1a000092 bne 410 &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x410&gt; 1c4: e5d0400e ldrb r4, [r0, #14] 1c8: e1a0e00c mov lr, ip 1cc: e5d1500e ldrb r5, [r1, #14] 1d0: e0654004 rsb r4, r5, r4 1d4: e5c2400e strb r4, [r2, #14] 1d8: ea000000 b 1e0 &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1e0&gt; 1dc: e1a0e00c mov lr, ip 1e0: e06c6003 rsb r6, ip, r3 1e4: e2435001 sub r5, r3, #1 1e8: e2464010 sub r4, r6, #16 1ec: e06c5005 rsb r5, ip, r5 1f0: e1a04224 lsr r4, r4, #4 1f4: e355000e cmp r5, #14 1f8: e2844001 add r4, r4, #1 1fc: e1a05204 lsl r5, r4, #4 200: 9a000010 bls 248 &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x248&gt; 204: e080900c add r9, r0, ip 208: e081800c add r8, r1, ip 20c: e3a07000 mov r7, #0 210: e082c00c add ip, r2, ip 214: f4690adf vld1.64 {d16-d17}, [r9 :64] 218: e2877001 add r7, r7, #1 21c: e1570004 cmp r7, r4 220: e2899010 add r9, r9, #16 224: f4682a0f vld1.8 {d18-d19}, [r8] 228: e2888010 add r8, r8, #16 22c: f34008e2 vsub.i8 q8, q8, q9 230: f44c0a0f vst1.8 {d16-d17}, [ip] 234: e28cc010 add ip, ip, #16 238: 3afffff5 bcc 214 &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x214&gt; 23c: e1560005 cmp r6, r5 240: e08ee005 add lr, lr, r5 244: 0a000064 beq 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 248: e7d0c00e ldrb ip, [r0, lr] 24c: e28e4001 add r4, lr, #1 250: e7d1500e ldrb r5, [r1, lr] 254: e1530004 cmp r3, r4 258: e065c00c rsb ip, r5, ip 25c: e7c2c00e strb ip, [r2, lr] 260: 9a00005d bls 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 264: e7d05004 ldrb r5, [r0, r4] 268: e28ec002 add ip, lr, #2 26c: e7d16004 ldrb r6, [r1, r4] 270: e153000c cmp r3, ip 274: e0665005 rsb r5, r6, r5 278: e7c25004 strb r5, [r2, r4] 27c: 9a000056 bls 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 280: e7d0500c ldrb r5, [r0, ip] 284: e28e4003 add r4, lr, #3 288: e7d1600c ldrb r6, [r1, ip] 28c: e1530004 cmp r3, r4 290: e0665005 rsb r5, r6, r5 294: e7c2500c strb r5, [r2, ip] 298: 9a00004f bls 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 29c: e7d05004 ldrb r5, [r0, r4] 2a0: e28ec004 add ip, lr, #4 2a4: e7d16004 ldrb r6, [r1, r4] 2a8: e153000c cmp r3, ip 2ac: e0665005 rsb r5, r6, r5 2b0: e7c25004 strb r5, [r2, r4] 2b4: 9a000048 bls 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 2b8: e7d0500c ldrb r5, [r0, ip] 2bc: e28e4005 add r4, lr, #5 2c0: e7d1600c ldrb r6, [r1, ip] 2c4: e1530004 cmp r3, r4 2c8: e0665005 rsb r5, r6, r5 2cc: e7c2500c strb r5, [r2, ip] 2d0: 9a000041 bls 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 2d4: e7d05004 ldrb r5, [r0, r4] 2d8: e28ec006 add ip, lr, #6 2dc: e7d16004 ldrb r6, [r1, r4] 2e0: e153000c cmp r3, ip 2e4: e0665005 rsb r5, r6, r5 2e8: e7c25004 strb r5, [r2, r4] 2ec: 9a00003a bls 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 2f0: e7d0500c ldrb r5, [r0, ip] 2f4: e28e4007 add r4, lr, #7 2f8: e7d1600c ldrb r6, [r1, ip] 2fc: e1530004 cmp r3, r4 300: e0665005 rsb r5, r6, r5 304: e7c2500c strb r5, [r2, ip] 308: 9a000033 bls 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 30c: e7d05004 ldrb r5, [r0, r4] 310: e28ec008 add ip, lr, #8 314: e7d16004 ldrb r6, [r1, r4] 318: e153000c cmp r3, ip 31c: e0665005 rsb r5, r6, r5 320: e7c25004 strb r5, [r2, r4] 324: 9a00002c bls 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 328: e7d0500c ldrb r5, [r0, ip] 32c: e28e4009 add r4, lr, #9 330: e7d1600c ldrb r6, [r1, ip] 334: e1530004 cmp r3, r4 338: e0665005 rsb r5, r6, r5 33c: e7c2500c strb r5, [r2, ip] 340: 9a000025 bls 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 344: e7d05004 ldrb r5, [r0, r4] 348: e28ec00a add ip, lr, #10 34c: e7d16004 ldrb r6, [r1, r4] 350: e153000c cmp r3, ip 354: e0665005 rsb r5, r6, r5 358: e7c25004 strb r5, [r2, r4] 35c: 9a00001e bls 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 360: e7d0500c ldrb r5, [r0, ip] 364: e28e400b add r4, lr, #11 368: e7d1600c ldrb r6, [r1, ip] 36c: e1530004 cmp r3, r4 370: e0665005 rsb r5, r6, r5 374: e7c2500c strb r5, [r2, ip] 378: 9a000017 bls 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 37c: e7d05004 ldrb r5, [r0, r4] 380: e28ec00c add ip, lr, #12 384: e7d16004 ldrb r6, [r1, r4] 388: e153000c cmp r3, ip 38c: e0665005 rsb r5, r6, r5 390: e7c25004 strb r5, [r2, r4] 394: 9a000010 bls 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 398: e7d0500c ldrb r5, [r0, ip] 39c: e28e400d add r4, lr, #13 3a0: e7d1600c ldrb r6, [r1, ip] 3a4: e1530004 cmp r3, r4 3a8: e0665005 rsb r5, r6, r5 3ac: e7c2500c strb r5, [r2, ip] 3b0: 9a000009 bls 3dc &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3dc&gt; 3b4: e7d05004 ldrb r5, [r0, r4] 3b8: e28ec00e add ip, lr, #14 3bc: e7d1e004 ldrb lr, [r1, r4] 3c0: e153000c cmp r3, ip 3c4: e06e3005 rsb r3, lr, r5 3c8: e7c23004 strb r3, [r2, r4] 3cc: 87d0300c ldrbhi r3, [r0, ip] 3d0: 87d1100c ldrbhi r1, [r1, ip] 3d4: 80613003 rsbhi r3, r1, r3 3d8: 87c2300c strbhi r3, [r2, ip] 3dc: e3a00000 mov r0, #0 3e0: e8bd83f8 pop {r3, r4, r5, r6, r7, r8, r9, pc} 3e4: e2411001 sub r1, r1, #1 3e8: e0803003 add r3, r0, r3 3ec: e2422001 sub r2, r2, #1 3f0: e4d0c001 ldrb ip, [r0], #1 3f4: e5f1e001 ldrb lr, [r1, #1]! 3f8: e1500003 cmp r0, r3 3fc: e06ec00c rsb ip, lr, ip 400: e5e2c001 strb ip, [r2, #1]! 404: 1afffff9 bne 3f0 &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x3f0&gt; 408: e3a00000 mov r0, #0 40c: e8bd83f8 pop {r3, r4, r5, r6, r7, r8, r9, pc} 410: e3a0e00e mov lr, #14 414: eaffff71 b 1e0 &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1e0&gt; 418: e3a0e007 mov lr, #7 41c: eaffff6f b 1e0 &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x1e0&gt; </code></pre>
<p>The compiler wrote this (buried inside of a lot of setup code to take care of edge cases):</p> <pre><code>214: f4690adf vld1.64 {d16-d17}, [r9 :64] 218: e2877001 add r7, r7, #1 21c: e1570004 cmp r7, r4 220: e2899010 add r9, r9, #16 224: f4682a0f vld1.8 {d18-d19}, [r8] 228: e2888010 add r8, r8, #16 22c: f34008e2 vsub.i8 q8, q8, q9 230: f44c0a0f vst1.8 {d16-d17}, [ip] 234: e28cc010 add ip, ip, #16 238: 3afffff5 bcc 214 &lt;code_c(unsigned char*, unsigned char*, unsigned char*, unsigned int)+0x214&gt; </code></pre> <p>My NEON is very rusty, and I'm not going to decode each line here (I'd get it wrong; hopefully someone will provide a more complete answer), but this is loading 16 bytes at a time into two 128-bit registers, subtracting all 16 from each other in parallel, and then writing them all back to the target. So this is doing the vectorization you were looking for. The fact that your NEON code is possibly slightly faster than the compiler's is at least partially because you don't check the edge case where <code>n</code> is not divisible by 8. The compiler does.</p> <p>In most cases, intrinsics are not going to be helpful. If you are trying to beat the compiler, you're going to need to handle the entire pipeline yourself, and intrinsics aren't powerful enough for that. You need to be able to pick your registers, decide when to read and write memory, and very carefully manage your data layout to even begin to beat the compiler (since it's already doing all of that).</p> <p>Why is the compiler's parallel behavior often better than hand-written even when you write basically the same things? Well, how do you manage faults? Assembly instructions do not run in series; many of them run in parallel. Often when you execute an expensive instruction, you may not be able to read the result for several clock cycles. If you try, the processor has to stop and wait. To avoid this problem, you often write assembly in very strange orders, like "start computation, load next data, write result of computation." That's really hard to pull off with intrinsics.</p> <hr> <p>To a few of your comments in @yeoman's answer:</p> <ol> <li>Doesn't the execution time depend on the number of assembly instructions generated?</li> </ol> <p>Absolutely not. Execution time depends on the number of assembly instructions executed and what those instructions are and in what order they are executed. Very, very often (almost always) faster code is longer code in assembly. (The converse is not promised of course…) The most famous example of this is loop unrolling. Cut-and-pasting an operation 3 times in a row is going to be faster than a loop that counts to 3. Avoiding branching alone is going to be massive there. So the compiler automatically unrolls small loops when it knows beforehand the number of iterations.</p> <ol start="2"> <li>There are supposed to be 8 parallel operations on Neon compared to single on C. </li> </ol> <p>There are supposed to be 8 parallel operations, and the compiler generates that. But your code doesn't; it does one at a time. </p> <p>Just using the NEON does magically make it go faster; the compiler already uses the NEON.</p> <p>For a slightly different issue (discussing the Accelerate framework in iOS), but still addressing the same basic issues, see <a href="http://robnapier.net/fast-bezier-intro" rel="nofollow">Introduction to Fast Bezier</a>.</p> <p>Also to reiterate @yeoman's point: If some very simple and mechanical change could make your C code go much faster, the compiler would just do that for you (and it does).</p>
Pass an updated function to an existing function <p>In this short sequence, the user creates a function <code>userfunc()</code>, but then wants to update the first definition to do something different. However the <code>programfunc()</code> has already compiled the first version, and continues to use it. </p> <pre><code>userfunc(str, n) = str ^ n userfunc("hello", 3) "hellohellohello" # program makes use of the user's function programfunc(func, a, b) = func(a, b) programfunc(userfunc, "hello", 3) "hellohellohello" # now the user redefines the function userfunc(str, n) = str ^ (n * n) # userfunc("hello", 3) give "hellohellohellohellohellohellohellohellohello" # but program still makes use of the first userfunc() programfunc(userfunc, "hello", 3) "hellohellohello" </code></pre> <p>So how could <code>programfunc()</code> be defined so that it always uses the latest definition of the function passed to it?</p>
<p><code>invoke</code> will do it. (Note though this will probably not compile to nice specialized code)</p> <p>The issue here is that julia specialized on Type. That is to say it compiles a custom version of the function for every combination of types passed to it. Since Functions have a type in julia 0.5 (Each function is a singleton type.) that causes it to specialize on the function</p> <p>tested on 0.5-rc0</p> <pre><code>julia&gt; userfunc(str, n) = str ^ (n*n) WARNING: Method definition userfunc(Any, Any) in module Main at REPL[16]:1 overwritten at REPL[20]:1. userfunc (generic function with 1 method) julia&gt; function programfunc(func, a, b) invoke(func, (typeof(a), typeof(b)), a, b) end programfunc (generic function with 1 method) julia&gt; programfunc(userfunc, "hello", 3) "hellohellohellohellohellohellohellohellohello" julia&gt; userfunc(str, n) = str ^ (n) WARNING: Method definition userfunc(Any, Any) in module Main at REPL[16]:1 overwritten at REPL[20]:1. userfunc (generic function with 1 method) julia&gt; programfunc(userfunc, "hello", 3) "hellohellohello" </code></pre> <p>Note this also works around <a href="https://github.com/JuliaLang/julia/issues/265" rel="nofollow">#265</a> </p> <pre><code>julia&gt; foo(x)=2*x foo (generic function with 1 method) julia&gt; function g(x) invoke(foo, (typeof(x),), x) end g (generic function with 1 method) julia&gt; g(2) 4 julia&gt; foo(x)=3*x WARNING: Method definition foo(Any) in module Main at REPL[1]:1 overwritten at REPL[10]:1. foo (generic function with 1 method) julia&gt; g(2) 6 </code></pre>
How to sort ArrayList<HashMap<String, String>> which contain number and string <p>Hello i get json response in following format</p> <pre><code>["{\"papersize\":\"4X6\"}","{\"papersize\":\"6X8\"}","{\"papersize\":\"5X7\"}","{\"papersize\":\"8X10\"}","{\"papersize\":\"8X12\"}","{\"papersize\":\"12X24\"}","{\"papersize\":\"12X36\"}","{\"papersize\":\"16X40\"}","{\"papersize\":\"12X30\"}","{\"papersize\":\"16X20\"}","{\"papersize\":\"20X30\"}","{\"papersize\":\"12X15\"}","{\"papersize\":\"10X12\"}","{\"papersize\":\"12X18\"}"] </code></pre> <p>I parsed that json by using following code and sorted the arraylist but i get sorted list as follows</p> <pre><code>10X12 12X15 12X18 . . . . 4X6 5X7 6X8 8X12 </code></pre> <p>So how to sort that arraylist in perfect manner like 4X6 5X7 6X8 8X12 . . . . 10X12 12X15 12X18 . . . like this</p> <p>Following is my code</p> <pre><code> for (int i = 0; i &lt; jsonArray.length(); i++) { HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); JSONObject mainjj = new JSONObject((String) jsonArray.get(i)); map.put("size", mainjj.getString("papersize")); arrayList.add(map); } Collections.sort(arrayList,new Comparator&lt;HashMap&lt;String,String&gt;&gt;() { public int compare(HashMap&lt;String, String&gt; mapping1, HashMap&lt;String, String&gt; mapping2) { return mapping1.get("size").compareTo(mapping2.get("size")); } }); Log.d("ArrayList", arrayList.toString()); } </code></pre>
<p>To solve this issue you can parse the size and then sort them.</p> <p>For Example,</p> <pre><code>import java.util.*; public class HelloWorld{ public static void main(String []args){ List&lt;String&gt; sizes = new ArrayList&lt;&gt;(); sizes.add("10X12"); sizes.add("4X6"); sizes.add("3X2"); sizes.add("5X12"); sizes.add("8X12"); Collections.sort(sizes, new Comparator&lt;String&gt;() { @Override public int compare(String o1, String o2) { int s1 = Integer.parseInt(o1.split("X")[0]); int s2 = Integer.parseInt(o2.split("X")[0]); return s1-s2; } }); System.out.println(sizes); } } </code></pre> <p>Cheer!!!</p>
How split java string using character which does not have an escape character before it <p>I've a string like this:</p> <pre><code>a=b\=c </code></pre> <p>and I need to split it using java <code>split</code> method such that my assertion does not throw an exception:</p> <pre><code>String[] res = "a=b\\=c".split("SPLIT_REGEX"); assert (res[0].equals("a") &amp;&amp; res[1].equals("b\\=c")); </code></pre> <p>I've tried <code>[^\\]=</code> as <code>SPLIT_REGEX</code> but it does not give me the desired answer. Could anybody tell me what would be the correct regex for my goal?</p>
<p>You can use a negative lookbehind before <code>=</code> to skip splitting in <code>\=</code>:</p> <pre><code>String res = "a=b\\=c"; String[] toks = res.split("(?&lt;!\\\\)="); //=&gt; ["a", "b\\=c"] </code></pre> <p><code>(?&lt;!\\\\)</code> is negative lookahead that asserts failure when <code>\</code> is present before <code>=</code></p>
Why do we have a slow `malloc`? <p>As far as I know, custom memory managers are used in several medium and large-scale projects. This <a href="https://security.stackexchange.com/questions/139364/how-is-the-heartbleed-exploit-even-possible">recent answer</a> on security.se discusses the fact that a custom memory allocator in OpenSSL was included for performance reasons and ultimately ended up making the Heartbleed exploit worse. This <a href="https://stackoverflow.com/questions/4642671/c-memory-allocators">old thread</a> here discusses memory allocators, and in particular one of the answer links to an academic paper that shows that while people write custom memory allocators for performance reasons because <code>malloc</code> is slow, a general-purpose state-of-the-art allocator easily beats them and causes fewer problems than developers reinventing the wheel in every project.</p> <p>As someone who does not program professionally, I am curious about how we ended up in this state and why we seem to be stuck there --- assuming my view is correct, which is not necessarily true. I imagine there must be subtler issues such as thread safety. Apologies if I am presenting the situation wrongly.</p> <p>Why is the system <code>malloc</code> not developed and optimized to match the performance of these "general-purpose state-of-the-art allocators"? It seems to me that it should be quite an important feature for OS and standard library writers to focus on. I have heard a lot of talking about the scheduler implementation in Linux kernel in the past, for instance, and naively I would expect to see more or less the same amount of interest for memory allocators. How come standard <code>malloc</code> is so bad that so many people feel the need roll out a custom allocator? If there are alternative implementations that work so much better, why haven't system programmers included them in Linux and Windows, either as default or as a linking-time option?</p>
<p>There are two problems:</p> <ol> <li><p>No single allocation scheme fits all application needs.</p></li> <li><p>The C library was poorly designed (or not designed). Some non-eunuchs operating systems have configurable memory managers that can allow the application to choose the allocation scheme. In eunuchs-land, the solution is to link in your own malloc/free implementation into your application.</p></li> </ol> <p>There is no real standard malloc implementation (GNU LIBC's is the probably the closest to standard). The malloc implementations that come with the OS tend to work fine for more applications.</p>
Is there something like a static thread_local method? <p>I guess it would not make much sense and I'm not sure what a <code>static thread_local</code> method would do, but does this exist?</p>
<p><code>static</code> unfortunately in C++ has many different unrelated meanings.</p> <p><code>thread_local</code> is a storage class specifier, and can be combined with <code>static</code> (that can also be used as a storage class specifier).</p> <p><code>static</code> in a method declaration however is NOT a storage class specifier and therefore talking about <code>thread_local</code> in this context is nonsense.</p> <p>In C++ methods are not data: they don't have a lifetime and they take no storage.</p>
What is masking here <p>In the python tutorial:</p> <p>In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:</p> <pre><code>&gt;&gt;&gt; tax = 12.5 / 100 &gt;&gt;&gt; price = 100.50 &gt;&gt;&gt; price * tax 12.5625 &gt;&gt;&gt; price + _ 113.0625 &gt;&gt;&gt; round(_, 2) 113.06 </code></pre> <p>This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name <strong>masking the built-in variable with its magic behavior</strong>.</p> <p>What is masking here? </p> <p><strong>In general</strong> what is meant by masking or mask variable in python? </p> <p>THanks</p>
<p>A variable is masked if some other variable with the same name exists, which is preferred. An example is having a global variable x. If you're in a function which also has a local variable x, then the global won't be accessible, without special measures the local variable is preferred whenever you use identifier x inside the function.</p> <p>It's as if you have two kids in your classroom both called Mary, one of which is closer, and will hear your voice earlier, so always gives the quickest answer. How to give the other girl a chance?</p>
Creating arrays of structs using text file <p>Given a text file with a semi-known format. Total characters in 1 line will be less than 1000. Zinteger is just a normal integer but it serves a different purpose. String terminated via space.</p> <p>String ZInteger Integer Integer</p> <p>String ZInteger Integer Integer Integer Integer </p> <p>So its a word followed by a number followed by pairs of numbers, but a random amount of pairs.</p> <p>I want to store the string , Zinteger, and integer pairs for each line in a data structure. </p> <p>So I tried an array where A[1] would be a struct that has String, Zinteger and the pairs of integers which will be another struct that has the integer pair. Heres what i tried.</p> <pre><code>typedef struct { int num1; int num2; } ints_t; typedef struct { char term[1000]; int quantity(bad variable name, could be called alpha); ints_t *pairs; } info_t; </code></pre> <p>Help is appreciated.</p> <p>EDIT: Alright so im being too open. So ill just ask a simple question are the two structs I made viable and if not how do I make them viable and how do I malloc the structs and array.</p>
<p>Your structure looks reasonable, however, it is missing a field to store a count for the number of pairs:</p> <pre><code>typedef struct { int num1; int num2; } int_pair_t; typedef struct { char term[1000]; int zinteger; /* so named to avoid confusion */ int n_pairs; int_pair_t *pairs; } info_t; </code></pre> <p>Given a maximum of 1000 characters per line, and assuming a one character string followed by a space, followed by a single digit <code>Zinteger</code>, 332 is the greatest number of pairs (single digit followed by space followed by a single digit) that could be accommodated in the remaining characters.</p> <p>So you could use a fixed size array of <code>int_pair_t pairs[332]</code> into which the pairs from one line are read, as well as a string for the <code>term</code>, and <code>int</code>s for the <code>Zinteger</code> and pair count. Once you have read the line, you can copy the pairs data into a newly malloced <code>info_t</code> struct of precisely the right size, and add that to whatever collection you have for the lines.</p> <p>If you don't overly care about memory usage (it's less than 3KB per line), you can skip the malloc and copy, and just allocate a fixed sized array in the <code>info_t</code> struct:</p> <pre><code>#define MAX_PAIRS 332 typedef struct { char term[1000]; int zinteger; /* so named to avoid confusion */ int n_pairs; int_pair_t pairs[MAX_PAIRS]; } info_t; </code></pre> <hr> <p>Your original question also asked how to read the data in from a text file. Read a line of data from the file into a <code>char</code> buffer. Then you can use <a href="http://linux.die.net/man/3/strtok" rel="nofollow"><code>strtok()</code></a> to process the fields from the file using space as a delimiter. You can combine that with <code>sscanf()</code> to extract the first 2 fields if you want, and the process the remaining fields with <code>strtok</code>.</p>
NewbieQ: Jupyter HTML command not working when multiple code lines <p>I'm new to Jupyter Notebook and have this simple line of code:</p> <pre><code>HTML('&lt;b&gt;Question&lt;/b&gt;') Q=1 </code></pre> <p>I have found that the first line only works when nothing else comes after it. Is this normal? Do I have to have each line of code in a separate cell?</p>
<p>There are two things at play here:</p> <ol> <li><code>HTML</code> creates an HTML <em>object</em>, whose <a href="https://nbviewer.jupyter.org/github/ipython/ipython/blob/5.0.0/examples/IPython%20Kernel/Rich%20Output.ipynb" rel="nofollow">rich representation</a> is the HTML string <code>&lt;b&gt;...</code>. Instantiating such an object does not display it.</li> <li>If a cell ends in an expression (the cell has a result, in a way), the result of that expression is displayed automatically.</li> </ol> <p>So a cell that <em>ends with</em> <code>HTML(...)</code> will display that HTML because it is the 'result' of the cell. If you store the HTML object in a variable, you can display it at any time. IPython has a <code>display</code> function, which is like the Jupyter rich-media version of Python's builtin <code>print</code> function. To display objects at any point:</p> <pre><code>from IPython.display import display display(obj) </code></pre> <p>in your case:</p> <pre><code>display(HTML('&lt;b&gt;Question&lt;/b&gt;')) </code></pre> <p>Or you can store the HTML in a variable and display it later or repeatedly:</p> <pre><code>msg = HTML('&lt;b&gt;Question&lt;/b&gt;') for i in range(3): display(msg) </code></pre>
use variables in Google Chart Options Javascript <p>I have created a Google Pie Chart using the following code:</p> <pre><code>var data = google.visualization.arrayToDataTable(array); var options = { title: 'Meta Share', is3D: true, sliceVisibilityThreshold: .04, slices: { 6 : {offset: 0.2}, }, }; var chart = new google.visualization.PieChart(document.getElementById('chart_div')); chart.draw(data, options); } </code></pre> <p>I want to select a slice of the pie chart dynamically depending on what my user is doing. I now have the following code:</p> <pre><code>var slice = 8; </code></pre> <p>I would now like to use this variable in the above code, however; replacing the '6' with the variable 'slice' does not work. </p> <p>Any suggestions? :) </p>
<p>You can't use variables as keys in object literals, you'd have to first create the object, then use brackets to use the variable as a key</p> <pre><code>var slice = 8; var slices = {}; slices[slice] = {offset: 0.2}; var data = google.visualization.arrayToDataTable(array); var options = { title : 'Meta Share', is3D : true, sliceVisibilityThreshold : .04, slices : slices }; var chart = new google.visualization.PieChart(document.getElementById('chart_div')); chart.draw(data, options); } </code></pre>
What are the reserved keywords in Elm? <p>Every once in a while you get a compiler error like this:</p> <pre><code>It looks like the keyword `port` is being used as a variable. </code></pre> <p>That's annoying. Is there a complete official list of these keywords? I've gotten as far as finding <a href="https://github.com/elm-lang/elm-compiler/blob/e9cfb680b1cddc80268ae15262b2389a2a852fc6/src/Reporting/Error/Syntax.hs" rel="nofollow">where the error messages are generated</a>, but I couldn't find where the keywords are actually defined.</p> <p>Meanwhile, here's a probably incomplete or incorrect list of keywords I found by browsing the <a href="http://elm-lang.org/docs/syntax" rel="nofollow">syntax</a> page and trying keywords in the repl:</p> <ul> <li>let</li> <li>in</li> <li>where</li> <li>module</li> <li>exposing</li> <li>type</li> <li>port</li> <li>import</li> <li>infixr</li> <li>as</li> <li>if</li> <li>else</li> <li>then</li> </ul>
<p>According to the <a href="https://github.com/elm-lang/elm-compiler" rel="nofollow">elm-compiler source code</a> the <a href="https://github.com/elm-lang/elm-compiler/blob/master/src/Parse/Helpers.hs#L25-L35" rel="nofollow">list of reserved keywords</a> is:</p> <pre><code>reserveds :: [String] reserveds = [ "if", "then", "else" , "case", "of" , "let", "in" , "type" , "module", "where" , "import", "exposing" , "as" , "port" ] </code></pre> <p>Edit: There are actually some more keywords (found by <a href="https://github.com/elm-lang/elm-compiler/search?utf8=%E2%9C%93&amp;q=reserved" rel="nofollow">searching for "reserved"</a> in the repo) I've found: <code>infix</code>, <code>infixl</code>, <code>infixr</code>. <code>infixr</code> has also be noted by the OP.</p>
How to remove a grey shadow from a JPEG? <p>So in Photoshop we all know it's relatively easy to remove a white background from a .jpg image if the contrast is quite visible.</p> <p>The problem with this image though is it has a grey shadow at the bottom of the image that is reliant on the white background, and therefore once it becomes transparent the shadow looks nasty.</p> <p>What would be the best approach to remove this once the white background had been removed?</p> <p>Thanks</p> <p><a href="https://s15.postimg.org/k2itasu7v/i_Stock_104502239_LARGE.jpg" rel="nofollow">https://s15.postimg.org/k2itasu7v/i_Stock_104502239_LARGE.jpg</a></p>
<p>You can use the Polygonal Lasso Tool. Manual removing. Zoom to the shadow, select it with the Polygonal Lasso Tool > Right click and : Refine the edge + give it a bit of Feather and paint using the background color of the image.</p>
Lato Font not rendering in IE but its working fine in Chrome <p>I am using Google Lato font for my UI Development perspective but i had a problem when i using lato font it doesn't render correctly in IE but its working fine in Chrome Browser, I couldn't understand what happened?</p> <p><br/> I just download the Google font to my local</p> <p><strong>Lato Google Font</strong></p> <pre><code>&lt;link href="https://fonts.googleapis.com/css?family=Lato:300,400,700&amp;amp;subset=latin-ext" rel="stylesheet"&gt; </code></pre> <p><strong>My Local Path</strong> <a href="https://i.stack.imgur.com/W04fF.png" rel="nofollow"><img src="https://i.stack.imgur.com/W04fF.png" alt="enter image description here"></a></p> <p><strong>Specify in CSS</strong></p> <pre><code>body { font-family: 'Lato', sans-serif;} </code></pre> <p><strong>Chrome</strong> - Its Taking <code>'Lato'</code></p> <p><strong>IE</strong> - Lato Font Not Rendering, Instead of lato font it will take <code>sans-serif</code></p> <p>I don't know what i missed, can you help me in that case ?</p>
<p>I used google font lato via</p> <pre><code>&lt;link href="https://fonts.googleapis.com/css?family=Lato&amp;amp;subset=latin-ext" rel="stylesheet"&gt; </code></pre> <p>and it renders properly on IE11 (on windows) as well as chrome , so I suggest try to used google font from google api instead of downloading it on ur local machine or ur server</p> <p>also check out this link <a href="https://css-tricks.com/snippets/css/using-font-face/" rel="nofollow">here</a> this might help you</p>
unable to send ckeditor data using Ajax post <p>I have a textarea which using ckeditor</p> <pre><code>&lt;textarea rows="25" cols="50" id="content" name="content" required="required"&gt;&lt;/textarea&gt; &lt;script type="text/javascript"&gt; CKEDITOR.replace( 'content' ); &lt;/script&gt; &lt;input type="submit" name="submit" value="submit" class="submit" /&gt; </code></pre> <p>When i click to submit, A Jquery function called</p> <pre><code>$("body").on("click", "input.submit", function() { for(instance in CKEDITOR.instances){ CKEDITOR.instances[instance].updateElement(); } var content = CKEDITOR.instances['content'].getData(); var dataString = 'content='+ content; if(content==='') { alert("Please fill all fields"); } else { $.ajax({ type: "POST", url: "transfer/action.php", data: dataString, cache: false, success: function(result){ $(".error").html(result); }, error:function (xhr, ajaxOptions, thrownError){ $(".error").html(thrownError); } }); } return false; }); </code></pre> <p>i inputted some data like.... </p> <blockquote> <p>That's because there are question-and-answer sites like where any developer can post a programming-related question</p> </blockquote> <p>When i clicked on submit button the data is showing in jquery but ajax is not sending data to php properly due to single quote where single quote is already encoded by editor.. Ajax denies to send data with single quote why.. please help me</p>
<p>You need to disable encoding of HTML entities on Ckeditor. Then, once you POST your data, you should be good. See more info here...</p> <p><a href="http://ckeditor.com/forums/CKEditor-3.x/Trying-disable-html-entities-not-working" rel="nofollow">http://ckeditor.com/forums/CKEditor-3.x/Trying-disable-html-entities-not-working</a></p>
Selecting all the records from table to which given number belongs to <p>Suppose I have following three records in my model :</p> <pre><code>#&lt;Rda:0xf6e8a0c id: 1, age_group: "18-100", weight: "60", nutrient: "energy(kcal/day)", value: "2730", created_at: Sat, 15 Oct 2016 08:21:43 UTC +00:00, updated_at: Sat, 15 Oct 2016 08:21:43 UTC +00:00&gt; #&lt;Rda:0xf6e8a0c id: 2, age_group: "10-15", weight: "60", nutrient: "energy(kcal/day)", value: "2730", created_at: Sat, 15 Oct 2016 08:21:43 UTC +00:00, updated_at: Sat, 15 Oct 2016 08:21:43 UTC +00:00&gt; #&lt;Rda:0xf6e8a0c id: 3, age_group: "20-100", weight: "60", nutrient: "energy(kcal/day)", value: "2730", created_at: Sat, 15 Oct 2016 08:21:43 UTC +00:00, updated_at: Sat, 15 Oct 2016 08:21:43 UTC +00:00&gt; </code></pre> <p>Now, I want to get all those records in which my given value falls in a 'age_group' columns ranges. For example: suppose my age is 25 then I should get records with ids 1 &amp; 3 from the above records because '25' falls in between '18-100' and '20-100'</p>
<p>You might do</p> <pre><code>def self.foo(age) all.select { |rda| Range.new(*rda.age_group.split('-').map(&amp;:to_i)).cover? age } end </code></pre>
PDF report generating in php <p>I have a php file which generate pdf report of guest reviews from the table. It shows well. But problem is in the report , Review cell content shows in a single line. Not breaks it. Please help me to break the line in review cell in a suitable point.</p> <p><img src="https://i.stack.imgur.com/fNSVH.jpg" alt="enter image description here"></p> <p><strong>Here is the code.</strong> <pre><code> include("connect.php"); $SQL = "SELECT * FROM reviews "; $run=mysql_query($SQL,$con) or die ("SQL error"); //---------------------pdf creation------------------------------------------- require("fpdf/fpdf.php"); $pdf=new FPDF(); $pdf-&gt;AddPage(); $pdf-&gt;SetFont("Arial","B",10); $pdf-&gt;Cell(190,10,"Guest reviews report",1,1,'C'); $pdf-&gt;SetFont("Arial","B",10); $pdf-&gt;Cell(20,10,"Booking ID",1,0,'C'); $pdf-&gt;Cell(40,10,"Guest name",1,0,'C'); $pdf-&gt;Cell(50,10,"email",1,0,'C'); $pdf-&gt;Cell(60,10,"Review",1,0,'C'); $pdf-&gt;Cell(20,10,"Rate",1,1,'C'); while($row = mysql_fetch_array($run)) { $pdf-&gt;SetFont("Arial","B",10); $pdf-&gt;Cell(20,10,$row['bookingid'],1,0); $pdf-&gt;Cell(40,10,$row['name'],1,0); $pdf-&gt;Cell(50,10,$row['email'],1,0); $pdf-&gt;Cell(60,10,$row['review'],1,0); $pdf-&gt;Cell(20,10,$row['rating'],1,1); } $pdf-&gt;Output(); ?&gt; </code></pre> <p>I have included a screenshot of my report. <a href="https://i.stack.imgur.com/FmuhW.jpg" rel="nofollow">screenshot</a></p>
<p>You need to use <strong>MultiCell</strong>. Here is the example</p> <pre><code>$pdf-&gt;MultiCell(55, 5, $row['review'], 1, 'L', 1, 0, '', '', true); </code></pre> <p>And here is the example from the <strong>tcpdf</strong>: <a href="https://tcpdf.org/examples/example_005/" rel="nofollow">https://tcpdf.org/examples/example_005/</a></p> <p>Documentation about MultiCell: <a href="http://www.fpdf.org/en/doc/multicell.htm" rel="nofollow">http://www.fpdf.org/en/doc/multicell.htm</a></p> <p>Note: <code>55</code> is the width and <code>5</code> is the height. In your case they would be <code>60</code> and <code>10</code></p> <blockquote> <p>MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])</p> </blockquote>