input
stringlengths
51
42.3k
output
stringlengths
18
55k
Mouse listnener not removing a JPanel in java <p>I have a JFrame with 64 JPanels on it. I have a mouseListener that should be removing the JPanel that is being clicked on. However, the only thing that happens when you click a JPanel is that you get a bunch of errors.</p> <p>The code is as follows:</p> <pre><code>import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Checkers extends JPanel implements MouseListener { private final int ROW_COUNT = 8; private JFrame board = new JFrame(); public Checkers() { GridLayout grid = new GridLayout(ROW_COUNT, ROW_COUNT); setLayout(grid); for (int i = 0; i &lt; ROW_COUNT * ROW_COUNT; i++) { JPanel panel = new JPanel(); int row = i / ROW_COUNT; int col = i % ROW_COUNT; String name = String.format("[%d, %d]", row, col); panel.setName(name); if ((row % 2) == (col % 2)) panel.setBackground(Color.black); add(panel); if (panel.getBackground() == Color.black &amp;&amp; row &lt;= 2) { remove(panel); add(new Checker(Color.black, Color.red)); } if (panel.getBackground() == Color.black &amp;&amp; row &gt;= 5) { remove(panel); add(new Checker(Color.black, Color.green)); } } } public void startGame() { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int screenHeight = (int) screenSize.getHeight(); Insets inset = board.getInsets(); int boardHeight = (screenHeight / 2) - inset.right - inset.left; int boardWidth = (screenHeight / 2) - inset.top - inset.bottom; board.setSize(boardHeight, boardWidth); board.setLocationRelativeTo(null); board.setVisible(true); board.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); board.getContentPane().add(new Checkers()); board.addMouseListener(this); addMouseListener(this); } public static void main(String[] args) { final Checkers obj = new Checkers(); SwingUtilities.invokeLater(new Runnable() { public void run() { obj.startGame(); } }); } public void mouseClicked(MouseEvent e){ JPanel panel = (JPanel) e.getComponent(); remove(panel); System.out.println("mouseClicked has been called"); } public void mouseExited(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } } class Checker extends JPanel { private Color circleColor; public Checker(Color c, Color cCircle) { setColor(c); setCircleColor(cCircle); repaint(); } public void setColor(Color c) { setBackground(c); } public void setCircleColor(Color c) { circleColor = c; } protected void paintComponent(Graphics g) { super.paintComponent(g); int width = getWidth(); int height = getHeight(); g.setColor(circleColor); int orgX = (width / 2) - ((width * 5) / 12); int orgY = (height / 2) - ((height * 5) / 12); int widthC = (width * 5) / 6; int heightC = (height * 5) / 6; g.fillOval(orgX, orgY, widthC, heightC); } } </code></pre> <p>These are the errors:</p> <pre><code>Exception in thread "AWT-EventQueue-1" java.lang.ClassCastException: javax.swing.JFrame cannot be cast to javax.swing.JPanel at Checkers.mouseClicked(Checkers.java:63) at java.awt.Component.processMouseEvent(Component.java:6538) at java.awt.Component.processEvent(Component.java:6300) at java.awt.Container.processEvent(Container.java:2236) at java.awt.Window.processEvent(Window.java:2029) at java.awt.Component.dispatchEventImpl(Component.java:4891) at java.awt.Container.dispatchEventImpl(Container.java:2294) at java.awt.Window.dispatchEventImpl(Window.java:2750) at java.awt.Component.dispatchEvent(Component.java:4713) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86) at java.awt.EventQueue$4.run(EventQueue.java:731) at java.awt.EventQueue$4.run(EventQueue.java:729) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) at org.GNOME.Accessibility.AtkWrapper$5.dispatchEvent(AtkWrapper.java:697) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) </code></pre>
<blockquote> <p>ClassCastException: javax.swing.JFrame cannot be cast to javax.swing.JPanel</p> </blockquote> <p>So fix the problem. You can't add a MouseListener to a JFrame and expect it to be a JPanel. </p> <p>You need to either:</p> <ol> <li><p>add the <code>MouseListener to each JPanel</code> in your loop when you create the panels. Then you can cast the source to a JPanel.</p></li> <li><p>Or in the MouseListener you need to write code that searches the frame for the panel at the given mouse point. In this case you need to cast the source to a JFrame.</p></li> </ol>
Exception handling in a class C++ <p>I am going through Data Structures and Algorithms in C++ and I am facing an issue currently. I am writing a stack class using arrays and the book suggests me to use exception specification in the function declaration. In my case I have StackEmptyException and StackFullException classes derived from RuntimeException class and the book says that I should not try to catch this exception in the function body but whenever I try to run my program forcing an exception it fails to start saying "Unhandled exception". I would like to understand where the problem comes from, because the book doesn't really explains it, only mentioning, thus I would appreciate any related answer. Here is my code:</p> <pre class="lang-cpp prettyprint-override"><code>class RuntimeException { private: string errMsg; public: RuntimeException(const string&amp; err) { errMsg = err; } string getMessage() const { return errMsg; } }; inline ostream&amp; operator&lt;&lt;(ostream&amp; out, const RuntimeException&amp; e){ return out &lt;&lt; e.getMessage(); } class StackEmptyException : public RuntimeException { public: StackEmptyException(const string&amp; err) : RuntimeException(err) {} }; class StackFullException : public RuntimeException { public: StackFullException(const string&amp; err) : RuntimeException(err) {} }; template &lt;typename Object&gt; class ArrayStack { private: enum { CAPACITY = 1000 }; int capacity; Object* S; int t; public: ArrayStack(int cap = CAPACITY) { capacity = cap; S = new Object[capacity]; t = -1; } int size() const { return t + 1; } bool isEmpty() const { return (t &lt; 0); } // Passing the object by reference so that we could // edit its value e.g. stack.top() = 10; would be valid Object&amp; top() throw(StackEmptyException) { if (isEmpty()) throw StackEmptyException("Access to empty stack"); return S[t]; } void push(const Object&amp; elem) throw(StackFullException) { if (size() == capacity) throw StackFullException("Stack overflow"); S[++t] = elem; } // Not passing by reference, because we remove the last element // from the stack, thus we can not change its value Object pop() throw(StackEmptyException) { if (isEmpty()) throw StackEmptyException("Access to empty stack"); return S[t--]; } ArrayStack(const ArrayStack&amp; st); // Copy constructor ArrayStack&amp; operator=(const ArrayStack&amp; st); // Assignment operator constructor ~ArrayStack() { delete[] S; } // Destructor }; </code></pre>
<p>I think the reason your book says you shouldn't always use a try/catch to catch this is because you should first do the bounds checking yourself. So before you pop() check if isEmpty() first for example.</p>
Does importing with (import ...) slow down the app? <p>I'm new to Android Development, sorry if it's a dumb question. Android Studio uses <code>import ...</code> by default. I want to know what libraries does it import and does using <code>import ...</code> slow down the app?</p>
<p>No, the import statement doesn't actually do anything except for removing the need to qualify.</p> <p>For example, if you didn't want to use the import statement for an arraylist, it is actually quite possible to write</p> <pre><code>java.util.ArrayList&lt;Integer&gt; foo = new java.util.ArrayList&lt;Integer&gt;(); </code></pre> <p>But this would clearly be horrible. By inserting the line</p> <pre><code>import java.util.ArrayList </code></pre> <p>You are indicating that in this file, <code>ArrayList</code> really means <code>java.util.ArrayList</code></p>
Ajax Callback -> messages form PHP via JSON to JS and output to DIV <p>This is a newbie-question. I have never learned JS and it is very hard for me to do easy things..</p> <p>I have a PHP-Script, which gets data via JS from the Website. The PHP-Script updates the database and Returns a success via the following code-line:</p> <pre><code>echo json_encode(array('success'=&gt;'true')); </code></pre> <p>I have Setup a function, which does something, when "success" is returned:</p> <pre><code>success: function(){ .... } </code></pre> <p>Now I want to extend it a little bit. My PHP-Script would also return a message, which should be output into a DIV.</p> <p>It would Output something like:</p> <p>"error-msg"=>"Could not write to DB." or "success-msg"=>"Data successfully saved in DB."</p> <p>I really don't know how to check if the returned data is a "error-msg" or success-msg. I don't know how to get the msg string and also how to Display it in a defined DIV.</p> <p>Could you help me?</p> <p>Thank you!</p>
<p>Instead of using <code>success_msg</code> and <code>error_msg</code>, you could just use <code>status_msg and status</code> (in your PHP script). </p> <p><code>status_msg</code> would contain the text. status would contain <code>"success" or "error"</code>. You could also use any other kind of marker you like.</p> <p>To check the status of the message in Javascript, </p> <pre><code>var response = JSON.parse(&lt;response_from_server&gt;); console.log(response.status_msg); //display the message if(response.status == "success"){ //do something } else { //do something } </code></pre> <p>After you get the message, you can display it in a DIV using</p> <pre><code>document.getElementById("message").innerHTML = response.status_msg; </code></pre> <p>The HTML file would look like</p> <pre><code>&lt;div id="message"&gt; &lt;/div&gt; </code></pre>
Why doesn't ${@:-1} return the last element of $@? <p><em>I thought to post up a Q&amp;A on this as I did not find anything similar. If it already exists, please mark this as a duplicate.</em></p> <hr> <p>The following code, running under Bash shell, doesn't work (should return just <code>f</code>, the last (-1-th) item in <code>$@</code>):</p> <pre><code>$ set -- a b c d e f $ echo ${@:-1} a b c d e f </code></pre>
<h3><code>${parameter:-word}</code> is a type of <a href="https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion">parameter expansion</a>:</h3> <blockquote> <p><strong><code>${parameter:-word}</code></strong></p> <p>If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.</p> </blockquote> <hr> <p>So <code>${@:-1}</code> is interpreted as:</p> <ul> <li>If <code>$@</code> is unset or null, substitute with <code>1</code></li> <li>Else leave <code>$@</code> as it is</li> </ul> <p>Since the latter is true, <code>echo</code> prints <code>$@</code> in all its glory</p> <hr> <h3>The Fix:</h3> <p>Put some space between <code>:</code> and <code>-</code>:</p> <pre><code>$ echo ${@: -1} f </code></pre>
Added SSL to Static IP Address API Server <p>I am not sure if anyone have this issue.</p> <p>I have an </p> <ul> <li>Local API Server + Database with Static IP</li> <li>Web Site</li> </ul> <p>My API server is holding all the information and the Web site is just a middleman and point all transaction to the server. So if we are talking about MVC, the website is like the View, and my API is the Model and Controller.</p> <p>So my question is how should I add SSL to the API Server? Because my API server is running on an IP, so SSL is unable to attached to a Public IP. (Quoted from GoDaddy. IP Address to SSL will stop on 1st October 2016).</p> <p>I seen online, saying to direct a domain name to the IP Address and get SSL for the domain but my question is, is there any security risk because technically I still access through the public IP directly.</p> <p>Please advise on how should I proceed.</p> <p>Thanks!</p>
<p>If you give it a hostname and a SSL cert for that hostname, anyone accessing via IP will get an "invalid SSL hostname mismatch" type error (exact error depends on what browser/client/etc. is being used to access it). This is because your 10.42.56.113 doesn't match "db.example.com" and the SSL cert is for "db.example.com".</p> <p>If you are using code to make the connection, then you need to know that some implementations of some things allow you to set flags/arguments/whatever that say "yes, use a self signed cert" or "don't freak out over SSL errors connect anyway".</p> <p>But, that is bad practice. Do it right. Get a hostname assigned to your IP, get a SSL certificate for it (let's encrypt makes it super easy), and connect to it via that host name.</p>
What is the reason for the garbage value printed at the beginning? <p>I am writing a program which will do two things</p> <ol> <li><p>get a number between 0 to 10(10 is not included,so values should be less than 10),separate them and store them in an array</p></li> <li><p>print the array for each number</p></li> </ol> <p>For that purpose I wrote an if-else block which will initialize an array each time exactly according to the size of the current integer value which is denoted by variable called <code>num</code></p> <p>Meaning that if I have a number of single digit it will create an array of one element, but if the number is two digits long, it will create an array of two elements, etc. But whenever I run the code, I get some garbage value printed at the beginning. </p> <p>What might be the reason for that and how to solve this issue?</p> <p><a href="https://i.stack.imgur.com/nlIb9.png" rel="nofollow"><img src="https://i.stack.imgur.com/nlIb9.png" alt="enter image description here"></a></p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;math.h&gt; int mirror(int *arr,int num,int i); int main(){ int num = 0; int range = 1; int *arr; while(num&lt;10){ int i=0; if(num&lt;(int)pow(10,range)){ arr=(int *)malloc(range*sizeof(int)); }else{ range+=1; arr=(int *)malloc(range*sizeof(int)); } mirror(arr,num,i); for(i=range-1;i&gt;=0;i--){ printf("%d ",arr[i]); } printf("\n"); num++; } } int mirror(int *arr,int num,int i){ if(num == 0){ return 0; } arr[i] = num%10; mirror(arr,num/10,++i); } </code></pre>
<p>It's because you're not setting <code>arr[i]</code> to anything in the base case in mirror function. And if there isn't any use of the return value of the function, why are you making it return anything?<br> Either make it <code>void</code> or if you've to return value from it, at-least make sure that all control paths return some value.</p> <p>As suggested in the below comment by @JonathanLeffler:</p> <pre><code>void mirror(int *arr,int num,int i){ arr[i] = num % 10; if (num &gt;= 10) mirror(arr, num / 10, ++i); } </code></pre> <p>And you're leaking memory horribly. Either <code>free</code> memory in each iteration or use a <code>realloc</code> and at the end of the program, <code>free</code> the memory.</p>
How to get class's numeric suffix? <p>There's a class:</p> <pre><code>&lt;div id="my-id" class"my-class my-class-level-3"&gt;&lt;/div&gt; </code></pre> <p>How can I get its numeric <code>my-class-level</code> suffix (in this case - <code>3</code>)? Order of class attributes can be absolutely random.</p>
<p>This is how I would do It:</p> <pre><code>"use strict"; function getSuffix(element) { let match; if ( match = element.className.match(/my-class.+my-class-level-(\d+)/) ) return match[1]; return null; } console.log(getSuffix({className: 'my-class random class names my-class-level-5'})); </code></pre> <p>Or you can just set a custom attribute like <code>level="9"</code> and retrieve it using <code>.getAttribute</code>. or better using <code>data-level="9"</code> and get it using <code>.dataset.level</code>.</p> <p>Hope this helps.</p>
Spring-Boot executable encoding <p>My Rest-Application delivers data in correct encoding when running under Eclipse. But when I start the application as executable jar on a Windows System, my special characters are broken.</p> <p>What am I missing?</p> <p><a href="https://i.stack.imgur.com/wnFSe.png" rel="nofollow"><img src="https://i.stack.imgur.com/wnFSe.png" alt="enter image description here"></a></p>
<h3>Eclipse</h3> <p>Eclipse's encoding is set in <code>preferences-&gt;general-&gt;workspace</code>, which whould by default be inherited from the OS (cp1250 on windows). When you create a "Run as" task, it also stores it. So if you update eclipse's setting, make sure you re-create your "run as" task. You can see the actual value used when launching your application: <code>Run configurations... -&gt; Your Run task -&gt; Common tab</code>.</p> <p>You can also force an encoding in eclipse.ini by adding <code>-Dfile.encoding=AnotherEncoding</code> at the end. </p> <h3>Command line</h3> <p>When launching from the command line, it takes the system default value, which would be cp1250 on whidows.</p> <p>You could print the encoding at the very first line of your program, just to see: <code>System.out.println(System.getProperty("file.encoding"));</code></p> <p>To specify an encoding from the command line: <code>java -Dfile.encoding=UTF-8 yourApp.jar</code></p> <h3>See also</h3> <p>Take a look at this too: <a href="http://stackoverflow.com/a/14867904/641627">http://stackoverflow.com/a/14867904/641627</a></p> <blockquote> <p>This indicates a problem with your code. Your code is currently depending on the default platform encoding, and doesn't work if that encoding is not "UTF-8". therefore, you should change the places in your code which depend on the default platform encoding to use the "UTF-8" encoding explicitly.</p> </blockquote>
How can I ensure a bind is updated on the VM before a component's props get populated <p>So I've a data property that is populated from a field on my vm</p> <pre><code>var vm = new Vue{ data: { somevalue: null, }, } </code></pre> <p>This value is bound to a field that is prepopulated on load:</p> <pre><code>&lt;input v-model:somevalue="1" /&gt; </code></pre> <p>I then use this value and pass it to a component as a prop. In that component, I have a function which gets called once, that uses this value.</p> <pre><code>&lt;some-component v-bind:propofsomevalue="somevalue"&gt;&lt;/some-component&gt; ... //the innards of the component prop: ["propofsomevalue"] ready: function(){ //Does something with this.propofsomevalue } </code></pre> <p>The problem is on ready/compile/attached etc, the base vm.somevalue hasn't yet updated, and so the prop doesn't get updated until later on down the lifecycle. So whenever it runs propofsomevalue is null. How can I perform this function once the props have been inserted.</p> <p>It works if I directly pass a value, instead of using the bind.</p> <pre><code>&lt;some-component v-bind:propofsomevalue="1"&gt;&lt;/some-component&gt; </code></pre> <p>It works, but the problem is that this value isn't static and gets populated dynamically by asp server side.</p> <p>Many thanks!</p>
<p>Can't you just put a "watch" on the prop and perform the action once the value has changed to something other than null?</p>
Prevent insertion of invalid characters to text input <p>I have a form with standard text elements:</p> <pre><code>&lt;form id="f"&gt; &lt;input type="text" name="from" pattern="^[A-Za-z ]+$&gt; &lt;input type="text" name="to" pattern="^[A-Za-z ]+$&gt; &lt;/form&gt; </code></pre> <p>And I'd like to prevent users from entering disallowed characters into them. For example, typing <kbd><code>0</code></kbd> should have no effect.</p> <p>How can I do this?</p>
<pre><code>$("#f input[type=text]").keypress( function(e) { new_text = $(this).val() + String.fromCharCode(e.which) pattern = $(this).attr("pattern") return Boolean(new_text.match(pattern)) }) </code></pre> <p>The code works by returning false, and thereby cancelling the keypress, if the new text does not match <code>pattern</code>. It's important to use <code>function(e)</code> instead of <code>(e) =&gt;</code> because the latter would bind <code>this</code> lexically, whereas we want to let jQuery bind <code>this</code> to the respective <code>input</code> element.</p>
hide or delete image not found with $("img").error(function() <p>In my page I can have images not uploaded yet or removed by error so I'm looking for something who can remove or hide the warning about my img src not found ?</p> <p>you can check my code here or in this link -> </p> <p><a href="http://www.booclin.ovh/tom/2/" rel="nofollow">http://www.booclin.ovh/tom/2/</a></p> <p>here is my 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>$("img").error(function() { $(this).parent().remove(); }); $("a.fancyboxgallery").fancybox();</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.css" rel="stylesheet" /&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.js"&gt;&lt;/script&gt; &lt;a class="fancyboxgallery" rel="book" href="http://www.booclin.ovh/tom/2/index/photos/projet/6.jpg" title=""&gt; &lt;img class="fancyboxthumbnailsgallery" src="http://www.booclin.ovh/tom/2/index/photos/projet/06.jpg" alt=""/&gt; &lt;/a&gt; &lt;a class="fancyboxgallery" rel="book" href="http://www.booclin.ovh/tom/2/index/photos/projet/5.jpg" title=""&gt; &lt;img class="fancyboxthumbnailsgallery" src="http://www.booclin.ovh/tom/2/index/photos/projet/05.jpg" alt=""/&gt; &lt;/a&gt; &lt;a class="fancyboxgallery" rel="book" href="http://www.booclin.ovh/tom/2/index/photos/projet/4.jpg" title=""&gt; &lt;img class="fancyboxthumbnailsgallery" src="http://www.booclin.ovh/tom/2/index/photos/projet/04.jpg" alt=""/&gt; &lt;/a&gt; &lt;a class="fancyboxgallery" rel="book" href="http://www.booclin.ovh/tom/2/index/photos/projet/3.jpg" title=""&gt; &lt;img class="fancyboxthumbnailsgallery" src="http://www.booclin.ovh/tom/2/index/photos/projet/03.jpg" alt=""/&gt; &lt;/a&gt; &lt;a class="fancyboxgallery" rel="book" href="http://www.booclin.ovh/tom/2/index/photos/projet/2.jpg" title=""&gt; &lt;img class="fancyboxthumbnailsgallery" src="http://www.booclin.ovh/tom/2/index/photos/projet/02.jpg" alt=""/&gt; &lt;/a&gt; &lt;a class="fancyboxgallery" rel="book" href="http://www.booclin.ovh/tom/2/index/photos/projet/1.jpg" title=""&gt; &lt;img class="fancyboxthumbnailsgallery" src="http://www.booclin.ovh/tom/2/index/photos/projet/01.jpg" alt=""/&gt; &lt;/a&gt;</code></pre> </div> </div> </p>
<p>The error you have in console : <code>$ is not defined</code> mean jQuery is NOT loaded.</p> <p>You load it inside <code>&lt;div class="rightpart"&gt;</code> within the <code>&lt;body&gt;</code>.</p> <p>Try loading it in the <code>&lt;head&gt;</code> right before: <code>&lt;script type="text/javascript" src="index/js/jquery.fancybox.js"&gt;&lt;/script&gt;</code></p> <p><strong>EDIT</strong></p> <p>Here is your HTML copied for the code inspector of your live link:</p> <pre><code>&lt;html lang="en" class="js backgroundsize"&gt;&lt;!--&lt;![endif]--&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=1, minimum-scale=1, maximum-scale=1.0"&gt; &lt;meta name="apple-mobile-web-app-capable" content="yes"&gt; &lt;link property="stylesheet" rel="stylesheet" type="text/css" href="index/css/style.css" class="--apng-checked"&gt; &lt;link property="stylesheet" rel="stylesheet" type="text/css" href="index/font/font.css" class="--apng-checked"&gt; &lt;link rel="stylesheet" type="text/css" media="screen" href="index/css/jquery.fancybox.css" class="--apng-checked"&gt; &lt;link rel="stylesheet" media="screen" href="index/js/jquery.fancybox.css" type="text/css" class="--apng-checked"&gt; &lt;script type="text/javascript" src="index/js/jquery.fancybox.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="index/js/fancybox.js"&gt;&lt;/script&gt; &lt;style type="text/css" class="--apng-checked"&gt;.fancybox-margin{margin-right:0px;}&lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="leftpart"&gt; &lt;a href="#"&gt;PROJECT&lt;/a&gt; &lt;/div&gt; &lt;div class="rightpart"&gt; &lt;div id="globalgalerie"&gt; &lt;a class="fancyboxgallery" rel="book" href="http://www.booclin.ovh/tom/2/index/photos/projet/3.jpg" title=""&gt; &lt;img class="fancyboxthumbnailsgallery" src="http://www.booclin.ovh/tom/2/index/photos/projet/03.jpg" alt=""&gt; &lt;/a&gt; &lt;a class="fancyboxgallery" rel="book" href="http://www.booclin.ovh/tom/2/index/photos/projet/2.jpg" title=""&gt; &lt;img class="fancyboxthumbnailsgallery" src="http://www.booclin.ovh/tom/2/index/photos/projet/02.jpg" alt=""&gt; &lt;/a&gt; &lt;a class="fancyboxgallery" rel="book" href="http://www.booclin.ovh/tom/2/index/photos/projet/1.jpg" title=""&gt; &lt;img class="fancyboxthumbnailsgallery" src="http://www.booclin.ovh/tom/2/index/photos/projet/01.jpg" alt=""&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="index/js/modernizr.custom.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="index/js/jquery.fancybox.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="index/js/fancybox.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $("img").error(function() { $(this).parent().remove(); }); $("a.fancyboxgallery").fancybox(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>So what I mean is to move these line in the <code>&lt;head&gt;</code> section:</p> <pre><code>&lt;script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="index/js/modernizr.custom.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="index/js/jquery.fancybox.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="index/js/fancybox.js"&gt;&lt;/script&gt; </code></pre> <p>These ones are already in the <code>&lt;head&gt;</code>... No need to duplicate them.</p> <pre><code>&lt;script type="text/javascript" src="index/js/jquery.fancybox.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="index/js/fancybox.js"&gt;&lt;/script&gt; </code></pre> <p>Your error function is ok at the end of the <code>&lt;body&gt;</code>.</p>
Using a for loop to set background images using Javascript <p>I am trying to set background URL of all the tiles to the name in the memory array.</p> <p>I have tried:</p> <pre><code>document.getElementById('tile_' + i).style.background = 'url(' + memory_array[i] + ') no-repeat';; </code></pre> <p>But this does not work!</p> <p>I wasn't sure what to put the arrays names as ... I think <code>url(img.gif)</code> is correct?</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 memory_array = ['url(img1.gif)', 'img1.gif', 'img2.gif', 'img2.gif', 'img3.gif', 'img3.gif', 'img4.gif', 'img4.gif', 'img5', 'img5']; var memory_values = []; var memory_tile_ids = []; var tiles_flipped = 0; Array.prototype.memory_tile_shuffle = function() { var i = this.length, j, temp; while (--i &gt; 0) { j = Math.floor(Math.random() * (i + 1)); temp = this[j]; this[j] = this[i]; this[i] = temp; } } function newBoard() { tiles_flipped = 0; var output = ''; memory_array.memory_tile_shuffle(); for (var i = 0; i &lt; memory_array.length; i++) { output += '&lt;div id="tile_' + i + '" onclick="memoryFlipTile(this,\'' + memory_array[i] + '\')"&gt;&lt;/div&gt;'; } document.getElementById('memory_board').innerHTML = output; // This is the relevant line document.getElementById('tile_' + i).style.background = 'url(' + memory_array[i] + ') no-repeat'; } function memoryFlipTile(tile, val) { if (tile.innerHTML == "" &amp;&amp; memory_values.length &lt; 2) { tile.style.background = 'url(qm.gif) no-repeat'; tile.innerHTML = val; if (memory_values.length == 0) { memory_values.push(val); memory_tile_ids.push(tile.id); } else if (memory_values.length == 1) { memory_values.push(val); memory_tile_ids.push(tile.id); if (memory_values[0] == 1) { tiles_flipped += 2; //Clear both arrays memory_values = []; memory_tile_ids = []; // Check to see if the whole board is cleared if (tiles_flipped == memory_array.length) { alert("Well done your a smart person ... Can you do it again ?"); document.getElementById('memory_board').innerHTML = ""; newBoard(); } } else { function flip2back() { //Flip the 2 tiles back over var tile_1 = document.getElementById(memory_tile_ids[0]); var tile_2 = document.getElementById(memory_tile_ids[1]); tile_1.style.background = 'url(qm.gif) no-repeat'; tile_1.innerHTML = ""; tile_2.style.background = 'url(qm.gif) no-repeat'; tile_2.innerHTML = ""; // Clear both array memory_values = []; memory_tile_ids = []; } setTimeout(flip2back, 700); } } } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>div#memory_board { background: black; border: 1px solid black; width: 900px; height: 540px; padding: 24px; margin: 0px auto; margin-bottom: 10px; } div#memory_board &gt; div { background: url(qm.gif) no-repeat; background-size: 100% 100%; border: 1px solid #fff; width: 120px; height: 120px; float: left; margin: 8px; padding: 20px; font-size: 20px; cursor: pointer; text-align: center; color: white; border-radius: 5px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Basic Java&lt;/title&gt; &lt;link href='style.css' type='text/css' rel='stylesheet' /&gt; &lt;script src="java.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;!--HEADER--&gt; &lt;div class='holder header'&gt; &lt;h1&gt;Simple picture guessing game&lt;/h1&gt; &lt;/div&gt; &lt;!--Container--&gt; &lt;div id='memory_board'&gt; &lt;script&gt; newBoard(); &lt;/script&gt; &lt;!--Add window.addEventListener() for window load.--&gt; &lt;/div&gt; &lt;!--footer--&gt; &lt;div class='holder footer'&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
<blockquote> <p>// This is the relevant line</p> </blockquote> <p>That line should be</p> <pre><code>document.getElementById('tile_' + i).style.background = 'url(' + memory_array[i] + ') no-repeat'; </code></pre> <p>And your array should be</p> <pre><code>var memory_array = ['img1.gif', 'img1.gif', 'img2.gif', 'img2.gif', 'img3.gif', 'img3.gif', 'img4.gif', 'img4.gif', 'img5.gif', 'img5.gif']; </code></pre> <p>Also make sure the path to your images is correct</p> <hr> <p>Alternatively you can use <code>backgroundImage</code></p> <pre><code>document.getElementById('tile_' + i).style.backgroundImage = 'url(' + memory_array[i] + ')'; </code></pre>
ExtJS 6.2 Sort grid Panel groupings based on summary row <p>I've been searching for hours to figure out how to do this. Essentially what I want to do is group data based on one column, create a summary for that grouping, then sort the groups based on the summary.</p> <p>Using one of their kitchen sink examples, I would like to be able to sort these groups by summary value rate. </p> <p><a href="http://examples.sencha.com/extjs/6.0.0/examples/classic/grid/group-summary-grid.html" rel="nofollow">http://examples.sencha.com/extjs/6.0.0/examples/classic/grid/group-summary-grid.html</a></p>
<p>This can be done using a <em>grouper</em> with a <em>sorterFn</em>. The <em>sorterFn</em> should compare the summary values you are sorting by. For the kitchen sink example you mentioned, if you want to sort by the sum of the <em>estimate</em> column while grouping by the <em>project</em> column, the grouper would look like:</p> <pre><code>groupers: [{ property: 'project', sorterFn: function(a,b) { var suma=0; store.each(function (rec) { suma += rec.data.project === a.data.project ? rec.data.estimate:0; }); var sumb=0; store.each(function (rec) { sumb += rec.data.project === b.data.project ? rec.data.estimate:0; }); if (suma &gt; sumb) return 1; if (suma &lt; sumb) return -1; return 0; } }] </code></pre> <p>The grouper can be applied using:</p> <pre><code>store.group(store.groupers[0]); </code></pre> <p>See fiddle: <a href="https://fiddle.sencha.com/#fiddle/1im3" rel="nofollow">https://fiddle.sencha.com/#fiddle/1im3</a></p>
Creating index on nested table column <pre><code> CREATE TYPE nums_list AS TABLE OF NUMBER; CREATE TABLE mytest ( id NUMBER, num NUMBER, tagged nums_list ) NESTED TABLE tagged STORE AS mytest_tagged_table; </code></pre> <p>Now I need creating index on <code>tagged</code> nested table column.</p> <p>So according to <a href="https://docs.oracle.com/database/121/SQLRF/statements_5013.htm#i2129697" rel="nofollow">documentation </a>, Syntax is like this:</p> <pre><code>CREATE INDEX index_name ON nested_storage_table(NESTED_TABLE_ID, document_typ); </code></pre> <p>I don't get what means second parameter <code>document_typ</code> ? and not found any explanation about this.</p> <p>Any help is appreciated.</p>
<p>This is an interesting example of the Oracle documentation being out of synch. The index example should include the definitions of the types. However we can find these examples in the <a href="https://docs.oracle.com/cloud/latest/db112/LNPLS/create_type.htm#i2126557" rel="nofollow">the PL/SQL reference</a>. So <a href="https://docs.oracle.com/database/121/COMSC/scripts.htm#CHDEGCDC" rel="nofollow">PRINT_MEDIA.AD_TEXTDOCS_NTAB</a> is of type TEXTDOC_TAB which has this signature:</p> <pre><code>CREATE TYPE textdoc_typ AS OBJECT ( document_typ VARCHAR2(32) , formatted_doc BLOB ) ; CREATE TYPE textdoc_tab AS TABLE OF textdoc_typ; </code></pre> <p>So, <code>document_typ</code> is some form of metadata column in a user-defined type. There is no equivalent of this column in your case because of the way you have defined the collection type: it has no named columns to index.</p> <p>It is hard to give a definitive solution without understanding why you're using a nested table and why you think it needs an index. However, this might suit you: </p> <pre><code>CREATE OR REPLACE TYPE num_t AS OBJECT (numcol NUMBER); CREATE OR REPLACE TYPE nums_list AS TABLE OF num_t; </code></pre> <p>So you can then build an index on your table's nested storage:</p> <pre><code>CREATE INDEX index_name ON nested_storage_table(NESTED_TABLE_ID, numcol); </code></pre>
how to match two different columns in Mysql which has comma separated values <p>I have two tables: </p> <ol> <li>CampaignTable</li> </ol> <p>which has following property</p> <pre><code>id , campaign ,user_group </code></pre> <p>example would be </p> <pre><code>1 8867116213 5,11,15,16,18,20 2 8867116214 0,8,22 </code></pre> <p>Then I have another table called User Table</p> <p>with following property</p> <pre><code>id emp_id user_group </code></pre> <p>Example is like this </p> <pre><code>1 274 0,5,8,9,10,11,21,20 2 275 5,11,20 3 279 19,21,22,25 </code></pre> <p>I have to join this table and create an Array which has campaign wise user </p> <p>for example for campaign with id 1 it should give me </p> <p>274, 275</p> <p>How can I achieve this in Mysql</p> <p>Thanks</p>
<p>You should definetely normalize your data. For example consider this kind of normalization which renders almost no change to your DB structure:</p> <pre><code>INSERT INTO CampaignTable (`campaign`, `user_group`) VALUES (8867116213, 5), (8867116213, 11), (8867116213, 15), (8867116213, 16), (8867116213, 18), (8867116213, 20), (8867116214, 0), (8867116214, 8), (8867116214, 22) ; INSERT INTO UserTable (`emp_id`, `user_group`) VALUES (274, 0), (274, 5), (274, 8), (274, 9), (274, 10), (274, 11), (274, 21), (274, 20), (275, 5), (275, 11), (275, 20), (279, 19), (279, 21), (279, 22), (279, 25) ; </code></pre> <p>You could then fetch your data with a query as simple as that:</p> <pre><code>SELECT c.campaign, GROUP_CONCAT(DISTINCT u.emp_id) FROM CampaignTable c JOIN UserTable u ON c.user_group = u.user_group GROUP BY c.campaign </code></pre> <p>See <a href="http://sqlfiddle.com/#!9/e10cdb/10/0" rel="nofollow">SQLFiddle</a></p>
WebSocket connection to 'ws://localhost:2017/' failed: Invalid frame header <p>I'm trying to make an async websocket server using c#.</p> <p>I already have handshake completed, after searching a lot on the internet.<br> But after the handshake I can't seem to send any data in byte array format :( </p> <p>This is the code i'm using to send byte[] data to the accepted and connected socket (I check both!) </p> <pre><code>socket.Send(Encoding.Default.GetBytes("Hello")); //socket is a System.Net.Sockets.Socket object. </code></pre> <p>If i try to do this I get this on the client side (I use a chrome extension called "Simple Web Socket Client"):</p> <pre><code>index.js:15 WebSocket connection to 'ws://localhost:2017/' failed: Invalid frame header CLOSED: ws://localhost:2017 </code></pre> <p>(Yes 2017 is the port), but why does it say Invalid frame</p> <p>OK, i get that there is no frame header on the "hello" string, but i can't seem to find what the appropriate header is anywhere on the internet :( and YES I searched and all I get is a seriously confusing specification about RTC!</p> <p>Anybody here know what I'm doing wrong?</p>
<p>As you can see in <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers" rel="nofollow">this article</a> or in the <a href="https://tools.ietf.org/html/rfc6455" rel="nofollow">webSocket specification itself</a>, the webSocket protocol exchanges data in a specific data frame format. You don't just write bytes to a plain socket.</p> <p>Here's an example of what the frame format looks like:</p> <pre><code> 0 1 2 3 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 +-+-+-+-+-------+-+-------------+-------------------------------+ |F|R|R|R| opcode|M| Payload len | Extended payload length | |I|S|S|S| (4) |A| (7) | (16/64) | |N|V|V|V| |S| | (if payload len==126/127) | | |1|2|3| |K| | | +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + 4 5 6 7 + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + | Extended payload length continued, if payload len == 127 | + - - - - - - - - - - - - - - - +-------------------------------+ 8 9 10 11 + - - - - - - - - - - - - - - - +-------------------------------+ | |Masking-key, if MASK set to 1 | +-------------------------------+-------------------------------+ 12 13 14 15 +-------------------------------+-------------------------------+ | Masking-key (continued) | Payload Data | +-------------------------------- - - - - - - - - - - - - - - - + : Payload Data continued ... : + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + | Payload Data continued ... | +---------------------------------------------------------------+ </code></pre> <p>You must put your data in this format and you must also use the security scheme based on the previously exchanged security credentials. A webSocket is not a plain socket. You must use the webSocket protocol.</p> <p>FYI, my people don't implement webSocket endpoints from scratch, but rather pick up a library in your selected language that does all that work for you. Then, you can just send bytes and the library will take care of the protocol work for you.</p>
drupal 8 accessing input type from label template <p>How do you reference the input type of the respective form input from inside the form element label template (form-element-label.html.twig)?</p>
<p>The element type is not available in that TWIG template. You will have to hook into the form element and pass a variable to the element label hook.</p> <pre><code>/** * The contents of $variable['label'] will be passed to the preprocess * hook of the element's label. */ function theme_preprocess_form_element(array &amp;$variables) { $variables['label']['#attributes']["data-element-type"] = $variables['element']['#type']; } /** * Now we need to merge the array element we created in the previous hook * with the label's attributes. */ function theme_preprocess_form_element_label(array &amp;$variables) { $variables['attributes'] = array_merge($variables['attributes'], $variables['element']['#attributes']); } </code></pre> <p>The label will have the following output (I testes on an email element type).</p> <pre><code>&lt;label for="edit-email-addresses" data-element-type="email" class="js-form-required form-required"&gt;Email Addresses&lt;/label&gt; </code></pre> <p>Don't forget to clear caches ;)</p>
shiny mainPanel width when including markdown <p>I'm trying to include a "reactive" <code>.Rmd</code> file within a shiny application. It would summarize the user's choices and various conditions that arise. For whatever reason, I find including <code>shiny</code> <em>within</em> <code>.Rmd</code> <a href="http://rmarkdown.rstudio.com/authoring_shiny.html" rel="nofollow">documented</a>, but not including the ability to knit <code>.Rmd</code> and have the output included inside a <code>shiny</code> app.</p> <p>I find these very hard to reproduce, so here's my attempt using the <a href="http://shiny.rstudio.com/tutorial/lesson1/" rel="nofollow">hello world</a> example from Rstudio. Here's the app as-is in chromium:</p> <p><a href="https://i.stack.imgur.com/EAcTw.png" rel="nofollow"><img src="https://i.stack.imgur.com/EAcTw.png" alt="full-size"></a></p> <p>Next, I add a <code>uiOutput</code> element to <code>ui.R</code>:</p> <pre><code># Show a plot of the generated distribution mainPanel( plotOutput("distPlot"), uiOutput("mark") ) </code></pre> <p>I also add a corresponding output in <code>server.R</code>, taken from this sort of similar <a href="http://stackoverflow.com/questions/33499651/rmarkdown-in-shiny-application">question</a>:</p> <pre><code>output$mark &lt;- renderUI({ HTML(markdown::markdownToHTML(knit("./test.Rmd", quiet = TRUE))) }) </code></pre> <p>The contents of <code>test.Rmd</code> are this:</p> <pre><code>## something to print ```{r} head(mtcars, input$bins) ``` </code></pre> <p>When I run it, I now get this (screenshot footprint is the same):</p> <p><a href="https://i.stack.imgur.com/IKGw8.png" rel="nofollow"><img src="https://i.stack.imgur.com/IKGw8.png" alt="cramped"></a></p> <p>I'm assuming there's some <code>css</code> or something in the knit document that's goofing things up, but I don't know. I can force the widths wider, but the main panel stays sort of centered.</p> <hr> <p>I've tried <code>includeMarkdown</code> but wasn't able to get it to update based on <code>input</code>. Keep in mind that's the eventual hope -- I need something that can regenerate whatever is displayed based on changed <code>input</code> values. I realize I could do <code>renderText</code> or something, but the <code>Rmarkdown</code> format is so convenient as this is sort of a guide. I can write some documentation, then show the user what they've selected and what happens as a result.</p> <p>It seems close... I just can't figure out why the page goes wonky.</p> <p>I also tried stuff like <code>style = "width: 1200px"</code> or <code>style = "width: 100%"</code> without being able to get the ratio between the <code>sidebarPanel</code> and <code>mainPanel</code> back to normal.</p> <p>Ideally, the output would look just like the original, but the knit results would show up under the current footprint of the plot.</p>
<p>It appears that the rmd code adds the following property to the <code>body</code> element:</p> <pre><code>max-width: 800px; </code></pre> <p>To remove this, add the following to your ui code (for example below <code>sliderInput</code>)</p> <pre><code> tags$head(tags$style(HTML(" body { width: 100% !important; max-width: 100% !important; } "))) </code></pre>
Improved SGBM based on previous frames result <p>I was wondering if there is any good method to make SGBM process faster, by taking the info from the previous video frame. </p> <p>I think that it can be made faster by searching correspondences only near the distance of the disparity of previous frame. The problem I see in this is when from one frame to the next, the block passes from an object to background of viceversa. I think, in case to be possible, is an interesting improve to be made, and I have looked for it but I didn't find it.</p>
<p>You have told what is the problem, if the scene is in motion. I managed to wrote some algorithm that take in consideration the critical zone around the objects' borders, they were a little more accurate but very slower than SGBM. </p> <p>Maybe you can simply set the maximum and the minimum value of disparity in a reasonable range of what you find in the previous frame instead of "safe values". In my experience wuth OpenCV, stereoBM is faster but not so good as SGBM, and SGBM is better optimized than any other algorithm written by oneself (always in my experience). </p> <p>Maybe you can have some better (faster) result using the CUDA algorithm (SGBM processed in GPU). My group and I are working on that. </p>
timeInterval Variable won't work <p>I'm trying to change the timeInterval in a scheduledTimer. I'm trying to do this by changing a variable to the interval and than setting the timeInterval to this variable. I don't get any errors but the timeInterval won't change. Can someone help me?</p> <pre><code>var enemyTimer = Timer() var playTime = 0 var enemySpawnTime: Double = 3 enemyTimer = Timer.scheduledTimer(timeInterval: Double(enemySpawnTime), target: self, selector: #selector(GameScene.enemySpawn), userInfo: nil, repeats: true) playTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(GameScene.ingameTimer), userInfo: nil, repeats: true) func enemySpawn() { let enemy = SKSpriteNode(imageNamed: "Enemy") let minValue = self.size.width / 8 let maxValue = self.size.width - 20 let spawnPoint = UInt32(maxValue - minValue) enemy.position = CGPoint(x: CGFloat(arc4random_uniform(spawnPoint)), y: self.size.height) let action = SKAction.moveTo(y: -70, duration: 5) enemy.run(action) self.addChild(enemy) } func ingameTimer() { playTime += 1 if(playTime &gt;= 10 &amp;&amp; playTime &lt; 30){ enemySpawnTime = 2 print(enemySpawnTime) }else if(playTime &gt;= 30 &amp;&amp; playTime &lt; 60){ enemySpawnTime = 1 print(enemySpawnTime) }else if(playTime &gt;= 60 &amp;&amp; playTime &lt; 120){ enemySpawnTime = 0.75 print(enemySpawnTime) }else if(playTime &gt;= 120 &amp;&amp; playTime &lt; 180){ enemySpawnTime = 0.5 print(enemySpawnTime) }else if(playTime &gt;= 180 &amp;&amp; playTime &lt; 240){ enemySpawnTime = 0.25 print(enemySpawnTime) } } </code></pre> <p>I hope someone can help me! Thanks!</p>
<p>The reason why your code doesn't work is because the <code>Timer</code> object doesn't know that its interval needs to be in sync with your <code>enemySpawnTime</code>. The solution is simple, just recreate the timer when you change the enemy spawn time.</p> <p>But...</p> <p>You should <em>NEVER</em> use <code>Timer</code> (<code>NSTimer</code> prior to Swift 3) or GCD to delay stuff when you're using SpriteKit. See <a href="http://stackoverflow.com/a/23978854/5133585">this</a> for more details.</p> <p>The correct way to do this is to create a sequence of <code>SKAction</code>s.</p> <p>Assuming <code>self</code> is a subclass of <code>SKScene</code>, you can do this:</p> <pre><code>override func didMove(to view: SKView) { let waitAction = SKAction.wait(forDuration: enemySpawnTime) let enemySpawnAction = SKAction.run { self.enemySpawn() } let sequence = SKAction.sequence([waitAction, enemySpawnAction]) somePlaceholderNode.run(SKAction.repeatForever(sequence)) } </code></pre> <p>where <code>somePlaceholderNode</code> is just a node that does nothing but run the action. I'll explain this later.</p> <p>And you should do this for the other timer as well.</p> <p>Now whenever you change the timer interval, also do this:</p> <pre><code>somePlaceholderNode.removeAllActions() let waitAction = SKAction.wait(forDuration: enemySpawnTime) let enemySpawnAction = SKAction.run { self.enemySpawn() } let sequence = SKAction.sequence([waitAction, enemySpawnAction]) somePlaceholderNode.run(SKAction.repeatForever(sequence)) </code></pre> <p>Here I first remove the action that the node was running, and tell it to run almost the same action, but with a different time interval. You can add this block of code to the <code>didSet</code> block of <code>enemySpawnTime</code>:</p> <pre><code>var enemySpawnTime: Double = 3 { didSet { let waitAction = SKAction.wait(forDuration: enemySpawnTime) let enemySpawnAction = SKAction.run { self.enemySpawn() } let sequence = SKAction.sequence([waitAction, enemySpawnAction]) somePlaceholderNode.run(SKAction.repeatForever(sequence)) } } </code></pre> <p>Now your code should work!</p> <p>The reason why we want a placeholder node here is because when we remove the action by calling <code>removeAllActions</code>, we don't want to remove <em>all</em> the actions that is running.</p>
Swift 3: error: ambiguous reference to member '>' <p>I can't make sense of this error from the Swift compiler:</p> <pre><code>error: ambiguous reference to member '&gt;' let moveDirection = dx &gt; 0 ? .right : .left </code></pre> <p>Here is the code:</p> <pre><code>enum MoveDirection { case none case left case right } override func touchesMoved(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) { guard let touch = touches.first else { return; } let location = touch.location(in: humanPlayerScreen) let previousLocation = touch.previousLocation(in: humanPlayerScreen) let dx = location.x - previousLocation.x let dy = location.y - previousLocation.y let moveDirection = dx &gt; 0 ? .right : .left // error ... } </code></pre> <p>I've tried numerous things like casting both <code>dx</code> and <code>0</code> to <code>CGFloat</code> or using <code>0.0</code> but none of them worked so far.</p> <p>Can somebody explain please why is this happening and how to fix it?</p> <p>Full error message:</p> <pre><code>Swift.&gt;:5:13: note: found this candidate public func &gt;(lhs: UInt8, rhs: UInt8) -&gt; Bool ^ Swift.&gt;:5:13: note: found this candidate public func &gt;(lhs: Int8, rhs: Int8) -&gt; Bool ^ Swift.&gt;:5:13: note: found this candidate public func &gt;(lhs: UInt16, rhs: UInt16) -&gt; Bool ^ Swift.&gt;:5:13: note: found this candidate public func &gt;(lhs: Int16, rhs: Int16) -&gt; Bool ^ Swift.&gt;:5:13: note: found this candidate public func &gt;(lhs: UInt32, rhs: UInt32) -&gt; Bool ^ Swift.&gt;:5:13: note: found this candidate public func &gt;(lhs: Int32, rhs: Int32) -&gt; Bool ^ Swift.&gt;:5:13: note: found this candidate public func &gt;(lhs: UInt64, rhs: UInt64) -&gt; Bool ^ Swift.&gt;:5:13: note: found this candidate public func &gt;(lhs: Int64, rhs: Int64) -&gt; Bool ^ Swift.&gt;:5:13: note: found this candidate public func &gt;(lhs: UInt, rhs: UInt) -&gt; Bool ^ Swift.&gt;:5:13: note: found this candidate public func &gt;(lhs: Int, rhs: Int) -&gt; Bool ^ Foundation.Date:95:24: note: found this candidate public static func &gt;(lhs: Date, rhs: Date) -&gt; Bool ^ Foundation.IndexPath:51:24: note: found this candidate public static func &gt;(lhs: IndexPath, rhs: IndexPath) -&gt; Bool ^ Foundation.IndexSet.Index:5:24: note: found this candidate public static func &gt;(lhs: IndexSet.Index, rhs: IndexSet.Index) -&gt; Bool ^ CoreMedia.&gt;:1:13: note: found this candidate public func &gt;(time1: CMTime, time2: CMTime) -&gt; Bool ^ Swift.&gt;:10:13: note: found this candidate public func &gt;&lt;T : Comparable&gt;(lhs: T, rhs: T) -&gt; Bool ^ Swift.&gt;:1:13: note: found this candidate public func &gt;&lt;T : FloatingPoint&gt;(lhs: T, rhs: T) -&gt; Bool ^ Swift.&gt;:1:13: note: found this candidate public func &gt;&lt;T : _SwiftNewtypeWrapper where T.RawValue : Comparable&gt;(lhs: T, rhs: T) -&gt; Bool ^ Swift.&gt;:12:13: note: found this candidate public func &gt;&lt;A : Comparable, B : Comparable&gt;(lhs: (A, B), rhs: (A, B)) -&gt; Bool ^ Swift.&gt;:12:13: note: found this candidate public func &gt;&lt;A : Comparable, B : Comparable, C : Comparable&gt;(lhs: (A, B, C), rhs: (A, B, C)) -&gt; Bool ^ Swift.&gt;:12:13: note: found this candidate public func &gt;&lt;A : Comparable, B : Comparable, C : Comparable, D : Comparable&gt;(lhs: (A, B, C, D), rhs: (A, B, C, D)) -&gt; Bool ^ Swift.&gt;:12:13: note: found this candidate public func &gt;&lt;A : Comparable, B : Comparable, C : Comparable, D : Comparable, E : Comparable&gt;(lhs: (A, B, C, D, E), rhs: (A, B, C, D, E)) -&gt; Bool ^ Swift.&gt;:12:13: note: found this candidate public func &gt;&lt;A : Comparable, B : Comparable, C : Comparable, D : Comparable, E : Comparable, F : Comparable&gt;(lhs: (A, B, C, D, E, F), rhs: (A, B, C, D, E, F)) -&gt; Bool ^ Swift.Comparable:158:24: note: found this candidate public static func &gt;(lhs: Self, rhs: Self) -&gt; Bool ^ Swift.LazyFilterIndex&lt;Base&gt;:7:24: note: found this candidate public static func &gt;(lhs: LazyFilterIndex&lt;Base&gt;, rhs: LazyFilterIndex&lt;Base&gt;) -&gt; Bool ^ </code></pre>
<p>The error message is misleading. The problem is that you need to give Swift more information about what <code>.left</code> and <code>.right</code> are:</p> <pre><code>let moveDirection = dx &gt; 0 ? MoveDirection.right : .left </code></pre> <p>or</p> <pre><code>let moveDirection: MoveDirection = dx &gt; 0 ? .right : .left </code></pre>
Difference between two similar Goodle Unity Ads plugins <p>Tere is a two plugins for Unity from Google for having Ads in your app.</p> <p>First, based on firebase and provided via google play services:</p> <p><a href="https://github.com/googleads/googleads-mobile-unity" rel="nofollow">https://github.com/googleads/googleads-mobile-unity</a></p> <p>Second one, also well-updated, used by some people plugin for similar purposes as as well as first plugin.</p> <p><a href="https://github.com/unity-plugins/Unity-Admob" rel="nofollow">https://github.com/unity-plugins/Unity-Admob</a></p> <p>I am new in Ads in Unity3d, and I want to make it clear, what is the difference between them ?</p> <p>I think someone can give a proper answer.</p>
<p>Maybe this can help.</p> <p><a href="http://stackoverflow.com/questions/19956048/should-we-prefer-admob-in-google-play-services-compared-to-old-admob-sdk">Should we prefer AdMob in Google Play services compared to &quot;old&quot; AdMob SDK</a></p> <p>But I think to read more their docs and choose, is best solution to choose.</p>
Node JS Array, Foreach, Mongoose, Synchronous <p>I'm not that experienced with node js yet , but i'm learning.</p> <p>So my issue. Example: I have a small app with mongoose and async modules. In mongodb in a user collection i have 1 user with a field balance = 100 . </p> <pre><code>var arr = [1,2,3,4]; var userId = 1; async.forEachSeries(arr, (item, cb) =&gt;{ async.waterfall([ next =&gt; { users.findById(userId, (err, user) =&gt;{ if (err) throw err; next(null, user) }); }, (userResult,next) =&gt;{ var newBalance = userResult.balance - item; users.findByIdAndUpdate(userId, {balance:newBalance}, err =&gt;{ if (err) throw err; next(null, userResult, newBalance); }) } ],(err, userResult, newBalance) =&gt;{ console.log(`Old user balance: ${userResult.balance} New user balance: ${newBalance}`); }); cb(null) }); </code></pre> <p>And i'm receiving such result</p> <pre><code>Old user balance: 100 New user balance: 98 Old user balance: 100 New user balance: 99 Old user balance: 100 New user balance: 97 Old user balance: 100 New user balance: 96 </code></pre> <p>So basically foreach asynchronously is invoking async.waterfall . My question how to do foreach Synchronously item by item, i have tried each, forEach, eachSeries , with and without Promises. Need to get such result at the end</p> <pre><code>Old user balance: 100 New user balance: 99 Old user balance: 99 New user balance: 97 Old user balance: 97 New user balance: 94 Old user balance: 94 New user balance: 90 </code></pre> <p>Thank You</p>
<p>The problem is where the final callback got called. You need to call cb() inside of waterfall's final callback, not outside:</p> <pre><code>var arr = [1,2,3,4]; var userId = 1; async.forEachSeries(arr, (item, cb) =&gt;{ async.waterfall([ next =&gt; { users.findById(userId, (err, user) =&gt;{ if (err) throw err; next(null, user) }); }, (userResult,next) =&gt;{ var newBalance = userResult.balance - item; users.findByIdAndUpdate(userId, {balance:newBalance}, err =&gt;{ if (err) throw err; next(null, userResult, newBalance); }) } ],(err, userResult, newBalance) =&gt;{ console.log(`Old user balance: ${userResult.balance} New user balance: ${newBalance}`); cb(null); // &lt;&lt;==== call here }); // cb(null); // &lt;&lt;==== NOT call here </code></pre> <p>});</p>
php _GET parameter passed through URL trouble, any length or size restriction on the url? <p>I am moving my site to a new cPanel linux server, here is the comparison of the new and old server:</p> <p>New Server: php version:5.6.25 (Zend: 2.6.0) Database: MySQL 5.5.52-cll Server OS: Linux 2.6.18-502.el5.lve0.8.85</p> <p>Old server:(as far as I can remember) php version:5.2.36 Database: MySQL 5.3.1</p> <p>Most codes are running just fine. But one file just let me pull out my hair. Here is the trick:</p> <p>The function is for updating the product data through URL after action is set, let say I hit the "update" button after input the form area. </p> <p>For some products having less attributes the code output shorter URL like the following, the function works perfectly updating the database:</p> <p><a href="http://www.domainname.com/demo/admin/stock.php?quantity0=1&amp;product_id=188&amp;cPath=81&amp;quantity1=5&amp;product_id=188&amp;cPath=81&amp;quantity2=3&amp;product_id=188&amp;cPath=81&amp;quantity3=0&amp;product_id=188&amp;cPath=81&amp;quantity4=0&amp;product_id=188&amp;cPath=81&amp;quantity5=0&amp;product_id=188&amp;cPath=81&amp;quantity6=0&amp;product_id=188&amp;cPath=81&amp;quantity7=0&amp;product_id=188&amp;cPath=81&amp;quantity8=0&amp;product_id=188&amp;cPath=81&amp;quantity9=0&amp;product_id=188&amp;cPath=81&amp;quantity10=0&amp;product_id=188&amp;cPath=81&amp;quantity11=0&amp;product_id=188&amp;cPath=81&amp;quantity12=0&amp;product_id=188&amp;cPath=81&amp;quantity13=0&amp;product_id=188&amp;cPath=81&amp;quantity14=0&amp;product_id=188&amp;cPath=81&amp;quantity15=0&amp;product_id=188&amp;cPath=81&amp;quantity16=0&amp;product_id=188&amp;cPath=81&amp;quantity17=0&amp;product_id=188&amp;cPath=81&amp;quantity18=0&amp;product_id=188&amp;cPath=81&amp;quantity19=0&amp;product_id=188&amp;cPath=81&amp;quantity20=0&amp;product_id=188&amp;cPath=81&amp;quantity21=0&amp;product_id=188&amp;cPath=81&amp;quantity22=0&amp;product_id=188&amp;cPath=81&amp;quantity23=0&amp;product_id=188&amp;cPath=81&amp;action=Update" rel="nofollow">http://www.domainname.com/demo/admin/stock.php?quantity0=1&amp;product_id=188&amp;cPath=81&amp;quantity1=5&amp;product_id=188&amp;cPath=81&amp;quantity2=3&amp;product_id=188&amp;cPath=81&amp;quantity3=0&amp;product_id=188&amp;cPath=81&amp;quantity4=0&amp;product_id=188&amp;cPath=81&amp;quantity5=0&amp;product_id=188&amp;cPath=81&amp;quantity6=0&amp;product_id=188&amp;cPath=81&amp;quantity7=0&amp;product_id=188&amp;cPath=81&amp;quantity8=0&amp;product_id=188&amp;cPath=81&amp;quantity9=0&amp;product_id=188&amp;cPath=81&amp;quantity10=0&amp;product_id=188&amp;cPath=81&amp;quantity11=0&amp;product_id=188&amp;cPath=81&amp;quantity12=0&amp;product_id=188&amp;cPath=81&amp;quantity13=0&amp;product_id=188&amp;cPath=81&amp;quantity14=0&amp;product_id=188&amp;cPath=81&amp;quantity15=0&amp;product_id=188&amp;cPath=81&amp;quantity16=0&amp;product_id=188&amp;cPath=81&amp;quantity17=0&amp;product_id=188&amp;cPath=81&amp;quantity18=0&amp;product_id=188&amp;cPath=81&amp;quantity19=0&amp;product_id=188&amp;cPath=81&amp;quantity20=0&amp;product_id=188&amp;cPath=81&amp;quantity21=0&amp;product_id=188&amp;cPath=81&amp;quantity22=0&amp;product_id=188&amp;cPath=81&amp;quantity23=0&amp;product_id=188&amp;cPath=81&amp;action=Update</a></p> <p>BUT:</p> <p>For some products having more attributes the code output longer URL like the following, the function didn't work at all:</p> <p><a href="http://www.domainname.com/demo/admin/stock.php?quantity0=0&amp;product_id=413&amp;cPath=83&amp;quantity1=0&amp;product_id=413&amp;cPath=83&amp;quantity2=0&amp;product_id=413&amp;cPath=83&amp;quantity3=0&amp;product_id=413&amp;cPath=83&amp;quantity4=0&amp;product_id=413&amp;cPath=83&amp;quantity5=2&amp;product_id=413&amp;cPath=83&amp;quantity6=0&amp;product_id=413&amp;cPath=83&amp;quantity7=0&amp;product_id=413&amp;cPath=83&amp;quantity8=0&amp;product_id=413&amp;cPath=83&amp;quantity9=0&amp;product_id=413&amp;cPath=83&amp;quantity10=0&amp;product_id=413&amp;cPath=83&amp;quantity11=0&amp;product_id=413&amp;cPath=83&amp;quantity12=0&amp;product_id=413&amp;cPath=83&amp;quantity13=0&amp;product_id=413&amp;cPath=83&amp;quantity14=1&amp;product_id=413&amp;cPath=83&amp;quantity15=1&amp;product_id=413&amp;cPath=83&amp;quantity16=0&amp;product_id=413&amp;cPath=83&amp;quantity17=0&amp;product_id=413&amp;cPath=83&amp;quantity18=0&amp;product_id=413&amp;cPath=83&amp;quantity19=0&amp;product_id=413&amp;cPath=83&amp;quantity20=1&amp;product_id=413&amp;cPath=83&amp;quantity21=0&amp;product_id=413&amp;cPath=83&amp;quantity22=0&amp;product_id=413&amp;cPath=83&amp;quantity23=0&amp;product_id=413&amp;cPath=83&amp;quantity24=1&amp;product_id=413&amp;cPath=83&amp;quantity25=1&amp;product_id=413&amp;cPath=83&amp;quantity26=2&amp;product_id=413&amp;cPath=83&amp;quantity27=2&amp;product_id=413&amp;cPath=83&amp;quantity28=3&amp;product_id=413&amp;cPath=83&amp;quantity29=1&amp;product_id=413&amp;cPath=83&amp;quantity30=1&amp;product_id=413&amp;cPath=83&amp;quantity31=1&amp;product_id=413&amp;cPath=83&amp;quantity32=0&amp;product_id=413&amp;cPath=83&amp;quantity33=1&amp;product_id=413&amp;cPath=83&amp;quantity34=1&amp;product_id=413&amp;cPath=83&amp;quantity35=1&amp;product_id=413&amp;cPath=83&amp;quantity36=1&amp;product_id=413&amp;cPath=83&amp;quantity37=1&amp;product_id=413&amp;cPath=83&amp;quantity38=1&amp;product_id=413&amp;cPath=83&amp;quantity39=0&amp;product_id=413&amp;cPath=83&amp;action=Update" rel="nofollow">http://www.domainname.com/demo/admin/stock.php?quantity0=0&amp;product_id=413&amp;cPath=83&amp;quantity1=0&amp;product_id=413&amp;cPath=83&amp;quantity2=0&amp;product_id=413&amp;cPath=83&amp;quantity3=0&amp;product_id=413&amp;cPath=83&amp;quantity4=0&amp;product_id=413&amp;cPath=83&amp;quantity5=2&amp;product_id=413&amp;cPath=83&amp;quantity6=0&amp;product_id=413&amp;cPath=83&amp;quantity7=0&amp;product_id=413&amp;cPath=83&amp;quantity8=0&amp;product_id=413&amp;cPath=83&amp;quantity9=0&amp;product_id=413&amp;cPath=83&amp;quantity10=0&amp;product_id=413&amp;cPath=83&amp;quantity11=0&amp;product_id=413&amp;cPath=83&amp;quantity12=0&amp;product_id=413&amp;cPath=83&amp;quantity13=0&amp;product_id=413&amp;cPath=83&amp;quantity14=1&amp;product_id=413&amp;cPath=83&amp;quantity15=1&amp;product_id=413&amp;cPath=83&amp;quantity16=0&amp;product_id=413&amp;cPath=83&amp;quantity17=0&amp;product_id=413&amp;cPath=83&amp;quantity18=0&amp;product_id=413&amp;cPath=83&amp;quantity19=0&amp;product_id=413&amp;cPath=83&amp;quantity20=1&amp;product_id=413&amp;cPath=83&amp;quantity21=0&amp;product_id=413&amp;cPath=83&amp;quantity22=0&amp;product_id=413&amp;cPath=83&amp;quantity23=0&amp;product_id=413&amp;cPath=83&amp;quantity24=1&amp;product_id=413&amp;cPath=83&amp;quantity25=1&amp;product_id=413&amp;cPath=83&amp;quantity26=2&amp;product_id=413&amp;cPath=83&amp;quantity27=2&amp;product_id=413&amp;cPath=83&amp;quantity28=3&amp;product_id=413&amp;cPath=83&amp;quantity29=1&amp;product_id=413&amp;cPath=83&amp;quantity30=1&amp;product_id=413&amp;cPath=83&amp;quantity31=1&amp;product_id=413&amp;cPath=83&amp;quantity32=0&amp;product_id=413&amp;cPath=83&amp;quantity33=1&amp;product_id=413&amp;cPath=83&amp;quantity34=1&amp;product_id=413&amp;cPath=83&amp;quantity35=1&amp;product_id=413&amp;cPath=83&amp;quantity36=1&amp;product_id=413&amp;cPath=83&amp;quantity37=1&amp;product_id=413&amp;cPath=83&amp;quantity38=1&amp;product_id=413&amp;cPath=83&amp;quantity39=0&amp;product_id=413&amp;cPath=83&amp;action=Update</a></p> <p>My thinking is there might be some setting with php.ini/apache/mysql, or even the browers that restricts the length of the URL, or something else I don't even know about.</p> <p>Any idea will be appreciated.</p> <p>Seahorse</p>
<p>The de facto limit is 2000 characters. That being said, is it possible to change it? Yes. Should you change it? No, because even if you set a higher limit, some of the most popular web browsers have limitations of their own, making your application less accessible.</p> <p>Since what you are doing is an update, I would recommend you to use a POST request instead of a GET, and then simply getting the attributes from the request using the global variable $_POST.</p>
onDragOver doesn't happen (in JavaFX) <p>Why doesn't <code>onDragOver</code> event happen in the following example?</p> <p>How to implement simplest drag behaviour, i.e. w/o clipboard things?</p> <pre><code>import javafx.application.Application; import javafx.event.EventHandler; import javafx.geometry.*; import javafx.scene.Scene; import javafx.scene.input.DragEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Pane; import javafx.scene.paint.*; import javafx.stage.Stage; public class DragTry extends Application { private Point2D dragVector = null; @Override public void start(Stage primaryStage) throws Exception { Pane root = new Pane(); Pane node = new Pane(); node.setBackground(new Background(new BackgroundFill(Color.BLUE, CornerRadii.EMPTY, javafx.geometry.Insets.EMPTY))); node.setPrefWidth(100); node.setPrefHeight(50); node.setTranslateX(200); node.setTranslateY(200); node.setOnDragDetected(new EventHandler&lt;MouseEvent&gt;() { @Override public void handle(MouseEvent event) { System.out.println("odDragDetected"); double x = event.getX(); double y = event.getY(); x -= node.getTranslateX(); y -= node.getTranslateY(); dragVector = new Point2D(x, y); node.startFullDrag(); } }); node.setOnDragOver(new EventHandler&lt;DragEvent&gt;() { @Override public void handle(DragEvent event) { System.out.println("onDragOver"); double x = event.getX(); double y = event.getY(); x += dragVector.getX(); y += dragVector.getY(); node.setTranslateX(x); node.setTranslateY(y); } }); node.setOnDragDone(new EventHandler&lt;DragEvent&gt;() { @Override public void handle(DragEvent event) { dragVector = null; } }); root.getChildren().add(node); Scene scene = new Scene(root, 800, 600); primaryStage.setScene(scene); primaryStage.setTitle("DragTry"); primaryStage.show(); } public static void main(String[] args) { DragTry.launch(args); } } </code></pre>
<p>First, you need to call <code>startDragAndDrop</code>, instead of <code>startFullDrag</code>. The different drag modes are described in the <a href="http://docs.oracle.com/javase/8/javafx/api/javafx/scene/input/MouseEvent.html" rel="nofollow">documentation for <code>MouseEvent</code></a>. Additionally, one annoying part of the drag and drop API is that dragging isn't activated unless you add something to the dragboard:</p> <pre><code> node.setOnDragDetected(new EventHandler&lt;MouseEvent&gt;() { @Override public void handle(MouseEvent event) { System.out.println("odDragDetected"); double x = event.getX(); double y = event.getY(); x -= node.getTranslateX(); y -= node.getTranslateY(); dragVector = new Point2D(x, y); Dragboard db = node.startDragAndDrop(TransferMode.COPY_OR_MOVE); ClipboardContent cc = new ClipboardContent(); cc.putString("Something"); db.setContent(cc); } }); </code></pre>
Google Sign In for websites: Can't render sign-in button <p>I am following the official guide <a href="https://developers.google.com/identity/sign-in/web/sign-in" rel="nofollow">here</a> and can't get a button to render. I'm not a front-end dev but have to get this working to demonstrate some backend functionality. Since the guide might assume some things that are obvious to front-end devs, I'll explain what I did to achieve the guide steps.</p> <ul> <li>Under "Load the Google Platform Library", I put that tag under the tag</li> <li>Under "Specify your app's client ID", I put that, with my clientId substituted, also under the tag, directly before the from previous step</li> <li>Under "Add a Google Sign-In button", I placed that Tag somewhere in the body of my page, next to a <p> tag that successfully renders text (to be sure I wasn't in a hidden div)</li> </ul> <p>At this point, when I refresh my page, I cannot see the sign-in button anywhere. Thinking it might have to do with the JS function from the next step missing, I added that function within the tag, directly after I open the tag.</p> <p>Still no button. I tried to put the code in jsfiddle, like another user suggested, but I couldn't figure out even where to put and tags in jsfiddle, because when I entered a tag, JSFiddle told me that it was already included for me, but I could not find it to add my tags to it.</p> <p>I took all my application code out and created a bare page with just the bits from Google to demonstrate how I'm trying to use the library. I've pasted that code to pastebin <a href="http://pastebin.com/M1ux89ZQ" rel="nofollow">here</a></p>
<p>Here's how you can use <a href="https://developers.google.com/identity/sign-in/web/build-button" rel="nofollow">Google's Sign-In button</a> template to initialize the login &amp; grant of permissions process in a slightly more elegant manner:</p> <pre class="lang-html prettyprint-override"><code>&lt;meta name="google-signin-client_id" content="{{ OAUTH2_CLIENT_ID }}"&gt; &lt;script src="https://apis.google.com/js/platform.js?onload=onLoad" async defer&gt;&lt;/script&gt; &lt;div id="google-signin-button" class="g-signin2" data-width="170" data-height="30" data-onsuccess="onSignIn" data-onfailure="onSignInFailure"&gt; &lt;/div&gt; </code></pre> <pre class="lang-js prettyprint-override"><code>function onSignIn(googleUser) { var profile = googleUser.getBasicProfile(); var idToken = googleUser.getAuthResponse().id_token; } function onSignOut(){ var auth2 = gapi.auth2.getAuthInstance(); auth2.signOut(); } </code></pre>
Jackson YAML: support for anchors and references <p>I'm investigating the use of YAML for a somewhat complicated metadata language. It would help to make the documents smaller and less complex if we could use <a href="http://camel.readthedocs.io/en/latest/yamlref.html#anchors" rel="nofollow">YAML's anchors and references</a>. I've written some test code that seems to show that Jackson's YAML implementation doesn't support this feature (and/or doesn't surface SnakeYAML's support for this feature).</p> <p>Here is my test YAML file:</p> <pre><code>set_one: bass: tama rockstar 22x16 snare: &amp;ludwig ludwig supralight 6.5x15 tom1: tama rockstar 12x11 tom2: tama rockstar 16x16 set_two: snare: *ludwig </code></pre> <p>I'm parsing this file like so:</p> <pre><code> ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); FileInputStream fis = null; try { fis = new FileInputStream(file); JsonNode nodeTree = mapper.readTree(fis); examineObject(nodeTree, 0); } ... </code></pre> <p>Here is the out from my "examineObject()" method (you can probably guess what it does):</p> <pre><code>key = "set_one", type = OBJECT key = "bass", type = STRING, value = "tama rockstar 22x16" key = "snare", type = STRING, value = "ludwig supralight 6.5x15" key = "tom1", type = STRING, value = "tama rockstar 12x11" key = "tom2", type = STRING, value = "tama rockstar 16x16" key = "set_two", type = OBJECT key = "snare", type = STRING, value = "ludwig" </code></pre> <p>Clearly something knew enough to omit the anchor value from "set_one.snare" but, in the debugger, I can't find that value anywhere in the JsonNode for this element. The real problem is that the value of "set_two.snare" is just "ludwig". The reference symbol ('*') has been stripped, but the value is that of the reference and not the element it is referring to.</p> <p>I'm using Jackson version 2.8.3 and SnakeYaml version 1.17. I am constrained to using Jackson as this is only part of a much bigger project which already uses Jackson for JSON.</p> <p>What I would really like is if Jackson could automatically resolve references and make a copy of the referenced value. In my example this would mean that the value of "set_two.snare" would be "ludwig supralight 6.5x15".</p> <p>If I can't get my first choice then I would like Jackson to preserve both the anchors and the references so that I could manually post-process the node tree and resolve the references myself. For example, when I saw that the value of "set_two.snare" was "*ludwig", I could search the tree for a node with an anchor of "&amp;ludwig" and make a copy of that node.</p> <p>If there is an answer, I have the feeling that it will probably involve the "com.fasterxml.jackson.dataformat.yaml.YAMLParser.Feature" class somehow. Unfortunately I can't find any documentation on the features (if they exist) that will enable the behavior I am looking for.</p>
<p>First, Jackson actually does support YAML anchors and references, at least to degree they work with how Jackson supports Object Id references with <code>@JsonIdentityInfo</code>: limitation being that you can not -- for example -- refer to one key/value pair of am Object.</p> <p>But identity id/reference handling is only enabled for types and properties specified by annotating then with <code>@JsonIdentityInfo</code>. So you have to annotate either types that may be referenced, or properties (no need to do both).</p> <p>One thing that may help here is to consider that Object Id handling by Jackson is very similar for all formats: so although <code>jackson-dataformat-yaml</code> does expose "native" Object (and Type) Ids that YAML has (and JSON does not have), handling at databinding level is identical. So if you can make Object Id/References work with JSON (which adds extra id property), it will work with YAML as well.</p> <p>There is one extra thing that is related: <code>YAMLParser.Feature.USE_NATIVE_OBJECT_ID</code> which determines how references and ids are expressed when writing YAML -- by default, it uses native anchors, but it can be turned off to use "JSON-like" plain properties.</p> <p>I hope this helps. For additional help the best place would be <code>jackson-users</code> mailing list.</p>
Keras mixture of models <p>Is it possible to implement MLP mixture of expert methodology in Keras? Could you please guide me by a simple code in Keras for a binary problem with 2 experts.</p> <p>It needs to define a cost function like this:</p> <pre class="lang-python prettyprint-override"><code>g = gate.layers[-1].output o1 = mlp1.layers[-1].output o2 = mlp2.layers[-1].output def ME_objective(y_true, y_pred): A = g[0] * T.exp(-0.5*T.sqr(y_true – o1)) B = g[1] * T.exp(-0.5*T.sqr(y_true – o2)) return -T.log((A+B).sum()) # cost </code></pre>
<h2>Model</h2> <p>You can definitely model such a structure in Keras, with <a href="https://keras.io/getting-started/sequential-model-guide/#the-merge-layer" rel="nofollow">a merge layer</a>, which enables you to combine different inputs. Here is a <a href="http://sscce.org/" rel="nofollow">SSCCE</a> that you'll hopefully be able to adapt to your structure</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from keras.engine import Merge from keras.models import Sequential from keras.layers import Dense import keras.backend as K xdim = 4 ydim = 1 gate = Sequential([Dense(2, input_dim=xdim)]) mlp1 = Sequential([Dense(1, input_dim=xdim)]) mlp2 = Sequential([Dense(1, input_dim=xdim)]) def merge_mode(branches): g, o1, o2 = branches # I'd have liked to write # return o1 * K.transpose(g[:, 0]) + o2 * K.transpose(g[:, 1]) # but it doesn't work, and I don't know enough Keras to solve it return K.transpose(K.transpose(o1) * g[:, 0] + K.transpose(o2) * g[:, 1]) model = Sequential() model.add(Merge([gate, mlp1, mlp2], output_shape=(ydim,), mode=merge_mode)) model.compile(optimizer='Adam', loss='mean_squared_error') train_size = 19 nb_inputs = 3 # one input tensor for each branch (g, o1, o2) x_train = [np.random.random((train_size, xdim)) for _ in range(nb_inputs)] y_train = np.random.random((train_size, ydim)) model.fit(x_train, y_train) </code></pre> <h2>Custom Objective</h2> <p>Here is an implementation of the objective you described. There are a few <strong>mathematical concerns</strong> to keep in mind though (see below).</p> <pre class="lang-py prettyprint-override"><code>def me_loss(y_true, y_pred): g = gate.layers[-1].output o1 = mlp1.layers[-1].output o2 = mlp2.layers[-1].output A = g[:, 0] * K.transpose(K.exp(-0.5 * K.square(y_true - o1))) B = g[:, 1] * K.transpose(K.exp(-0.5 * K.square(y_true - o2))) return -K.log(K.sum(A+B)) # [...] edit the compile line from above example model.compile(optimizer='Adam', loss=me_loss) </code></pre> <h2>Some Math</h2> <p>Short version: somewhere in your model, I think there should be at least one constraint (maybe two):</p> <blockquote> <p>For any <code>x</code>, <code>sum(g(x)) = 1</code></p> <p>For any <code>x</code>, <code>g0(x) &gt; 0 and g1(x) &gt; 0</code> <em># might not be strictly necessary</em></p> </blockquote> <p><strong>Domain study</strong></p> <ol> <li><p>If <code>o1(x)</code> and <code>o2(x)</code> are infinitely <strong>far</strong> from <code>y</code>:</p> <ul> <li>the exp term tends toward +0</li> <li><code>A -&gt; B -&gt; +-0</code> depending on <code>g0(x)</code> and <code>g1(x)</code> signs</li> <li><code>cost -&gt; +infinite</code> or <code>nan</code></li> </ul></li> <li><p>If <code>o1(x)</code> and <code>o2(x)</code> are infinitely <strong>close</strong> to <code>y</code>:</p> <ul> <li>the exp term tends toward 1</li> <li><code>A -&gt; g0(x)</code> and <code>B -&gt; g1(x)</code></li> <li><code>cost -&gt; -log(sum(g(x)))</code></li> </ul></li> </ol> <p>The problem is that <code>log</code> is only defined on <code>]0, +inf[</code>. Which means that for the objective to be always defined, there needs to be a constraint somewhere ensuring <code>sum(A(x) + B(x)) &gt; 0</code> for <strong>any</strong> <code>x</code>. A more restrictive version of that constraint would be (<code>g0(x) &gt; 0</code> and <code>g1(x) &gt; 0</code>).</p> <p><strong>Convergence</strong></p> <p>An even more important concern here is that this objective does not seem to be designed to converge towards 0. When <code>mlp1</code> and <code>mlp2</code> start predicting <code>y</code> correctly (case 2.), there is currently nothing preventing the optimizer to make <code>sum(g(x))</code> tend towards <code>+infinite</code>, to make <code>loss</code> tend towards <code>-inifinite</code>.</p> <p>Ideally, we'd like <code>loss -&gt; 0</code>, i.e. <code>sum(g(x)) -&gt; 1</code></p>
GitHub: Can't find remote repository after re-installation <p>I've re-installed the git bash. And when I tried to clone from one of my private repository, I was told that </p> <pre><code>remote: Repository not found. fatal: repository 'https://github.com/&lt;MY REPO ADDRESS&gt;/' not found </code></pre> <p>I've checked that my username and email were all correct using the command</p> <pre><code>git config user.name git config user.email </code></pre> <p>Why couldn't git find the repository? Is it because I forgot to configure something else?</p> <p>Here is a snapshot of the command line: <a href="https://i.stack.imgur.com/hs9BE.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/hs9BE.jpg" alt="enter image description here"></a></p>
<p>The user.name and user.email have nothing to do with https authentication.<br> The former is for commits, the latter uses the GitHub username and password.</p> <p>Since I don't see a debugging.git repo in <a href="https://github.com/neolicd?tab=repositories" rel="nofollow">your repo page</a>, it could be a private repo (in which case double-check the username and password you should have to enter when cloning it).<br> Or it does not exist (in which case, <a href="https://help.github.com/articles/create-a-repo/" rel="nofollow">create it on GitHub first</a>)</p>
Sort Single Linked List in descending order <p>How would I display this linked list in desending order by Score? I need it when it when I display it in my GUI to sort by the highest score at the top, and then desending to the lowest score in the bottom? Also, I was wondering if there is a way to limit the entries to only 10. Any help would be appreciated! Thanks.</p> <pre><code>public class ScoreList { private Player head; //reference to the head of the list private Player tail; //reference to the tail of the list int count; public ScoreList() { count = 0; head = null; tail = null; } public int getCount() { return count; } public int size() { int count = 0; Player p = head; while(p != null) { count++; p = p.next; } return count; } //method to add an item to the list - append to the tail of the list public void add(String name, String score) { // Create Player object Player newPlayer = new Player(name, score); if (head == null) { head = newPlayer; tail = head; count++; } else { //append to the end of the list tail.setNext(newPlayer); tail = newPlayer; count++; } if(size() &gt; 10) { Player currentPlayer = head; for (int i = 0; i &lt; 9; i++) { currentPlayer = currentPlayer.next; } currentPlayer.next = null; } } // end add method //method to let the user get the data from a node in the list public String getItem(int index) { String result = ""; String name = ""; String score = ""; Player curName; if (count &gt; 0 &amp;&amp; index == 0) { //return the Player info at the head of the list name = head.getName(); score = head.getScore(); } else if (index &gt; 0 &amp;&amp; index &lt; count) { curName = head; for (int i = 1; i &lt;= index; i++) { curName = curName.getNext(); } name = curName.getName(); score = curName.getScore(); } result = "Player: " + name + " Score: " + score; return result; } //nested inner class public class Player { private String player; private String score; private Player next; public Player() { player = ""; score = ""; next = null; } public Player(String artist, String title) { this.player = artist; this.score = title; next = null; } public String getName() { return player; } public String getScore() { return score; } public Player getNext() { return next; } public void setArtist(String player) { this.player = player; } public void setTitle(String score) { this.score = score; } public void setNext(Player next) { this.next = next; } } } </code></pre>
<p>Why are you taking Score as a String?</p> <p>I am assuming score as Integer</p> <p>below is the sort method that you can include in ScoreList class, which will sort your LinkList in descending order of player score. </p> <ul> <li>Time Complexity : O(nlogn)</li> <li>Space COmplexity: O(n)</li> </ul> <p>Hope this helps</p> <pre><code>public void sort() { Player runner = head; Player[] arr = new Player[size()]; int i = 0; while (runner != null) { arr[i++] = runner; runner = runner.next; } Arrays.sort(arr, new Comparator&lt;Player&gt;() { public int compare(Player o1, Player o2) { if (Integer.parseInt(o1.getScore()) &gt; Integer.parseInt(o2.getScore())) { return -1; } else if (Integer.parseInt(o1.getScore()) &lt; Integer.parseInt(o2.getScore())) { return 1; } else { return 0; } } }); for (int j = 0; j &lt; arr.length - 1; j++) { arr[j].setNext(arr[j + 1]); } if (arr.length &gt; 0) { arr[arr.length - 1].setNext(null); head = arr[0]; tail = arr[arr.length - 1]; } } </code></pre>
asp.NET and SQL Server datetime issues <p>I am having hard time to store date information into the datetime column of SQL Server.</p> <p>I get the input from the user for three columns:</p> <ol> <li>Creation Date</li> <li>Preparation Date</li> <li>Next Preparation Date</li> </ol> <p>I use calendarextender and format the date as "yyyy/MM/dd". When all the fields have date, they are stored in the DB as for instance, 16-10-2016 (dd-MM-yyyy).</p> <p>At this point I have two issues:</p> <ol> <li><p>These columns are optional, when some of them are empty my code does not work (I assume because datetime cannot be null). To overcome this, I am using the following code snippet but still does not work.</p> <pre><code>DateTime? creationDate= null; if (creationDateTextbox.Text != null &amp;&amp; creationDateTextbox.Text != "") { creationDate= Convert.ToDateTime(creationDateTextbox.Text); } </code></pre></li> <li><p>When I fetch the dates from DB, they are shown as 10/16/2016 (MM-dd-yyyy) which is different how I formatted it. I would like to show it in the format user enters them.</p></li> </ol>
<p>Dates do not have a format while stored in a database. It is actually usually just a very large <code>long</code> that counts the number of milliseconds from a set starting date.</p> <p>If you want to store the format you need to stop storing it as dates and instead just treat the text as text in the database, however if you do this you won't get the advantage of sorting or filtering by a date range because it will just be seen as text.</p>
Python system libraries leak into virtual environment <p>While working on a new python project and trying to learn my way through virtual environments, I've stumbled twice with the following problem:</p> <ul> <li>I create my virtual environment called venv. Running <code>pip freeze</code> shows nothing. </li> <li>I install my dependencies using pip install dependency. the venv library starts to populate, as confirmed by pip freeze. </li> <li>After a couple of days, I go back to my project, and after activating the virtual environment via <code>source venv/bin/activate</code>, when running pip freeze I see the whole list of libraries installed in the system python distribution (I'm using Mac Os 10.9.5), instead of the small subset I wanted to keep inside my virtual environment. </li> </ul> <p>I'm sure I must be doing something wrong in between, but I have no idea how could this happen. Any ideas? </p> <hr> <p>Update: after looking at <a href="http://stackoverflow.com/a/33366748/3294665">this</a> answer, I realized the that when running <code>pip freeze</code>, the <code>pip</code> command that's being invoked is the one at <code>/usr/local/bin/pip</code> instead of the one inside my virtual environment. So the virtual environment is fine, but I wonder what changes in the path might be causing this, and how to prevent them to happen again (my PYTHONPATH variable is not set).</p>
<p>I realized that my problem arose when moving my virtual environment folder around the system. The fix was to modify the <code>activate</code> and <code>pip</code> scripts located inside the <code>venv/bin</code> folder to point to the new venv location, as suggested by <a href="http://stackoverflow.com/a/16683703/3294665">this</a> answer. Now my pip freeze is showing the right files.</p>
reading a csv file into a array <p>I am completely new to java (just started this week). I am trying to read the csv file, "read_ex.csv", into an array. I have searched endlessly on the web/satckoverflow to find a way to read the file into an array. The best i have been able to do is read it in a streaming fashion, but I cant store it in an array due the variable size of the file. I belive that ArrayList is a method to deal with variable size array, but I don't know how to work with it. Essentially I want to be able to access the String array "values" after the while loop finishes. </p> <pre><code>import java.util.Scanner; import java.io.FileNotFoundException; import java.io.File; public class sortarray { public static void main (String []agrs){ String fileName= "read_ex.csv"; File file= new File(fileName); try{ Scanner inputStream= new Scanner(file); while(inputStream.hasNext()){ String data= inputStream.next(); String[] values = data.split(","); System.out.println(values[1]); } inputStream.close(); }catch (FileNotFoundException e) { e.printStackTrace(); } //This prints out the working directory System.out.println("Present Project Directory : "+ System.getProperty("user.dir")); } } </code></pre> <p>As i mentioned, I am new to java and wold be open to any method that reads a csv into a file that a beginner could understand.</p>
<p><img src="https://commons.apache.org/proper/commons-csv/images/logo.png" ></p> <blockquote> <p>I am new to java and wold be open to any method that reads a csv into a file that a beginner could understand.</p> </blockquote> <p>Here is an existing solution for you from <a href="http://commons.apache.org/" rel="nofollow">Apache Commons</a>, the <a href="https://commons.apache.org/proper/commons-csv/" rel="nofollow"><em>Apache Commons CSV</em></a> project. See the <a href="https://commons.apache.org/proper/commons-csv/user-guide.html" rel="nofollow">Apache Commons CSV parser guide</a>.</p> <p>It is very easy to use out of the box. </p> <p>Here is a basic worfklow: </p> <ul> <li>Create a class that has the fields that "match" the columns of <a href="https://en.wikipedia.org/wiki/Comma-separated_values" rel="nofollow">csv</a> file.</li> <li>Each row in your csv is an object of that class with properties corresponding to the fields in your csv. Use the library to get each field and store it in your object in a loop.</li> <li>In your loop, you will store the object with the fields/properties read from the csv in the ArrayList </li> <li>After the loop ends, your ArrayList will have elements that "matches" the rows in your csv file. You are free to access any of the rows/elements in the list. </li> </ul> <p>If you are not familiar with how <a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" rel="nofollow"><code>List</code></a> and <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html" rel="nofollow"><code>ArrayList</code></a> works in Java, please refer to pretty much any Java tutorials online including the <a href="http://docs.oracle.com/javase/tutorial/collections/TOC.html" rel="nofollow">Oracle Tutorial</a>.</p> <p><a href="http://stackoverflow.com/search?q=Apache+Commons+CSV">Search Stackoverflow</a> for hundreds of posts about using Commons CSV.</p>
JAVA - creating basic 2D shapes that scale to window size <p>I am trying to learn Java by reading and doing examples out of a textbook I found online. I was able to do an example in the book fairly easily but want to take it one step further. When I wrote the code for a program called 'concentric circles' I noticed that my circles didn't scale to the size of the window and I think it looks horrible (If I make the window too small the circles don't scale and you only see a piece of the circles. I tweaked my code and it seems to scale a little bit but looks terrible when I make my window too small or too large. I would like my 12 circles to fit the window size no matter the size of the window. I feel like I am so close but just can't seem to wrap my head around it. Any and all help is much appreciated, thanks in advance!</p> <pre><code>import java.awt.Graphics; import javax.swing.JPanel; public class Circles extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); int width = getWidth(); int height = getHeight(); int x = width / 12; int y = height / 12; int buffersize = 0; for (int i = 0; i &lt; 12; i++) { g.drawOval(width / 2 - buffersize, height / 2 - buffersize, x + buffersize * 2, y + buffersize * 2); buffersize += 10; } } } </code></pre> <p>Driver class</p> <pre><code>import javax.swing.JFrame; import javax.swing.JOptionPane; /** * * @author */ public class ConcentricCirclesTest { public static void main(String[] args) { //create a panel that will contain our drawing Circles panel = new Circles(); //create a new frame to house the panel JFrame application = new JFrame(); //set the frame to exit when closed application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); application.add(panel); application.setSize(350, 350); application.setVisible(true); } } </code></pre>
<p>If you want your circles to be circular (not elliptical) then first off you need to know which is narrower, the width or the height. Using the syntax shortcut for <code>if...else</code> you'd want something like: </p> <pre><code>int smallest = width &lt; height ? width : height; </code></pre> <p>Next you need to think about how far apart your circles will be. It's no good trying to draw 12 circles that get bigger (or smaller) by 10 pixels if you only have 100 pixels to draw them in. Likewise if you've 500 pixels of space. So something like: </p> <pre><code>float spacing = smallest / 12f; </code></pre> <p>Note that you can get unexpected results dividing one <code>int</code> with another. Then in your <code>for</code> loop: </p> <pre><code>g.drawOval(0 + ((spacing / 2) * i), 0 + ((spacing / 2) * i), smallest - ((spacing / 2) * i), smallest - ((spacing / 2) * i)); </code></pre> <p>I hope thus is clear. Basically,the bounding rectangle (or square) gets smaller by <code>spacing</code> for each iteration.</p> <p>OK, this is going to need tweeking so it doesn't draw in the bottom left and I think the last circle would be 0 by 0 but I hope this is of some help. And good luck!</p>
DataBinding: How to create RecyclerView Adapter with same model and different layout? <p>I use same adapter for two different item layouts. One is for grid, one is for linear display. I'm passing layout id with itemLayout to adapter. However, I wasn't able to add data binding properly. Could you help me out, please?</p> <p>Here is my adapter effort so far:</p> <pre><code>public class OyuncuAdapter extends RecyclerView.Adapter&lt;OyuncuAdapter.ViewHolder&gt; { ArrayList&lt;Oyuncu&gt; oyuncuListesi; Context context; int itemLayout; public OyuncuAdapter(ArrayList&lt;Oyuncu&gt; oyuncuListesi, Context context, int itemLayout) { this.oyuncuListesi = oyuncuListesi; this.context=context; this.itemLayout = itemLayout; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(context).inflate(itemLayout, parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(ViewHolder holder, int position) { Oyuncu oyuncu = oyuncuListesi.get(position); holder.binding.setVariable(BR.oyuncu, oyuncu); holder.binding.executePendingBindings(); } @Override public int getItemCount() { return oyuncuListesi.size(); } public static class ViewHolder extends RecyclerView.ViewHolder{ private ViewDataBinding binding; public ViewHolder(View itemView) { super(itemView); binding = DataBindingUtil.bind(itemView); } } } </code></pre> <p>Here is the item layout:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto"&gt; &lt;data&gt; &lt;variable name="oyuncu" type="com.figengungor.suits.model.Oyuncu" /&gt; &lt;/data&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" android:padding="@dimen/itemPadding" tools:background="@color/darkgrey"&gt; &lt;ImageView android:id="@+id/foto" android:layout_width="150dp" android:layout_height="150dp" android:gravity="center" android:scaleType="centerCrop" app:imageResource="@{oyuncu.foto}" tools:src="@drawable/gabrielmacht" /&gt; &lt;TextView android:id="@+id/isim" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:textColor="@android:color/white" android:text="@{oyuncu.isim}" tools:text="Gabriel Macht" /&gt; &lt;/LinearLayout&gt; &lt;/layout&gt; </code></pre> <p>The error I'm getting is not really helpful: </p> <pre><code>Caused by: java.lang.RuntimeException: view tag isn't correct on view:null </code></pre>
<p>My bad. This part works perfectly. My problem is extending BaseActivity which also uses DataBinding. The crash is related to that. After removing extending BaseActivity from my activity, it worked. However, I opened another question realted to that. If you could look at that, I'll be grateful. <a href="http://stackoverflow.com/questions/40076251/databinding-how-to-use-baseactivity">DataBinding: How to use BaseActivity</a></p>
Maven - Is `maven-archetype-simple` a valid archetype? <p>Usually, I create maven jar project with archetype <code>maven-archetype-quickstart</code>, it works well.</p> <p>But I want to create Maven project with no sample <code>App.java</code> class, thus I tried <code>maven-archetype-simple</code> archetype, and get error.</p> <p><strong>Maven command:</strong></p> <p><code>mvn archetype:generate -DgroupId=eric -DartifactId=hello -Dversion=0.1 -DarchetypeArtifactId=maven-archetype-simple -DinteractiveMode=false -X -DarchetypeCatalog=local</code> </p> <p><strong>Error tip:</strong></p> <blockquote> <p>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:2.4:generate (default-cli) on project standalone-pom: The defined artifact is not an archetype -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:2.4:generate (default-cli) on project standalone-pom: The defined artifact is not an archetype at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288) at org.apache.maven.cli.MavenCli.main(MavenCli.java:199) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356) Caused by: org.apache.maven.plugin.MojoFailureException: The defined artifact is not an archetype at org.apache.maven.archetype.mojos.CreateProjectFromArchetypeMojo.execute(CreateProjectFromArchetypeMojo.java:205) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207) ... 20 more Caused by: org.apache.maven.archetype.exception.ArchetypeGenerationConfigurationFailure: The defined artifact is not an archetype at org.apache.maven.archetype.ui.generation.DefaultArchetypeGenerationConfigurator.configureArchetype(DefaultArchetypeGenerationConfigurator.java:150) at org.apache.maven.archetype.mojos.CreateProjectFromArchetypeMojo.execute(CreateProjectFromArchetypeMojo.java:189) ... 22 more [ERROR] [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] <a href="http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException" rel="nofollow">http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException</a></p> </blockquote> <p><strong>The questions are:</strong></p> <ul> <li>Is <code>maven-archetype-simple</code> a valid archetype?<br> In the official doc of maven, it says <code>maven-archetype-simple</code> is a archetype, refer: <a href="https://maven.apache.org/guides/introduction/introduction-to-archetypes.html" rel="nofollow">https://maven.apache.org/guides/introduction/introduction-to-archetypes.html</a> , but it won't work in my test, so get confused.</li> <li>How to create Maven project without the generated code <code>App.java</code>?</li> </ul>
<p>The artifact <code>maven-archetype-simple</code> <a href="http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-simple/" rel="nofollow">does exist on Maven Central</a>, but it isn't a valid archetype since it doesn't containt the right metadata files. A valid archetype <a href="http://maven.apache.org/archetype/archetype-models/archetype-descriptor/archetype-descriptor.html" rel="nofollow">must have in its JAR file</a>:</p> <ul> <li>either a <code>META-INF/maven/archetype-metadata.xml</code> (this is the new format);</li> <li>or a <code>META-INF/maven/archetype.xml</code> or even a <code>META-INF/archetype.xml</code> (this is the old format).</li> </ul> <p>And that specific artifact, as it is present on Central, doesn't have those files. As such, it isn't considered a valid archetype for the plugin. Those files store the required parameters for the archetype, their possible default values, the files that it should use, etc. so they really are required.</p> <p>I'm not sure there exists an archetype that would generate <em>just</em> a lone <code>pom.xml</code> with the given Maven coordinates. This is effectively what using the <code>maven-archetype-quickstart</code>, without generating the <code>App.java</code> and <code>AppTest.java</code> would do. Keep in mind that an archetype is really intended at creating a project from a pre-defined template, like a sample Java EE application, or a sample Maven project; all of those would require more set-up than just writing a POM file.</p> <p>If you really, <em>really</em>, do not want those files, you can either</p> <h3><a href="https://maven.apache.org/guides/mini/guide-creating-archetypes.html" rel="nofollow">Create your own archetype</a></h3> <p>Create a new Maven project, for example <code>my-simple-archetype</code>, with the following directory structure:</p> <pre><code>pom.xml src \---main \---resources +---archetype-resources | pom.xml | \---META-INF \---maven archetype-metadata.xml </code></pre> <p>Content of <code>pom.xml</code> at the root:</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;eric&lt;/groupId&gt; &lt;artifactId&gt;my-simple-archetype&lt;/artifactId&gt; &lt;version&gt;0.1&lt;/version&gt; &lt;packaging&gt;maven-archetype&lt;/packaging&gt; &lt;build&gt; &lt;extensions&gt; &lt;extension&gt; &lt;groupId&gt;org.apache.maven.archetype&lt;/groupId&gt; &lt;artifactId&gt;archetype-packaging&lt;/artifactId&gt; &lt;version&gt;2.4&lt;/version&gt; &lt;/extension&gt; &lt;/extensions&gt; &lt;pluginManagement&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-archetype-plugin&lt;/artifactId&gt; &lt;version&gt;2.4&lt;/version&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/pluginManagement&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>Content of the <code>src/main/resources/archetype-resources/pom.xml</code>:</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;${groupId}&lt;/groupId&gt; &lt;artifactId&gt;${artifactId}&lt;/artifactId&gt; &lt;version&gt;${version}&lt;/version&gt; &lt;/project&gt; </code></pre> <p>And finally, content of the <code>src/main/resources/META-INF/maven/archetype-metadata.xml</code>:</p> <pre><code>&lt;archetype&gt; &lt;id&gt;my-simple-archetype&lt;/id&gt; &lt;/archetype&gt; </code></pre> <p>Now you can build this project and install it:</p> <pre class="lang-none prettyprint-override"><code>cd my-simple-archetype mvn clean install </code></pre> <p>This will update your local catalog so that this new archetype is available. You can finally use it! In a new directory, do</p> <pre class="lang-none prettyprint-override"><code>mvn archetype:generate -DgroupId=eric -DartifactId=hello -Dversion=0.1 -DarchetypeArtifactId=my-simple-archetype -DarchetypeGroupId=eric -DinteractiveMode=false </code></pre> <p>And you will have as result your wanted project... which consists of the lone <code>pom.xml</code>. So, of course, you can now <a href="http://maven.apache.org/archetype/archetype-models/archetype-descriptor/archetype-descriptor.html" rel="nofollow">customize this archetype of yours</a>.</p> <h3>Remove the files</h3> <p>Or you decide that it is not worth the effort, and it is a lot simpler to remove the files after their creation:</p> <pre class="lang-none prettyprint-override"><code>mvn archetype:generate -DgroupId=eric -DartifactId=hello -Dversion=0.1 -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false rmdir /S /Q hello\src </code></pre> <p>Or <code>rm -rf hello/src</code> if you're on a Linux machine.</p>
using inappbrowser to convert website to mobile app without showing the link of the website <p>I am using phonegap to be able to have my website (that is already hosted in shared hosting server) and has responsive web design. I have tried the solution provided in posted question:</p> <ol> <li>typing my website link in src, that has been done successfully as the index page is loaded and no website link shown in the app, but once the user click on any button (which basically go to other website pages) it will open it inside the app but the link of the webpage is shown, you can see the screenshout I took from my mobile (android). </li> </ol> <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;content src="http://192.168.1.4:8080/www/index.html" /&gt;</code></pre> </div> </div> </p> <p>I have followed the same instruction in the answer and set the target to _self in the following:</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>indow.open(url, target, options);</code></pre> </div> </div> </p> <p>but it still show the link of the site. </p> <p>Thanks <a href="https://i.stack.imgur.com/CLILB.png" rel="nofollow"><img src="https://i.stack.imgur.com/CLILB.png" alt="screenshot of the app running in android device"></a></p>
<p>Ok I figure out this issue, Actually I need to set the location = no and the link will not be shown</p>
How can I delete an item from an Object in NodeJs/express/mongoose? <p>I know this has been asked before, but no one of the answers worked for me. In my App, I have a users collection in MongoDb. These users collection have an array field named 'segActuacions' that can be modified within a form. This form sends this Object to router:</p> <pre><code>{ "segActuacions.0.date": "27/09/2016", "segActuacions.0.body": "first item", "segActuacions.1.date": "27/09/2016", "segActuacions.1.body": "second item" } </code></pre> <p>router has this line to go to controller:</p> <pre><code>router.delete('/seg_act_upd_EE/:id/actDel/:i', sessionController.loginRequired, userController.actuaDelete ); </code></pre> <p>where <code>':id'</code> is <code>User-id</code>, and <code>':i'</code> is the index of <code>segActuacions</code></p> <p>Controller has this code:</p> <pre><code>exports.actuaDelete = function (req, res) { var userId = req.params.id; var userI = req.params.i; var usr = req.body; delete usr['segActuacions.userI.date']; delete usr['segActuacions.userI.body']; models.User.findByIdAndUpdate(userId, usr, function (error, user){ if (error) res.json(error); res.redirect('/list_EE'); }); } </code></pre> <p>I want to delete the fields <code>'i'</code> of the Object (for instance: <code>if i=0</code>, i'd like to delete <code>"segActuacions.0.date"</code> and <code>"segActuacions.0.body"</code>, ...but nothing happens.</p>
<p>Note your delete wouldn't work because you are using <code>userI</code> as a string and not using the variable value. Also update will just update the fields that are in the object.</p> <p>But I think you should use <a href="https://docs.mongodb.com/manual/reference/operator/update/unset/#unset" rel="nofollow">$unset</a>, like the following:</p> <pre><code>var updateObj = {}; updateObj['segActuacions'] = {}; updateObj['segActuacions'][userI] = {}; updateObj['segActuacions'][userI]['body'] = ''; updateObj['segActuacions'][userI]['date'] = ''; var update = { $unset: updateObj }; models.User.findByIdAndUpdate(userId, update, function (error, user){ if (error) res.json(error); res.redirect('/list_EE'); }); </code></pre> <p>(This code can be improved and wasn't tested)</p>
Str.length ,if..else <p>I want my code to run a statement if a string has more than 12 characters. My code:(I have a ("demo") that i have not mentioned here.)</p> <pre><code> &lt;script&gt; var str = "Hello World!"; if(str.length=="12"){ document.getElementById("demo").innerHTML = "Hi"; }else{ document.getElementById("demo").innerHTML = "Not 12"; } &lt;/script&gt; </code></pre> <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;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;button onclick="myFunction()"&gt;Try it&lt;/button&gt; &lt;p id="demo"&gt;&lt;/p&gt; &lt;script&gt; function myFunction() { var str = "Hello World!"; if(str.length===12){ document.getElementById("demo").innerHTML = "Hi"; } else { document.getElementById("demo").innerHTML = "Screw up"; } } //this was missing &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
<pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;button onclick="myFunction()"&gt;Try it&lt;/button&gt; &lt;p id="demo"&gt;&lt;/p&gt; &lt;script&gt; function myFunction() { var str = "Hello World!"; if(str.length&gt;=11){ document.getElementById("demo").innerHTML = "Thanks Keith,For the help"; }else{ document.getElementById("demo").innerHTML = "Hi"; } } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
declare Angular2 component at top level module and use at lower level modules <p>I am working on Angular2 application using Angular2 final release.</p> <p><a href="https://i.stack.imgur.com/6laNs.png" rel="nofollow"><img src="https://i.stack.imgur.com/6laNs.png" alt="enter image description here"></a></p> <p>This is my application scenario. I have a component which I want to use same component at two different modules at two different level.</p> <p>If I declare it at FeatureModule and use it it works. And I haven't tried but if I export it from FeatureModule then it would work in main module as well.</p> <p>But component i designed is not feature specific. So it doesn't seem right to declare it at FeatureModule level and then propagate to other levels. I think it would be more appropriate to declare at AppModule level or MainModule level and use it in both MainModule &amp; FeatureModule level. But this doesnt work. It is throwing following error.</p> <p><strong>If 'xxxx' is an Angular component, then verify that it is part of this module.</strong></p> <p>Any idea, how to achieve this?</p>
<p>You can put your component in a separate module and have your Main and Feature modules import it.</p>
Function that returns an int value, instead of a string in C <p>I'm trying to write a function in C that gets an int as a parameter and returns a char array (or a string).</p> <pre><code>const char * month(int x) { char result[40]; if(x&lt;=31) strcpy(result,"can be a day of the month"); else strcpy(result,"cannot be a day of the month"); return result; } </code></pre> <p>But my function returns an int, not a string. I have read posts where people might have run into similar situations, but I can't understand how the pointer-type functions work and how to make them return what I want (I have documented a bit about pointers and I have an idea about how they work alone, but I have never tried to write a piece of code that adds some functionality to them, like making a solution more effective or something else.)</p>
<pre><code>const char * month(int x) { char result[40]; if(x&lt;=31) strcpy(result,"can be a day of the month"); else strcpy(result,"cannot be a day of the month"); return result; } </code></pre> <p>This doesn't make sense. You return a pointer to the array, but after the function returns, the array no longer exists since <code>result</code> is local to the function.</p> <p>For C:</p> <pre><code>const char * month(int x) { if(x&lt;=31) return "can be a day of the month"; return "cannot be a day of the month"; } </code></pre> <p>For C++:</p> <pre><code>std::string month(int x) { if(x&lt;=31) return "can be a day of the month"; return "cannot be a day of the month"; } </code></pre>
Return value based on closest number <p>In the snippet you'll find a function that returns and outputs the distance belonging to a planet inside an array, based on what planet you type in <code>var found = getDistanceNumber('Saturn');</code></p> <p>I wanna use this code, not to return the distance of the planet as it's programmed now, but <em>the name of the planet closest to it</em>. So if I have Saturn as the parameter, I want it to check what its distance is, find the closest distance in the array, and output the planet belonging to that. In this case that'd be Jupiter.</p> <p>How do I go about that?</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 data = [ { "Planet": "Mercury", "Distance": "-92 million" }, { "Planet": "Venus", "Distance": "-42 million" }, { "Planet": "Earth", "Distance": "0" }, { "Planet": "Mars", "Distance": "78 million" }, { "Planet": "Jupiter", "Distance": "628 million" }, { "Planet": "Saturn", "Distance": "1,3 billion" }, { "Planet": "Uranus", "Distance": "2,7 billion" }, { "Planet": "Neptune", "Distance": "4, 3 billion" } ] function getDistanceNumber(Planet) { return data.filter( function(data){return data.Planet == Planet} ); } var found = getDistanceNumber('Mars'); document.getElementById('output').innerHTML=found[0].Distance;</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="output"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
<p>Check this solution that save the previous planet then return it as result if the passed Planet in condition is matched :</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 data = [ { "Planet": "Mercury", "Distance": "-92 million" }, { "Planet": "Venus", "Distance": "-42 million" }, { "Planet": "Earth", "Distance": "0" }, { "Planet": "Mars", "Distance": "78 million" }, { "Planet": "Jupiter", "Distance": "628 million" }, { "Planet": "Saturn", "Distance": "1,3 billion" }, { "Planet": "Uranus", "Distance": "2,7 billion" }, { "Planet": "Neptune", "Distance": "4, 3 billion" } ] function getClosestPlanet(Planet) { var previous_planet=""; var result=""; data.filter(function(data){ if( data.Planet == Planet ) result = previous_planet; else previous_planet = data.Planet; }) return result; } var found = getClosestPlanet('Saturn'); document.getElementById('output').innerHTML=found;</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="output"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
Can I add a dynamic key to an object? <p>What would a function look like that "keys" an input object? I've been researching the topic, but couldn't find any good answers. </p> <p>So, if I have an input object... </p> <pre><code>var fruits = [{fruit: "apple", taste: "sour"}, {fruit: "cherry", taste: "sweet", color: "red"}]; functionname(fruits, function(i) { return i.fruit; }); RETURN: { "apple": [{fruit: "apple", taste: "sour"}], { "cherry": [{fruit: "cherry", taste: "sweet", color: "red"}] functionname(fruits, function(i) { return i.taste.length; }); RETURN: { "4": [{fruit: "apple", taste: "sour"}], { "5": [{fruit: "cherry", taste: "sweet", color: "red"}] </code></pre>
<p>You could use a function which creates a new object and return the items with the wanted key.</p> <p>Version with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach" rel="nofollow"><code>Array#forEach</code></a></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>function getKeyedArray(array, callback) { var object = Object.create(null); array.reduce(function (a) { var key = callback(a); object[key] = object[key] || []; object[key].push(a); }); return object; } var fruits = [{ fruit: "apple", taste: "sour" }, { fruit: "cherry", taste: "sweet", color: "red" }]; console.log(getKeyedArray(fruits, function (i) { return i.fruit; })); console.log(getKeyedArray(fruits, function (i) { return i.taste.length; }));</code></pre> </div> </div> </p> <p>Version with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce" rel="nofollow"><code>Array#reduce</code></a></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>function getKeyedArray(array, callback) { return array.reduce(function (r, a) { var key = callback(a); r[key] = r[key] || []; r[key].push(a); return r; }, Object.create(null)); } var fruits = [{ fruit: "apple", taste: "sour" }, { fruit: "cherry", taste: "sweet", color: "red" }]; console.log(getKeyedArray(fruits, function (i) { return i.fruit; })); console.log(getKeyedArray(fruits, function (i) { return i.taste.length; }));</code></pre> </div> </div> </p>
Trying to annotate classes to represent a json string with jackson <p>I have an JSON structure from an external source and have some difficulty trying to build a class structure that can be used for deserialization. I have registered that each member of the json array has a name for the array item (oneDevice) - first time i see this</p> <pre><code>{ "pushResponse" : [ { "oneDevice" : { "status" : "Error 0", "token" : "7676jbhjh", "type" : "gcm" } }, { "oneDevice" : { "status" : "Error 0", "token" : "asdasf66a", "type" : "gcm" } } ]} </code></pre> <p>I have tried to create the following class structure but get an error message when running the code:</p> <pre><code>@JsonIgnoreProperties( ignoreUnknown = true ) public class PushOkResponse { @JsonProperty("pushResponse") @XmlElement(required = true) protected PushResponseType pushResponse; } @JsonIgnoreProperties( ignoreUnknown = false ) public class PushResponseType { @JsonProperty( "oneDevice" ) protected List&lt;OneDeviceType&gt; oneDevice; } @JsonIgnoreProperties( ignoreUnknown = false ) public class OneDeviceType { @XmlElement( required = true ) @JsonProperty( "status" ) protected String status; @XmlElement( required = true ) @JsonProperty( "token" ) private String token; @XmlElement( required = true ) @JsonProperty( "type" ) private String type; } PushOkResponse pushOkResponse = mapper.readValue(jsonInString, PushOkResponse.class); </code></pre> <p>fails with com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of (packageName ommitted)...PushResponseType out of START_ARRAY token at [Source: { "pushResponse" : [ { "oneDevice" : { "status" : "Error 0", "token" : "7676jbhjh", "type" : "gcm" } } ]}; line: 1, column: 22] (through reference chain: (packageName ommitted)...PushOkResponse["pushResponse"])</p>
<p>Reading the following POST <a href="http://stackoverflow.com/questions/27154631/json-mapping-exception-can-not-deserialize-instance-out-of-start-array-token">Related question</a> i finally got this to work only short time after posting the question.</p> <p>If I instead use List in the PushOkResponse class, and drop the List for the OneDeviceType in the PushResponseType class everything worked fine. Like this:</p> <pre><code>@JsonIgnoreProperties( ignoreUnknown = true ) public class StrettoOkResponse extends StrettoResponse { @JsonProperty("pushResponse") @XmlElement(required = true) protected List&lt;PushResponseType&gt; pushResponse; } @JsonIgnoreProperties( ignoreUnknown = false ) public class PushResponseType { @JsonProperty( "oneDevice" ) protected OneDeviceType oneDevice; } </code></pre>
Unity3d different screen sizes and limited play area <p>I have been playing around with unity for quite some time now, and I have an app or two published on android, but I have yet to figure out one really important thing that keeps eluding me about mobile. </p> <p>I have looked at various tutorials on things such as unity2d physics and things of that nature, and I have seen tutorials where the person puts a ground sprite on the ground, then attached an edge collider to one side and so on. </p> <p>Now, I may be wrong about this, but to me it seems like if you are making any game at all that involves having to set any sort of boundaries, or objects that you collide with inside a set play area, you can pretty much never use the editor for any sort of level design, and everything has to be done by script because every object you create has to have its location and size set by script on startup to account for various screen sizes. </p> <p>Am i wrong in this? Is there indeed an easy way to create a level using the editor to import sprites and create shapes and edges and object and then have the game automatically scale and move the objects to the proper limits based on screen size?</p> <p>For me, every time I have done an android game or any mobile game in general. I have had to generate all the objects via script, add components via script and generally do everything via script to the point where my actual editor pretty much just had the camera object and a script attached to it and thats about it. </p> <p>Is there an easier way? because so far all the tutorials about 2d games I have seen are pretty much useless for mobile because they use the editor to add sprites and edge colliders manually, which to me seems like it would not look right 90 percent of the time. </p> <p>Any thoughts would be appreciated. </p>
<h1>Game design today must indeed be reactive.</h1> <h1>It is very, very difficult, and there is no easy or built-in solution.</h1> <p>Yes, this is unfortunately an absolute basic aspect of game design in our era.</p> <p>It is indeed very, very difficult to make 2D games work on all different screen shapes.</p> <p>Consider say some sort of landscape 2D arcade game - perhaps where you shoot against each other. What does it actually mean if two people are competing, and one has a 4:3 screen and one has a 16:9 screen?</p> <p>Should it actually <strong><em>take longer for one user to fly across the screen</em></strong>?!? Should you <strong><em>adjust the speed of the ship, so that screen-travel-time is constant</em></strong>?!?</p> <p>Should you just <strong><em>show more stuff on the edges</em></strong>? But wait - does that mean some players get <strong><em>far more warning</em></strong> of arriving enemy or scenery??!</p> <p>Nobody has the answer - it is very, very difficult.</p> <p>it is difficult conceptually, and a real pain to program.</p> <p>In answer to your question, there is absolutely NO built-in method to deal with these hassles in Unity (or any game engine).</p> <p>Almost all teams have code like this .......</p> <pre><code>/* Call this dynamically, probably from SizeCare or RotationCare Position something in relation to the dynamic screen edges - reactively so to speak This is critical for (for example) knowing where to launch sprites from, knowing where to dispose of them, and so on. */ using UnityEngine; using System.Collections; public class KeepAtScreenEdges:MonoBehaviour { [Header("Left and right...")] public bool keepOnLeftEdge; public bool keepOnRightEdge; [Header("Bottom and top...")] public bool keepOnBottomEdge; public bool keepOnTopEdge; public void ScreenMaybeChanged() { if (keepOnLeftEdge) gameObject.ScreenLeft(); if (keepOnRightEdge) gameObject.ScreenRight(); if (keepOnBottomEdge) gameObject.ScreenBottom(); if (keepOnTopEdge) gameObject.ScreenTop(); } } </code></pre> <p>you just stick it on a marker (marker: empty GameObject)</p> <p><a href="https://i.stack.imgur.com/HSN0z.png" rel="nofollow"><img src="https://i.stack.imgur.com/HSN0z.png" alt="enter image description here"></a> </p> <p>there's the "top left" one ...</p> <p><a href="https://i.stack.imgur.com/p2O2l.png" rel="nofollow"><img src="https://i.stack.imgur.com/p2O2l.png" alt="enter image description here"></a></p> <p>and indeed you'll have whole constellations of "reactive markers" like this.</p> <p>Then, every single thing you do in the game, is positioned in relation to these.</p> <p>So for example you'll have a marker for "place where offscreen enemies come in to existence, just off the right edge of the screen". And you'll use that extensively for launching enemies, or whatever.</p> <p>You can do nothing in the editor: everything is reactive. (Well, indeed, you have to program editor code so that it too is perfectly reactive, for during development: you</p> <p>Note that - thank goodness - Unity's awesome .UI system of course is reactive, and that, thank goodness, takes care of the UI aspect of "modern frickin' reactive game layout". (Then again, it's not really that easy to be absolutely expert with .UI, and you have to be. And that's absolutely trivial compared to "game layout reactiveness" :/ )</p> <p>Again - just fundamentally - forget about executing it technically! - are you going to go for a solution like "equal speed across the screen" or "always show more trees at the top" - or whatever? It's very difficult.</p>
Referencing self in a callback <p>My code is:</p> <pre><code>class myclass observable.Observable { let label = "test"; navigatingTo(args: observable.EventData) { target.on( "name", this._callback ); } _callback ( eventData ) { console.log( this.label); } } </code></pre> <p>When I print out this.label in the callback - "this" object is not the object that I expect - which I think should be the myclass instance.</p> <p>I've got a separate method for the callback because I'm also calling .off() later and need a reference to the method (as opposed to anonymous function)</p>
<p>You can pass a third argument when subscribing with <code>on()</code>. The third argument will be used as a context(this) for the callback. So probably you want to do:</p> <pre><code>target.on("name", this._callback, this); </code></pre>
Python program asks for input twice, doesn't return value the first time <p>Here is my code, in the <code>get_response()</code> function, if you enter 'y' or 'n', it says invalid the first time but then works the second time.<br> How do I fix this?</p> <pre><code>import random MIN = 1 MAX = 6 def main(): userValue = 0 compValue = 0 again = get_response() while again == 'y': userRoll, compRoll = rollDice() userValue += userRoll compValue += compRoll if userValue &gt; 21: print("User's points: ", userValue) print("Computer's points: ", compValue) print("Computer wins") else: print('Points: ', userValue, sep='') again = get_response() if again == 'n': print("User's points: ", userValue) print("Computer's points: ", compValue) if userValue &gt; compValue: print('User wins') elif userValue == compValue: print('Tie Game!') else: print('Computer wins') def rollDice(): userRoll = random.randint(MIN, MAX) compRoll = random.randint(MIN, MAX) return userRoll, compRoll def get_response(): answer = input('Do you want to roll? ') if answer != 'y' or answer != 'n': print("Invalid response. Please enter 'y' or 'n'.") answer = input('Do you want to roll? ') main() </code></pre>
<p><code>answer != 'y' or answer != 'n':</code> is always true; <code>or</code> should be <code>and</code>.</p>
GAE (Python) Best practice: Load config from JSON file or Datastore? <p>I wrote a platform in GAE Python with a Datastore database (using NDB). My platform allows for a theme to be chosen by the user. Before <em>every</em> page load, I load in a JSON file (using <code>urllib.urlopen(FILEPATH).read()</code>). Should I instead save the JSON to the Datastore and load it through NDB instead?</p> <p>Here's an example of my JSON config file. These can range in size but not by much. They're generally very small.</p> <pre><code>{ "TITLE": "Test Theme", "VERSION": "1.0", "AUTHOR": "ThePloki", "DESCRIPTION": "A test theme for my platform", "FONTS": ["Arial", "Times New Roman"], "TOOLBAR": [ {"left":[ {"template":"logo"} ]}, {"center":[ {"template":"breadcrumbs"} ]}, {"right":[ {"template":"link", "url":"account", "msg":"Account"}, {"template":"link", "url":"logout", "msg":"Log Out"} ]} ], "NAV_LEFT": true, "SHOW_PAGE_TITLE": false } </code></pre> <p>I don't currently notice any delays, but I'm working locally. During production would the <code>urllib.urlopen().read()</code> cause problems if there is high traffic?</p>
<p>Do you expect the configuration to change without the application code being re-deployed? That is the scenario where it would make sense to store the configuration in the Datastore.</p> <p>If the changing the configuration involves re-deploying the code anyway, a local file is probably fine - you might even consider making it a Python file rather than JSON, so that it'd simply be a matter of importing it rather than messing around with file handles.</p>
TypeError: 'HtmlResponse' object is not iterable <p>I'm new to python, but trying to get my head around it in order to use Scrapy for work.</p> <p>I'm currently following this tutorial: <a href="http://scrapy2.readthedocs.io/en/latest/intro/tutorial.html" rel="nofollow">http://scrapy2.readthedocs.io/en/latest/intro/tutorial.html</a></p> <p>I've having trouble with this part (from the tutorial): </p> <pre><code>def parse(self, response): for sel in response.xpath('//ul/li'): title = sel.xpath('a/text()').extract() link = sel.xpath('a/@href').extract() desc = sel.xpath('text()').extract() print title, link, desc </code></pre> <p>The problem I'm having is with the <code>for sel in response.xpath('//ul/li'):</code> part. I understand that line to essentially narrow down what is crawled to anything that matches the xpath <code>//ul/li</code>.</p> <p>However, in my implementation, I can't narrow down the page to one singular section. I tried to get around this by selecting the entire HTML, see my attempt below:</p> <pre><code> def parse(self, response): for sel in response.xpath('//html'): title = sel.xpath('//h1/text()').extract() author = sel.xpath('//head/meta[@name="author"]/@content').extract() mediumlink = sel.xpath('//head/link[@rel="author"]/@href').extract() print title, author, mediumlink </code></pre> <p>The xpaths work both in a Chrome plugin I use, and using <code>response.xpath('//title').extract()</code> in <code>scrapy shell</code></p> <p>I've tried changing the line to this:</p> <p><code>for sel in response.xpath('//html'):</code> and <code>for sel in response.xpath('html'):</code></p> <p>But each time I get this:</p> <pre><code>2016-10-16 14:33:43 [scrapy] ERROR: Spider error processing &lt;GET https://medium.com/swlh/how-our-app-went-from-20-000-day-to-2-day-in-revenue-d6892a2801bf#.smmwwqxlf&gt; (referer: None) Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 587, in _runCallbacks current.result = callback(current.result, *args, **kw) File "/Users/Matthew/Sites/crawl/tutorial/tutorial/spiders/medium_Spider.py", line 11, in parse for sel in response: TypeError: 'HtmlResponse' object is not iterable </code></pre> <p>Could somebody give me some pointers on how best to resolve this? Go easy on me, my skills are not so hot. Thanks!</p>
<p>As the error message states</p> <pre><code> for sel in response: </code></pre> <p>You try to iterate through the <code>response</code> object in your <code>medium_Spider.py</code> file at <strong>line 11</strong>.</p> <p>However <code>response</code> is an <code>HtmlResponse</code> not an <em>iterable</em> which you could use in a <code>for</code> loop --> you are missing some method call on <code>response</code>. Try to do the loops as you have written in your question:</p> <pre><code>for sel in response.xpath('//html'): </code></pre> <p>Where <code>.xpath('//html')</code> returns an iterable which you can use in the <code>for</code> loop.</p>
Java Best Practice for Date Manipulation/Storage for Geographically Diverse Users <p>I have read all of the other Q/A about Date Manipulation, but none of them seems to deliver a satisfactory answer to my concern.</p> <p>I have a project with geographically diverse users which uses <code>Date</code> in some of its classes and data. The thing is that I am looking for an efficient way to manipulate the Dates for the different users in their respective timezone, most of the answers suggest using <a href="http://www.joda.org/joda-time/" rel="nofollow">Joda</a> library for <code>Date</code> manipulation, which quite don't understand yet because I still have not found any operation you cannot do with traditional Java, so if someone can explain what can I do with <a href="http://www.joda.org/joda-time/" rel="nofollow">Joda</a> that can't be done with traditional Java, then I may consider using it.</p> <p>I finally came to the approach of using <code>System.currentTimeMillis()</code> to save my dates into the database (any database). This would avoid me to worry about what timezone is using the database to store the dates. If I want to query the database for an specific date or range of dates, I would perform the queries using the <code>long</code> value of the <code>Date</code> I want to query:</p> <pre><code>SELECT * FROM table1 WHERE date1&gt;=1476653369000 </code></pre> <p>And when retrieving a <code>ResultSet</code> I would then format the <code>long</code> value retrieved from database to a readable <code>Date</code> using the timezone of the user requesting the data.</p> <pre><code>Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(resultSet.getLong(1)); cal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta")); Date myDate = cal.getTime(); </code></pre> <p>According to some opinions I have read, some people say emphatically that storing <code>System.currentTimeMillis()</code> is definitely not the best practice, nevertheless, for some reason they all miss to say <strong>WHY</strong> it is not recommendable. Am I missing something? Does this cause a performance issue for the conversions <code>Long-&gt;Date</code>/<code>Date-&gt;Long</code>? Is there any use case that cannot be accomplished when using <code>Long</code> instead <code>Date</code> in database? Can someone post a rationale explanation about this?</p> <p>In the other hand, assuming that I keep using <code>Date</code> values to store dates in database, is there a way to avoid worrying about time-zones while handling database <code>Date</code>?</p> <p>Thanks in advance.</p>
<blockquote> <p>what can I do with Joda that can't be done with traditional Java</p> </blockquote> <p>It's not really about what you can or cannot do with traditional Java in the general case. It's more about how the library API works to make you write better (more robust and correct) code easier than traditional Java does.</p> <p>So much so that as of Java 8 the Joda API was more or less copied/adopted verbatim with just package names changed and incorporated into the Java 8 SE standard library.</p> <p>Therefore if you are using Java 8 you should pick the new API, and if not you should consider that using Joda will at least buy you a smooth path towards upgrading/porting to Java 8 when you are able to.</p> <p>A few examples:</p> <ul> <li>Consistent API for date and time types.</li> <li>Date/time objects are immutable, manipulations return new instances of the type representing the altered value. (Like Java Strings). This makes it easier to reason about reuse of date/time objects.</li> <li>By design avoids mixing DST &amp; timezone dependent values/operations with DST &amp; timezone agnostic ones. This makes it a lot easier to write code that works consistently and correctly and doesn't have corner cases dependent on timezone/locale/date/time-of-day.</li> <li>Sane defaults for things like <code>toString()</code> so serialising/deserialising can be expected to work correctly with minimal effort.</li> <li>Culture/locale dependent corner cases and things you weren't aware of yet (for example, did you know about the traditional Korean calendar?) which saves you a whole lot of hassle when converting your date times between locales/calendaring systems. Also: a wealth of formatting options.</li> <li>The concept of <code>Instant</code>s to represent 'absolute' time stamps which is useful when working with geographically distributed systems (when the system default clocks/timezones &amp; DST rules may differ) or for interop because it uses UTC.</li> </ul> <p>EDIT to add:</p> <blockquote> <p>According to some opinions I have read, some people say emphatically that storing <code>System.currentTimeMillis()</code> is definitely not the best practice, nevertheless, for some reason they all miss to say WHY it is not recommendable. Am I missing something?</p> </blockquote> <p><code>System.currentTimeMillis()</code> has a few downsides. The big drawback is that the type of clock is ill defined. It could be a monotonic clock, it could be clock subject to DST and timezone or it could be a UTC time. It is also not necessarily an accurate clock, it is not actually guaranteed to be accurate down to the millisecond. Just whatever happens to be to hand for something that will work as a semblance of the current time <em>at</em> the current time, basically.</p> <p>This means that if you want to use multiple servers to handle incoming requests, for instance, it gets tricky when you have to consider working with the output of <code>System.currentTimeMillis()</code> from server <code>A</code> in the context of your program running on a different server <code>B</code> the next day, say.</p>
Validate user input to only accept type int or String "quit" <p>My code prints out an array which is already declared then asks for user input. User is supposed to enter a number in the format xy or type quit to stop using the program. After getting user input it prints out the element of the array using x as row and y as column number which is followed by setting that index to 0 and printing the new array. I have so far achieved most of it apart from accepting only integers or "quit" from the user. If user enters another string apart from "quit" the program crashes. This is my code. import java.util.Scanner;</p> <pre><code>public class Exercise23 { public static void main(String[] args) { Scanner read = new Scanner(System.in); int [][] array = { {0, 1, 4, 5}, {3, 7, 9, 7}, {1, 8, 2, 1} }; for (int i = 0; i &lt; array.length; i++) { for (int j = 0; j &lt; array[i].length; j++) { System.out.print(array[i][j]); } System.out.println(); } boolean exitCon = false; do { System.out.println("Please enter a number in the format 'xy' with no spaces in between or enter 'quit' to stop"); String xy = read.nextLine(); if (!"quit".equals(xy)) { String x = xy.substring(0, 1); String y = xy.substring(1); int row = Integer.parseInt(x); int column = Integer.parseInt(y); if (0 &lt;= row &amp;&amp; 0 &lt;= column &amp;&amp; row &lt;= 2 &amp;&amp; column &lt;=) { System.out.println(); System.out.println(array[row][column]); array[row][column] = 0; System.out.println(); for (int i = 0; i &lt; array.length; i++) { for (int j = 0; j &lt; array[i].length; j++) { System.out.print(array[i][j]); } System.out.println(); } System.out.println(); } else { System.out.println("The number has to be in range 00-23 inclusive considering the format 'xy'."); } } else if (xy.equals("")) { System.out.println("You can only enter integers or 'quit'."); } else { exitCon= true; } } while (!exitCon); } } </code></pre> <p>The problem is in this bit</p> <pre><code>String xy = read.nextLine(); if (!"quit".equals(xy)) { String x = xy.substring(0, 1); String y = xy.substring(1); int row = Integer.parseInt(x); int column = Integer.parseInt(y); if (0 &lt;= row &amp;&amp; 0 &lt;= column &amp;&amp; row &lt;= 2 &amp;&amp; column &lt;= 3) { System.out.println(); System.out.println(array[row][column]); array[row][column] = 0; System.out.println(); for (int i = 0; i &lt; array.length; i++) { for (int j = 0; j &lt; array[i].length; j++) { System.out.print(array[i][j]); } System.out.println(); } System.out.println(); } else { System.out.println("The number has to be in range 00-23 inclusive considering the format 'xy'."); } } else if (xy.equals("")) { System.out.println("You can only enter integers or 'quit'."); } else { exitCon= true; </code></pre> <p>I get this error "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1 at java.lang.String.substring(String.java:1963) at Exercise23.main(Exercise23.java:26) "</p>
<p>With the exception added, it appears the failure is occurring here;</p> <pre><code>String x = xy.substring(0, 1); String y = xy.substring(1); </code></pre> <p>The StringIndexOutOfBoundsException means the String "xy" is too short, presumably blank on the readline.</p>
Single-row subquery returns more than one row Help Please <p>I am trying to build a simple query for working out times when staff clock in and clock out. The DB records the person's name, if their clocking in or out and the time. It records more then that but I don't need that info.</p> <p>So an example DB would be:</p> <pre><code>Id | User | In_out | Date_Time ---------------------------------- 2 | Bob | In | 13/Oct/16 9:30:35AM 3 | Ken | In | 13/Oct/16 9:34:27AM 4 | Jon | In | 13/Oct/16 9:34:46AM 5 | Billy | In | 13/Oct/16 9:52:06AM 6 | Bob | Out | 13/Oct/16 4:30:05PM 7 | Jon | Out | 13/Oct/16 4:32:55PM </code></pre> <p>The result I want to bring back in a SQL is:</p> <pre><code>User | Time_In | Time_Out ------------------------------- Bob | 9:30:35AM | 4:30:05PM Jon | 9:34:46AM | 4:32:55PM </code></pre> <p>The SQL I am trying is not right I know that. But what do I need to change to get the result I want?</p> <pre><code>SELECT Clock.Checkin_Checkout.User, Clock.Checkin_Checkout.In_Out, (SELECT TO_CHAR(Clock.Checkin_Checkout.DATETIME, 'hh:mi:ss AM') FROM Clock.Checkin_Checkout WHERE Clock.Checkin_Checkout.In_Out = 'In') AS "Time In", To_Char(Clock.Checkin_Checkout.Create_Datetime, 'hh:mi:ss AM') AS "Time Out" FROM Clock.Checkin_Checkout WHERE Clock.Checkin_Checkout.In_Out = 'Out' AND Clock.Checkin_Checkout.Datetime &gt;= '13/Oct/2016' </code></pre> <p>Any help would be appreciate. </p> <p>Thanks Rob.</p>
<p>I've created an example <a href="http://rextester.com/OXLN87427" rel="nofollow">here</a>.</p> <p>In the naive assumption that in the table there will be alwas one "In" and at most one "Out" for a single name, the following query should work:</p> <pre><code>Select c1.user, to_char(MAX(CASE WHEN c1.In_Out='In' then c1.Date_Time end), 'hh:mi:ss AM') time_in, to_char(MAX(CASE WHEN c1.In_Out='Out' then c1.Date_Time end), 'hh:mi:ss AM') time_out From Clock.Checkin_Checkout as c1 group by c1.user having MAX(CASE WHEN c1.In_Out='Out' then c1.Date_Time end) is not null; </code></pre> <p>If you want also the cases where there is no 'Out', just omit the "having" clause</p> <p><strong>Edited: more realistic scenario</strong></p> <p>If you want the query to be able to recognize multiple shifts from the same person, you might use this query:</p> <pre><code>select c1.user, c1.Date_Time as Time_In, c2.Date_Time as Time_Out from Clock.Checkin_Checkout c1 join Clock.Checkin_Checkout c2 on c2.user= c1.user where c1.In_Out= 'In' and c2.In_Out= 'Out' and c1.Date_Time &lt;c2.Date_Time and not exists (select 1 from Clock.Checkin_Checkout c3 where c1.user=c3.user and c1.Date_Time &lt;c3.Date_Time and c3.Date_Time &lt;c2.Date_Time ) </code></pre> <p>I've also tested this solution on <a href="http://rextester.com/ZAFEZ72625" rel="nofollow">rextester</a>.</p> <p><em>Disclaimer: I started from @user1751825 query for this second scenario as it was simple to arrive to this solution from his query rather than from my previous one.</em></p>
Swift 3 - find number of calendar days between two dates <p>The way I did this in Swift 2.3 was:</p> <pre><code> let currentDate = NSDate() let currentCalendar = NSCalendar.currentCalendar() var startDate : NSDate? var endDate : NSDate? // The following two lines set the `startDate` and `endDate` to the start of the day currentCalendar.rangeOfUnit(.Day, startDate: &amp;startDate, interval: nil, forDate: currentDate) currentCalendar.rangeOfUnit(.Day, startDate: &amp;endDate, interval: nil, forDate: self) let intervalComps = currentCalendar.components([.Day], fromDate: startDate!, toDate: endDate!, options: []) print(intervalComps.day) </code></pre> <p>Now this has all changed with Swift 3. I have to either use <code>NSCalendar</code> and <code>NSDate</code> by constantly type casting with <code>as</code>, or find the Swift 3 way of doing it. </p> <p>What's the right way to do it in Swift 3? </p>
<p>Turns out this is much simpler to do in Swift 3:</p> <pre><code>let currentCalendar = Calendar.current guard let start = currentCalendar.ordinality(of: .day, in: .era, for: date) else { return 0 } guard let end = currentCalendar.ordinality(of: .day, in: .era, for: self) else { return 0 } print( start - end ) </code></pre> <p><strong>Edit</strong></p> <p>Comparing the ordinality of the two dates should be within the same <code>era</code> instead of the same <code>year</code>, since naturally the two dates may fall in different years.</p>
Unable to access modified value of imported variable <p>I am new to python and have some problem understanding the scope here.</p> <p>I have a python module A with three global variables :</p> <pre><code>XYZ = "val1" ABC = {"k1" : "v1", "k2" : "v2"} PQR = 1 class Cls_A() : def sm_fn_A(self) : global XYZ global ABC global PQR XYZ = "val2" ABC["k1"] = "z1" ABC["k3"] = "v3" PQR += 1 </code></pre> <p>And another module B :</p> <pre><code>from A import Cls_A, XYZ, ABC, PQR class Cls_B(): def sm_fn_B(self) : Cls_A().sm_fn_A() print XYZ print ABC print PQR Cls_B().sm_fn_B() </code></pre> <p>This gives me the following output :</p> <pre><code>val1 {'k3': 'v3', 'k2': 'v2', 'k1': 'z1'} 1 </code></pre> <p>Since these are all global variables, why do I not get updated values of all the global variables printed ? </p>
<h1>Explanation</h1> <p>Three global variables are defined in module <code>A</code>, in this code:</p> <pre><code>XYZ = "val1" ABC = {"k1" : "v1", "k2" : "v2"} PQR = 1 </code></pre> <p>Then new global variables <code>XYZ</code>, <code>ABC</code>, <code>PQR</code> are defined in module <code>B</code>, in this code:</p> <pre><code>from A import Cls_A, XYZ, ABC, PQR </code></pre> <p>This line of code creates new variables, just as if the following was written:</p> <pre><code>import A XYZ = A.XYZ ABC = A.ABC PQR = A.PQR </code></pre> <p>It is important to understand that <code>A.XYZ</code> and <code>B.XYZ</code> are two variables which point to the same object. They are not the same variable.</p> <p>Then a new object is assigned to <code>A.XYZ</code>:</p> <pre><code> XYZ = "val2" </code></pre> <p>This modified <code>A.XYZ</code>, but did not modify <code>B.XYZ</code>. The two used to be two variables which pointed to the same object, but now <code>A.XYZ</code> points to a different object.</p> <p>On the other hand, <code>A.ABC</code> is not assiciated with a different object. Instead, the object itself is modified. When the object is modified, both <code>A.ABC</code> and <code>B.ABC</code> still point to the same object:</p> <pre><code> ABC["k1"] = "z1" ABC["k3"] = "v3" </code></pre> <p>The third case is also not a case of object modification, but rather reassignment:</p> <pre><code> PQR += 1 </code></pre> <p>The value was incremented. That created a new object and than thet new object was assigned to <code>A.PQR</code>. <code>B.PQR</code> is unchanged. This is equivalent to:</p> <pre><code> PQR = PQR + 1 </code></pre> <p>A thing which may not be obvious is that both strings and integers are <em>immutable</em> objects in Python (there is no way to change number to <code>2</code> to become <code>3</code> - one can only assign a different int object to a variable, not change the existing one). Because of that, there is actually no way to change <code>A.XYZ</code> in a way that affects <code>B.XYZ</code>.</p> <h2>The dictionary could behave the same way</h2> <p>The reason why with the dictionary it <em>"worked"</em> is that the object was modified. If a new dictioanry was assigned to <code>A.ABC</code>, that would not work. E.g.</p> <pre><code> ABC = {'k3': 'v3', 'k2': 'v2', 'k1': 'z1'} </code></pre> <p>Now it would not affect <code>B.ABC</code>, because the object in <code>A.ABC</code> was not changed. Another object was assigned to <code>A.ABC</code> instead.</p> <h1>Not related to modules</h1> <p>The same behaviour can be seen without any modules:</p> <pre><code>A_XYZ = "val1" A_ABC = {"k1" : "v1", "k2" : "v2"} A_PQR = 1 B_XYZ = A_XYZ B_ABC = A_ABC B_PQR = A_PQR A_XYZ = "val2" A_ABC["k1"] = "z1" A_ABC["k3"] = "v3" A_PQR += 1 print B_XYZ print B_ABC print B_PQR </code></pre> <p>Prints:</p> <pre><code>val1 {'k3': 'v3', 'k2': 'v2', 'k1': 'z1'} 1 </code></pre> <h1>Solution</h1> <p>Well, don't keep reference to the temporary object. Use the variable which has the correct value.</p> <p>For example, in module <code>B</code>:</p> <pre><code>import A class Cls_B(): def sm_fn_B(self) : A.Cls_A().sm_fn_A() print A.XYZ print A.ABC print A.PQR Cls_B().sm_fn_B() </code></pre> <p>Now there is actually no <code>B.XYZ</code> variable, which could be wrong. <code>A.XYZ</code> is always used.</p>
how to manipulate my dataframe in spark? <p>I have an nested json rdd stream comming in from a kafka topic. the data looks like this: </p> <pre><code>{ "time":"sometext1","host":"somehost1","event": {"category":"sometext2","computerName":"somecomputer1"} } </code></pre> <p>I turned this into a dataframe and the schema looks like </p> <pre><code>root |-- event: struct (nullable = true) | |-- category: string (nullable = true) | |-- computerName: string (nullable = true) |-- time: string (nullable = true) |-- host: string (nullable = true) </code></pre> <p>Im trying to save it to a hive table on hdfs with a schema like this</p> <pre><code>category:string computerName:string time:string host:string </code></pre> <p>This is my first time working with spark and scala. I would appretiate if someone could help me. Thanks </p>
<pre><code>// Creating Rdd val vals = sc.parallelize( """{"time":"sometext1","host":"somehost1","event": {"category":"sometext2","computerName":"somecomputer1"}}""" :: Nil) // Creating Schema val schema = (new StructType) .add("time", StringType) .add("host", StringType) .add("event", (new StructType) .add("category", StringType) .add("computerName", StringType)) import sqlContext.implicits._ val jsonDF = sqlContext.read.schema(schema).json(vals) </code></pre> <p><strong>jsonDF.printSchema</strong></p> <pre><code>root |-- time: string (nullable = true) |-- host: string (nullable = true) |-- event: struct (nullable = true) | |-- category: string (nullable = true) | |-- computerName: string (nullable = true) // selecting columns val df = jsonDF.select($"event.*",$"time", $"host") </code></pre> <p><strong>df.printSchema</strong></p> <pre><code>root |-- category: string (nullable = true) |-- computerName: string (nullable = true) |-- time: string (nullable = true) |-- host: string (nullable = true) </code></pre> <p><strong>df.show</strong></p> <pre><code>+---------+-------------+---------+---------+ | category| computerName| time| host| +---------+-------------+---------+---------+ |sometext2|somecomputer1|sometext1|somehost1| +---------+-------------+---------+---------+ </code></pre>
Oracle SQL developer- Create Table from Table and View <p>I have one table and view where one column is common which is the primary key of the table. Now if I want to join the table and view only with specific columns, should I create view or table in that case? Also I want to import the joined result to Tableau.</p>
<p>Well If you want just join table and view in single query you may write it, or you may create view for it, if you want. For example:</p> <pre><code> create table tmp_table_a (id, first_col, second_col, third_col) as select level, lpad('a',level,'b'), lpad('c',level,'d'), lpad('e',level,'f') from dual connect by level &lt; 101; create view v_tmp_a as select id, substr(first_col,1,10) as first_sub_col from tmp_table_a; </code></pre> <p>simple query:</p> <pre><code> select second_col, third_col, first_sub_col from tmp_table_a t1, v_tmp_a v1 where t1.id = v1.id; </code></pre> <p>or create view:</p> <pre><code> create view v_join_a as select second_col, third_col, first_sub_col from tmp_table_a t1, v_tmp_a v1 where t1.id = v1.id; select * from v_join_a; </code></pre>
Drag and Drop between tables in horizontalLayout doesn't work <p>I've got 3 Tables in Vaadin: </p> <p><a href="https://i.stack.imgur.com/4x5bH.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/4x5bH.jpg" alt="3 Tables within a horizontal Layout"></a></p> <p>My Problem now is that Drag &amp; Drop doesn't work. My Code is the following one: </p> <pre><code>@Theme("valo") @SpringView(name = TaskboardView.VIEW_NAME) public class TaskboardView extends VerticalLayout implements View { private enum TableType { DONE, PROGRESS, OPEN; } private static final long serialVersionUID = 1L; private final Logger logger = LoggerFactory.getLogger(TaskboardView.class); public static final String VIEW_NAME = "taskboard"; // Components: private SprintController sprintController = new SprintController(); private TaskController taskController = new TaskController(); private Sprint sprint; private Set&lt;Task&gt; allTasks; private List&lt;Task&gt; openTasks = new ArrayList&lt;Task&gt;(); private List&lt;Task&gt; inProgressTasks = new ArrayList&lt;Task&gt;(); private List&lt;Task&gt; doneTasks = new ArrayList&lt;Task&gt;(); // UI Components: private Table openTable = new Table("Open Tasks:"); private int openTableId = 1; private Table inProgressTable = new Table("Tasks in Progress"); private int inProgressTableId = 1; private Table doneTable = new Table("Done Tasks"); private int doneTableId = 1; private TextField sprintName = new TextField(); private OpenTableDropHandler openTableDropHandler = new OpenTableDropHandler(); private InProgressTableDropHandler inProgressTableDropHandler = new InProgressTableDropHandler(); DoneTableHandler doneTableHandler = new DoneTableHandler(); @PostConstruct void init() { logger.info("Initializing Taskboard View..."); try { this.sprint = sprintController.getActiveSprint(); this.allTasks = sprintController.getTasksInSprint(this.sprint.getId().intValue()); sortSprintTasks(this.allTasks); this.sprintName.setNullRepresentation("-- No active Sprint found --"); this.sprintName.setValue(this.sprint.getSprintName()); this.sprintName.setWidth("800px"); this.sprintName.setReadOnly(true); this.sprintName.addStyleName("align-center"); // sets Allignment of // the textfield!!! } catch (NoActiveSprintReceivedException | NoSprintsExistException | IOException e) { logger.error("Something went wrong initializing active Sprint. The taskboard can't be displayed.", e); Notification.show("No Active Sprint found!", Notification.Type.ERROR_MESSAGE); e.printStackTrace(); return; } catch (TaskCanNotBeAllocatedException e) { logger.error("Task of sprint couldn't be allocated to an status.", e); Notification.show("Error! \n \n Task of sprint couldn't be allocated to an status.", Notification.Type.ERROR_MESSAGE); e.printStackTrace(); return; } // Layout for Sprint Name: VerticalLayout headLayout = new VerticalLayout(); headLayout.setSpacing(true); headLayout.setSizeFull(); ; headLayout.setMargin(true); headLayout.addComponent(this.sprintName); headLayout.setComponentAlignment(this.sprintName, Alignment.MIDDLE_CENTER); setSizeFull(); setSpacing(true); setMargin(true); // Layout: VerticalLayout verticalLayout = new VerticalLayout(); verticalLayout.setSpacing(true); // Layout for Board: HorizontalLayout taskBoardLayout = new HorizontalLayout(); taskBoardLayout.setSizeUndefined(); taskBoardLayout.setSpacing(true); taskBoardLayout.setMargin(true); // Adding to HorizontalLayout(TaskBoadLayout) try { initTable(this.openTable, TableType.OPEN); initTable(this.inProgressTable, TableType.PROGRESS); initTable(this.doneTable, TableType.DONE); } catch (IOException e) { logger.error("Something went wrong initizalizing Tables."); Notification.show("Error! \n \n Couldn't initialize tables.", Notification.Type.ERROR_MESSAGE); return; } taskBoardLayout.addComponent(openTable); taskBoardLayout.addComponent(inProgressTable); taskBoardLayout.addComponent(doneTable); // Adding to VerticalLayout (MainLayout) verticalLayout.addComponent(headLayout); verticalLayout.addComponent(taskBoardLayout); verticalLayout.setComponentAlignment(taskBoardLayout, Alignment.MIDDLE_CENTER); addComponent(verticalLayout); } /** * Sorts the tasks of the sprint to the required lists like open, in * Progress, done. * * @param tasks * @throws TaskCanNotBeAllocatedException */ private void sortSprintTasks(Set&lt;Task&gt; tasks) throws TaskCanNotBeAllocatedException { logger.info("sortSprintTask(Set&lt;Task&gt;tasks): Sorting Tasks to the required lists..."); for (Task t : tasks) { logger.info("Checking Sprint Status of Task &gt;&gt;&gt;&gt; " + t.getHeadLine() + " &lt;&lt;&lt;&lt;"); logger.info("Status: " + t.getStatus()); if (t.getStatus().equals(WorkflowStatusConfigurator.open)) { this.openTasks.add(t); } else if (t.getStatus().equals(WorkflowStatusConfigurator.inProgress)) { this.inProgressTasks.add(t); } else if (t.getStatus().equals(WorkflowStatusConfigurator.done)) { this.doneTasks.add(t); } else { throw new TaskCanNotBeAllocatedException( "Task can't be allocated to a sprint status: " + WorkflowStatusConfigurator.open + ", " + WorkflowStatusConfigurator.inProgress + ", " + WorkflowStatusConfigurator.done + "."); } } } @Override public void enter(ViewChangeEvent event) { // TODO Auto-generated method stub } /** * Creates the tables depending on the type parameter * * @param table * @param type * @throws IOException * @throws ClientProtocolException */ private void initTable(Table table, TableType type) throws ClientProtocolException, IOException { table.setSelectable(true); table.setImmediate(true); table.setDragMode(TableDragMode.ROW); table.addContainerProperty("ID", Long.class, null); table.setColumnWidth("ID", 50); table.addContainerProperty("Headline", String.class, null); table.setColumnWidth("Headline", 300); table.addContainerProperty("Task-Type", String.class, null); table.setColumnWidth("Task-Type", 120); table.addContainerProperty("Assignee", String.class, null); table.setColumnWidth("Assignee", 100); if (type.equals(TableType.OPEN) &amp;&amp; this.openTasks.size() &gt; 0) { logger.info("Loading values of Open Tasks Table..."); table.setDropHandler(this.openTableDropHandler); for (Task t : this.openTasks) { String assignee = this.taskController.getAssigneeInTask(t.getId().intValue()).getUserName(); table.addItem(new Object[] { t.getId(), t.getHeadLine(), t.getTaskType(), assignee }, this.openTableId); this.openTableId++; } return; } if (type.equals(TableType.PROGRESS) &amp;&amp; this.inProgressTasks.size() &gt; 0) { logger.info("Loading values of Progress Tasks Table..."); table.setDropHandler(this.inProgressTableDropHandler); for (Task t : this.inProgressTasks) { String assignee = this.taskController.getAssigneeInTask(t.getId().intValue()).getUserName(); table.addItem(new Object[] { t.getId(), t.getHeadLine(), t.getTaskType(), assignee }, this.inProgressTableId); this.inProgressTableId++; } return; } if (type.equals(TableType.DONE) &amp;&amp; this.doneTasks.size() &gt; 0) { logger.info("Loading values of Done Tasks Table..."); table.setDropHandler(this.doneTableHandler); for (Task t : this.doneTasks) { String assignee = this.taskController.getAssigneeInTask(t.getId().intValue()).getUserName(); table.addItem(new Object[] { t.getId(), t.getHeadLine(), t.getTaskType(), assignee }, this.doneTableId); this.doneTableId++; } return; } } private int giveEncreasedAvailableTableId(TableType tableType) { if(tableType.equals(TableType.OPEN)){ this.openTableId++; return this.openTableId; }else if(tableType.equals(TableType.PROGRESS)){ this.inProgressTableId++; return this.inProgressTableId; }else if(tableType.equals(TableType.DONE)){ this.doneTableId++; return this.doneTableId; }else{ return -1; } } private class OpenTableDropHandler implements DropHandler{ private static final long serialVersionUID = 1L; private final Logger logger = LoggerFactory.getLogger(OpenTableDropHandler.class); @Override public void drop(DragAndDropEvent event) { // Wrapper for the object that is dragged logger.info("Received Drag and Drop Event from OpenTable..."); DataBoundTransferable t = (DataBoundTransferable) event.getTransferable(); AbstractSelectTargetDetails dropData = ((AbstractSelectTargetDetails) event.getTargetDetails()); Object itemId = t.getItemId(); Long id = (Long) t.getSourceContainer().getItem(itemId).getItemProperty("ID").getValue(); try { Task taskToAdd = taskController.getById(id.intValue()); String author = taskController.getAuthorInTask(taskToAdd.getId().intValue()).getUserName(); if ( t.getSourceComponent() != openTable &amp;&amp; dropData.getTarget().equals(inProgressTable)) { logger.info("Preparing Task Update to InProgress..."); openTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(), taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.OPEN)); openTasks.add(taskToAdd); inProgressTable.removeItem(itemId); inProgressTasks.remove(taskToAdd); }else if(t.getSourceComponent() != openTable &amp;&amp; dropData.getTarget().equals(doneTable)){ logger.info("Preparing Task Update to Done..."); openTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(), taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.OPEN)); openTasks.add(taskToAdd); doneTable.removeItem(itemId); doneTasks.remove(taskToAdd); }else{ logger.info("Do nothing..."); return; } taskToAdd.setStatus(WorkflowStatusConfigurator.open); logger.info("Sending updates of taskboard to webservice..."); HttpResponse response = taskController.put(taskToAdd, taskToAdd.getId().intValue()); MainView.navigator.navigateTo(TaskboardView.VIEW_NAME); // HttpResponse authorResponse = taskController.setAuthorInTask(taskToAdd.getAuthor().getId().intValue(), // taskToAdd.getId().intValue()); // HttpResponse assigneeResponse = taskController.setAssigneeInTask(taskToAdd.getAssignee().getId().intValue(), // taskToAdd.getId().intValue()); } catch (ClientProtocolException e) { logger.warn("Something went wrong during Drag and Drop Process", e.getCause()); } catch (IOException e) { logger.warn("Something went wrong during Drag and Drop Process", e.getCause()); } } @Override public AcceptCriterion getAcceptCriterion() { return AcceptAll.get(); } } private class InProgressTableDropHandler implements DropHandler{ private static final long serialVersionUID = 1L; private final Logger logger = LoggerFactory.getLogger(InProgressTableDropHandler.class); @Override public void drop(DragAndDropEvent event) { // Wrapper for the object that is dragged logger.info("Received Drag and Drop Event from In Progress Table."); DataBoundTransferable t = (DataBoundTransferable) event.getTransferable(); AbstractSelectTargetDetails dropData = ((AbstractSelectTargetDetails) event.getTargetDetails()); Object itemId = t.getItemId(); Long id = (Long) t.getSourceContainer().getItem(itemId).getItemProperty("ID").getValue(); try { Task taskToAdd = taskController.getById(id.intValue()); String author = taskController.getAuthorInTask(taskToAdd.getId().intValue()).getUserName(); if (t.getSourceComponent() != inProgressTable &amp;&amp; dropData.getTarget().equals(doneTable) ){ inProgressTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(), taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.PROGRESS)); doneTable.removeItem(itemId); inProgressTasks.add(taskToAdd); doneTasks.remove(taskToAdd); }else if(t.getSourceComponent() != inProgressTable &amp;&amp; dropData.getTarget().equals(openTable)){ inProgressTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(), taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.PROGRESS)); openTable.removeItem(itemId); inProgressTasks.add(taskToAdd); openTasks.remove(taskToAdd); }else{ return; } logger.info("Sending updates of taskboard to webservice..."); taskToAdd.setStatus(WorkflowStatusConfigurator.inProgress); HttpResponse response = taskController.put(taskToAdd, taskToAdd.getId().intValue()); MainView.navigator.navigateTo(TaskboardView.VIEW_NAME); }catch (ClientProtocolException e) { logger.warn("Something went wrong during Drag and Drop Process", e.getCause()); } catch (IOException e) { logger.warn("Something went wrong during Drag and Drop Process", e.getCause()); } } @Override public AcceptCriterion getAcceptCriterion() { return AcceptAll.get(); } } private class DoneTableHandler implements DropHandler{ private static final long serialVersionUID = 1L; private final Logger logger = LoggerFactory.getLogger(DoneTableHandler.class); @Override public void drop(DragAndDropEvent event) { logger.info("Received Drag and Drop Event from In Done Table."); DataBoundTransferable t = (DataBoundTransferable) event.getTransferable(); AbstractSelectTargetDetails dropData = ((AbstractSelectTargetDetails) event.getTargetDetails()); Object itemId = t.getItemId(); Long id = (Long) t.getSourceContainer().getItem(itemId).getItemProperty("ID").getValue(); try { Task taskToAdd = taskController.getById(id.intValue()); String author = taskController.getAuthorInTask(taskToAdd.getId().intValue()).getUserName(); if (t.getSourceComponent() != doneTable &amp;&amp; dropData.getTarget().equals(inProgressTable) ){ doneTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(), taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.DONE)); inProgressTable.removeItem(itemId); doneTasks.add(taskToAdd); inProgressTasks.remove(taskToAdd); }else if(t.getSourceComponent() != doneTable &amp;&amp; dropData.getTarget().equals(openTable)){ doneTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(), taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.DONE)); openTable.removeItem(itemId); doneTasks.add(taskToAdd); openTasks.remove(taskToAdd); }else{ return; } logger.info("Sending updates of taskboard to webservice..."); taskToAdd.setStatus(WorkflowStatusConfigurator.done); HttpResponse response = taskController.put(taskToAdd, taskToAdd.getId().intValue()); MainView.navigator.navigateTo(TaskboardView.VIEW_NAME); }catch (ClientProtocolException e) { logger.warn("Something went wrong during Drag and Drop Process", e.getCause()); } catch (IOException e) { logger.warn("Something went wrong during Drag and Drop Process", e.getCause()); } } @Override public AcceptCriterion getAcceptCriterion() { return AcceptAll.get(); } } } </code></pre> <p>Has anyone any idea or at least a clue why this doesn't work? I wrote a code following the same pattern or way and it worked fine. The only difference is that there I don't use Horizontal Layout. And now the in Progress and Done Table don't react to draggin a row on them. </p>
<p>Off-topic: why do you have <code>@Theme("valo")</code> on your view? As far as I know that's used with the <code>UI</code> class...</p> <hr> <p>On-topic:</p> <p>As I was saying in my comment I don't think it's related to <code>HorizontalLayout</code>. Either you may have misunderstood the <em>drag source</em> and <em>drop target</em> concepts or it simply slipped in the code.</p> <p>As it's also described in <a href="https://vaadin.com/docs/-/part/framework/advanced/advanced-dragndrop.html" rel="nofollow">the docs</a> the <em>dragging</em> starts from a source, and the event of <em>dropping</em> the data on the target is handled by a <code>DropHandler</code>. If you take a look at your sources, <code>DoneTableHandler</code> for example, you can see </p> <pre class="lang-java prettyprint-override"><code>if (t.getSourceComponent() != doneTable &amp;&amp; dropData.getTarget().equals(inProgressTable) ){ ... }else if(t.getSourceComponent() != doneTable &amp;&amp; dropData.getTarget().equals(openTable)){ ... }else{ return; } </code></pre> <p>Since you're listening for drops on your <code>doneTable</code> it will be the target and sources can only be the <code>openTable</code> or <code>inProgressTable</code>, not the other way around. I have a hunch that if you're going to add a log line in the <code>else</code> branch you'll see it on each drag &amp; drop.</p> <hr> <p>Below you can see a working sample in Vaadin 7.7.3 with a <code>HorizontalLayout</code> and 3 tables, similar to yours. It's quick and dirty so there's room for improvement (suggestions are welcome) but (eg: <a href="https://vaadin.com/api/com/vaadin/ui/AbstractSelect.AbstractSelectTargetDetails.html#idOver" rel="nofollow">position of dropped items</a>), it supports <a href="https://vaadin.com/api/com/vaadin/ui/Table.TableDragMode.html" rel="nofollow">multirow</a> drag and also the <code>AcceptCriterion</code> filters drops from the source table or any other component than the expected ones:</p> <pre class="lang-java prettyprint-override"><code>public class DragAndDropTables extends HorizontalLayout { public DragAndDropTables() { // leave some space between the tables setSpacing(true); // tables Table toDoTable = createTable("To do"); Table inProgressTable = createTable("In progress"); Table doneTable = createTable("Done"); // drop handlers which allow only drops from expected sources configureDragAndDrop(toDoTable, inProgressTable, doneTable); configureDragAndDrop(inProgressTable, toDoTable, doneTable); configureDragAndDrop(doneTable, toDoTable, inProgressTable); // some table to make sure AcceptCriterion allows drops only from expected sources Table tableNotAcceptableForDrops = createTable("Drops from here will not be accepted"); configureDragAndDrop(tableNotAcceptableForDrops); tableNotAcceptableForDrops.addItem(new Task(100, "Not droppable task")); // add some dummy data for (int i = 0; i &lt; 10; i++) { toDoTable.addItem(new Task(i, "Task " + i)); } // add the tables to the UI addComponent(toDoTable); addComponent(inProgressTable); addComponent(doneTable); addComponent(tableNotAcceptableForDrops); } private Table createTable(String caption) { // basic table setup Table table = new Table(caption); BeanItemContainer&lt;Task&gt; itemContainer = new BeanItemContainer&lt;&gt;(Task.class); table.setContainerDataSource(itemContainer); table.setMultiSelect(true); table.setSelectable(true); table.setPageLength(10); return table; } private void configureDragAndDrop(Table table, Table... acceptedSources) { // drag &amp; drop configuration table.setDragMode(Table.TableDragMode.MULTIROW); table.setDropHandler(new DropHandler() { @Override public void drop(DragAndDropEvent event) { // where the items are dragged from Table source = (Table) event.getTransferable().getSourceComponent(); // where the items are dragged to Table target = (Table) event.getTargetDetails().getTarget(); // unique collection of dragged tasks HashSet&lt;Task&gt; draggedTasks = new HashSet&lt;&gt;(); // https://vaadin.com/api/com/vaadin/ui/Table.TableDragMode.html // even in MULTIROW drag mode, the event contains only the row on which the drag started draggedTasks.add((Task) event.getTransferable().getData("itemId")); // we'll get the rest, if any, from the source table selection value draggedTasks.addAll((Collection&lt;Task&gt;) source.getValue()); // remove items from source table draggedTasks.forEach(((Table) source)::removeItem); // add items to destination table target.addItems(draggedTasks); } @Override public AcceptCriterion getAcceptCriterion() { // accept drops only from specified tables, and prevent drops from the source table return new SourceIs(acceptedSources); } }); } // basic bean for easy binding public static class Task { private String name; private int id; public Task(int id, String name) { this.name = name; this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } } } </code></pre> <p>Result:</p> <p><a href="https://i.stack.imgur.com/Kbkkc.gif" rel="nofollow"><img src="https://i.stack.imgur.com/Kbkkc.gif" alt="Vaadin table drag &amp; drop"></a></p>
How to check runtime error of a program in bash? <p>I made a C program that would throw <strong>segmentation fault</strong> error whenever I run it. And then I made a bash script as follows:</p> <pre><code>cat input.txt | ./a.out 1&gt; output.txt 2&gt; error.txt cat error.txt </code></pre> <p>The output of the second line should have been something like <em>segmentation error (core-dumped)</em> But instead it's a blank file. </p> <p>How do I capture the runtime errors of a C program?</p>
<p>Your problem stems from the fact that the <code>Segmentation fault (core dumped)</code> message is <strong>not</strong> generated <em>by your program</em>, it is generated by the shell in which you can the <code>a.out</code> command. The process looks approximately like this:</p> <ul> <li>Your program generates a segfault</li> <li>Your program receives a <code>SIGSEGV</code> signal</li> <li>Your program exits</li> <li>The <code>wait()</code> system call executed by your shell exits with a status code that indicates your program exited abnormally due to a <code>SIGSEGV</code> signal.</li> <li>The shell prints an error message</li> </ul> <p>This is discussed in somewhat more detail in <a href="http://unix.stackexchange.com/a/257665/4989">this answer</a>.</p> <p>If you want to capture this output, you can try something like:</p> <pre><code>$ sh -c 'trap "" 11; ./a.out' 1&gt; output.txt 2&gt; error.txt $ cat error.txt Segmentation fault (core dumped) </code></pre> <p>This will run your code in a subprocess and will inhibit the default handling of the segfault by the shell.</p>
How to ignore an empty constraint in SQL SELECT query <p>I have a simple MySQL database that I am querying from PHP. I have a user input some constraints in via a form, and then want to return results from a SELECT query based on the constraints. What I have is working when both constraints are used. However, if one of the constraints is not specified by the user, the SELECT query is returning no results, which I think is because it seeing the constraint variable as empty. </p> <p>How do I get the SELECT query to use the constraint if it is not empty, but to ignore it if it is empty? </p> <p>Here is what I tried earlier but it isn't working. I thought I could test for empty and use OR to ignore it. </p> <pre><code>$query="SELECT * FROM food_items WHERE (type IN ('$foodtypes') OR ('$foodtypes') &gt; '') AND ('$budget' &gt; '' OR cost &lt;= ('$budget')) "; </code></pre> <p>In this example, type and cost are fields in the database and $foodtypes and $budget are variables taken from the user inputs. </p> <p>Thanks</p>
<p>I think you should build your query differently based on the value of the constraints:</p> <pre><code>$query = "SELECT * FROM food_items WHERE " . ($foodtypes != "" ? "type IN ('$foodtypes')" : "TRUE") . " AND " . ($budget ? "cost &lt;= $budget" : "TRUE") . " AND " . .. and so on .. </code></pre> <p><strong>Security note:</strong> Always escape your SQL strings before using (see mysqli_real_escape_string).</p>
How to rename many groups of rows in Pandas? <p>I have a list of lists:</p> <p>result_list = [[10x20], [10x10], [10x5], [10x2], [10x20, [10x10], [10x5] ....[10x2]]</p> <p>Inside each [ ] there are 10 values. I imported this list of lists to a Pandas Dataframe,I calculated the average and rounded to 2 decimals. </p> <p>I need to rename the rows. As an image is better to explain, I added 2 pictures.</p> <p>Dataframe I have: <a href="https://i.stack.imgur.com/BW2ti.png" rel="nofollow"><img src="https://i.stack.imgur.com/BW2ti.png" alt="enter image description here"></a></p> <p>Dataframe I need: <a href="https://i.stack.imgur.com/SEt7e.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/SEt7e.jpg" alt="enter image description here"></a> </p> <p>Now the code:</p> <pre><code> df.loc['AWA'] = [[0:4], :] df.loc['REM'] = [[4:8], :] df.loc['S1'] = [[8:12], :] df.loc['S2'] = [[12:16], :] df.loc['SWS'] = [[16:20], :] df.loc['stades'] = [[20:24], :] </code></pre> <p>I also thought of "group by". But how can I use it when my rows do not have a name?</p>
<p>Assume I have this <code>df</code></p> <pre><code>df = pd.DataFrame(np.random.rand(24, 10)) df['Total Acc'] = df.sum(1) df </code></pre> <p><a href="https://i.stack.imgur.com/OTWwo.png" rel="nofollow"><img src="https://i.stack.imgur.com/OTWwo.png" alt="enter image description here"></a></p> <p>Create a new index and assign it</p> <pre><code>lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'stades'] lvl1 = ['10x20', '10x10', '10x5', '10x2', ] df.index = pd.MultiIndex.from_product([lvl0, lvl1]) df </code></pre> <p><a href="https://i.stack.imgur.com/qZHTe.png" rel="nofollow"><img src="https://i.stack.imgur.com/qZHTe.png" alt="enter image description here"></a></p>
Rectangle collision in pygame? (Bumping rectangles into each other) <p>I decided to move that Squarey game to pygame, and now I have 2 rectangles that can move around and bump into the walls. However, the rectangles can move right through each other. How would I make them bump into each other and stop? My code:</p> <pre><code>import pygame pygame.init() screen = pygame.display.set_mode((1000, 800)) pygame.display.set_caption("Squarey") done = False is_red = True x = 30 y = 30 x2 = 100 y2 = 30 clock = pygame.time.Clock() while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: is_red = not is_red pressed = pygame.key.get_pressed() if pressed[pygame.K_UP]: y -= 3 if pressed[pygame.K_DOWN]: y += 3 if pressed[pygame.K_LEFT]: x -= 3 if pressed[pygame.K_RIGHT]: x += 3 if pressed[pygame.K_w]: y2 -= 3 if pressed[pygame.K_s]: y2 += 3 if pressed[pygame.K_a]: x2 -= 3 if pressed[pygame.K_d]: x2 += 3 if y &lt; 0: y += 3 if x &gt; 943: x -= 3 if y &gt; 743: y -= 3 if x &lt; 0: x += 3 if y2 &lt; 0: y2 += 3 if x2 &gt; 943: x2 -= 3 if y2 &gt; 743: y2 -= 3 if x2 &lt; 0: x2 += 3 screen.fill((0, 0, 0)) if is_red: color = (252, 117, 80) else: color = (168, 3, 253) if is_red: color2 = (0, 175, 0) else: color2 = (255, 255, 0) rect1 = pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60)) rect2 = pygame.draw.rect(screen, color2, pygame.Rect(x2, y2, 60, 60)) pygame.display.flip() clock.tick(60) pygame.quit() </code></pre>
<p>To check for collisions, try something like this:</p> <pre><code>def doRectsOverlap(rect1, rect2): for a, b in [(rect1, rect2), (rect2, rect1)]: # Check if a's corners are inside b if ((isPointInsideRect(a.left, a.top, b)) or (isPointInsideRect(a.left, a.bottom, b)) or (isPointInsideRect(a.right, a.top, b)) or (isPointInsideRect(a.right, a.bottom, b))): return True return False def isPointInsideRect(x, y, rect): if (x &gt; rect.left) and (x &lt; rect.right) and (y &gt; rect.top) and (y &lt; rect.bottom): return True else: return False </code></pre> <p>Then, while moving them, you can call</p> <pre><code>if doRectsOverlap(rect1, rect2): x -= 3 y -= 3 rect1 = pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60)) </code></pre> <p>Or something like that.</p>
react authentication flow verification <p>I have some API in nodejs and a React App for client side. I try to create the auth system for my API/backoffice with a jwt token, I use <code>jsonwebtoken</code> for create and verify token on server side but I have some doubt for client side...now on login I save the token on localstorage, then with React-Router "onUpdate" I check if local storage has a token, if not I redirect to login else nothing append, then on my app I append an auth header for each ajax request. </p> <p>This is my router</p> <pre><code>export const isLoggedIn = (nextState, replace) =&gt; { console.log(localStorage.getItem('id_token')); } &lt;Router history={browserHistory} onUpdate={isLoggedIn} &gt; &lt;Route path="/" component={App}&gt; &lt;IndexRoute component={Login.Login} /&gt; &lt;Route path="admin/" component={Dashboard} /&gt; &lt;Route path="admin/tutti" component={Users} /&gt; &lt;/Route&gt; &lt;/Router&gt; </code></pre> <p>Here I login</p> <pre><code>$.get('/login',credential, function (result) { localStorage.setItem('id_token', result.token) }); </code></pre> <p>Generic request:</p> <pre><code>$.ajax({ url:"/api/users", type:'GET', contentType: "application/json", success:function (result) {}, headers: {"x-access-token": localStorage.getItem('id_token')} }); </code></pre> <p>is this a correct way to manage the React auth flow? my doubt is, on isLoggedIn I need to verify the token in some way?</p> <p>thank you at all!</p>
<p>Do you know <code>Higher Order Components</code>?</p> <p>Here is an article about HOC: <a href="https://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e#.hb4ck2u52" rel="nofollow">https://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e#.hb4ck2u52</a></p> <p>React authentication flow can be written as a HOC.</p> <p>For example:</p> <pre><code>import React, { Component, PropTypes } from 'react'; export default function (ComposedComponent) { class Auth extends Component { componentWillMount() { const isLoggedIn = .... // your way to check if current user is logged in if (!isLoggedIn) { browserHistory.push('/'); // if not logged in, redirect to your login page } } render() { return &lt;ComposedComponent {...this.props} /&gt;; } } return Auth; } </code></pre> <p>But I suggest you to use FLUX flow, such as Redux, and store your state in Redux store.</p> <p>Here is my Redux implementation:</p> <pre><code>import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { browserHistory } from 'react-router'; export default function (ComposedComponent) { class Auth extends Component { componentWillMount() { if (!this.props.isLoggedIn) { browserHistory.push('/login'); } } componentWillUpdate(nextProps) { if (!nextProps.isLoggedIn) { browserHistory.push('/login'); } } render() { return &lt;ComposedComponent {...this.props} /&gt;; } } Auth.propTypes = { isLoggedIn: PropTypes.bool.isRequired, }; function mapStateToProps(state) { return { isLoggedIn: state.userReducer.isLoggedIn }; } return connect(mapStateToProps)(Auth); } </code></pre> <p>Usage:</p> <pre><code>import auth from '/path/to/HOC/Auth'; &lt;Router history={browserHistory}&gt; &lt;Route path="/" component={App}&gt; &lt;IndexRoute component={Login.Login} /&gt; &lt;Route path="admin/" component={auth(Dashboard)} /&gt; // wrap components supported to be protected &lt;Route path="admin/tutti" component={auth(Users)} /&gt; &lt;/Route&gt; &lt;/Router&gt; </code></pre>
Declare enum as a class property (for child classes to define later?) <p>I am making a game in Unity, and all of the player characters and enemy character's actions are determined by the value of enumerated type <code>moveState</code>. (The update function first queries the variable <code>myMoveState</code> and calls a switch/case function <code>MoveStateAction()</code> to decide what to do.) I want their parent class, <code>ActorClass</code>, to declare this enum so I don't have to declare it in every single script. Problem is, each actor has different possible <code>moveState</code>s. Whereas one enemy may be able to Charge, Return, Wait, and Search, maybe another enemy can Jump, Fall, Run, and Stop (these could be any state of action that needs to call a particular method). I want the child class to inherit the enum declaration and fill it with its own values.</p> <p>I've tried to make the enum a property using <code>{ get; set; }</code> but the compiler reads "get" as the first enumeration and reads the semicolon as a syntax error. I've looked into using a generic property but I don't know if it's possible, let alone how to implement it. Microsoft's API guide is confusing.</p> <p>And what if there's no way to declare an empty enum as a property? Is there a better way? I could use a different variable type just as well, but my code wouldn't be nearly as readable. And I don't even think I could use a <code>typedef</code> alias to improve readability.</p> <p>Here's what the generic code looks like for an enemy:</p> <pre><code>void Start () { myBody = GetComponent&lt;Rigidbody2D&gt; (); myDirection = Direction.S; myMoveState = moveState.START; currentSpeed = new Vector2(0, 0); previousSpeed= new Vector2(0, 0); } void FixedUpdate () { currentSpeed = myBody.velocity; previousSpeed *= dragScale; MoveStateAction(); previousSpeed = currentSpeed; myBody.velocity = currentSpeed; } </code></pre>
<p>I think you are viewing the problem from an unfavorable angle. What are you going to do? You define a property in a parent class, inherit it by the child class and then say "Nah, lets kick out all the values and define new ones". But that is not the parent property anymore, nor is this the idea of inheritance.</p> <p>So why do you want to make a property that can be inherited? Probably because you want all children to react the same way on the property. So the most favorable way probably would be to define an enum with all possible move states, and then block those you don't want for the specific class. For example, define a function CheckMoveState that returns None if MoveState is not one of the allowed states (for example, if it is Jump even though the create can only slither), and invoke this function each time a MoveState is passed to the class property in the setter.</p> <p>So this is the definition in the parent class:</p> <pre><code>public enum MoveState { None, Jump, Stop, Slither } </code></pre> <p>And in the child class we have:</p> <pre><code>private MoveState CheckMoveState(MoveState myMoveState) { if (myMoveState == MoveState.Slither || myMoveState == MoveState.Stop) return myMoveState; return MoveState.None; } private MoveState _currentMoveState = MoveState.None; public MoveState CurrentMoveState { get { return _currentMoveState; } set { _currentMoveState = CheckMoveState(value); } } </code></pre>
How can I find out if two lines overlap? <p>My function takes two objects that represent lines and is supposed to return whether they overlap or not. Overlapping returns "true", but not overlapping doesn't seem to return false. Any idea why? </p> <pre><code>function checkOverlap(line1, line2) { if(line2.start &lt;= line1.end || line1.start &lt;=line2.end) { return true } else { return false } } </code></pre>
<p>You have to check whether one line's start is between the start and end of the other line.</p> <pre><code> if((line2.start &lt;= line1.end &amp;&amp; line2.start &gt;=line1.start) || (line1.start &lt;=line2.end &amp;&amp; line1.start &gt;= line2.start)) { return true; } </code></pre>
How is numpy pad implemented (for constant value) <p>I'm trying to implement the numpy pad function in theano for the constant mode. How is it implemented in numpy? Assume that pad values are just 0.</p> <p>Given an array </p> <pre><code>a = np.array([[1,2,3,4],[5,6,7,8]]) # pad values are just 0 as indicated by constant_values=0 np.pad(a, pad_width=[(1,2),(3,4)], mode='constant', constant_values=0) </code></pre> <p>would return</p> <pre><code>array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0], [0, 0, 0, 5, 6, 7, 8, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) </code></pre> <p>Now if I know the number of dimensions of a beforehand, I can just implement this by creating a new array of the new dimensions filled the pad value and fill in the corresponding elements in this array. But what if I don't know the dimensions of the input array? While I can still infer the dimensions of the output array from the input array, I have no way of indexing it without knowing the number of dimensions in it. Or am I missing something?</p> <p>That is, if I know that the input dimension is say, 3, then I could do:</p> <pre><code>zeros_array[pad_width[0][0]:-pad_width[0][1], pad_width[1][0]:-pad_width[1][1], pad_width[2][0]:-pad_width[2][1]] = a </code></pre> <p>where zeros array is the new array created with the output dimensions.</p> <p>But if I don't know the ndim before hand, I cannot do this.</p>
<p>My instinct is to do:</p> <pre><code>def ...(arg, pad): out_shape = &lt;arg.shape + padding&gt; # math on tuples/lists idx = [slice(x1, x2) for ...] # again math on shape and padding res = np.zeros(out_shape, dtype=arg.dtype) res[idx] = arg # may need tuple(idx) return res </code></pre> <p>In other words, make the target array, and copy the input with the appropriate indexing tuple. It will require some math and maybe iteration to construct the required shape and slicing, but that should be straight forward if tedious.</p> <p>However it appears that <code>np.pad</code> iterates on the axes (if I've identified the correct alternative:</p> <pre><code> newmat = narray.copy() for axis, ((pad_before, pad_after), (before_val, after_val)) \ in enumerate(zip(pad_width, kwargs['constant_values'])): newmat = _prepend_const(newmat, pad_before, before_val, axis) newmat = _append_const(newmat, pad_after, after_val, axis) </code></pre> <p>where <code>_prepend_const</code> is:</p> <pre><code>np.concatenate((np.zeros(padshape, dtype=arr.dtype), arr), axis=axis) </code></pre> <p>(and <code>append</code> would be similar). So it is adding each pre and post piece separately for each dimension. Conceptually that is simple even if it might not be the fastest.</p> <pre><code>In [601]: np.lib.arraypad._prepend_const(np.ones((3,5)),3,0,0) Out[601]: array([[ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.]]) In [604]: arg=np.ones((3,5),int) In [605]: for i in range(2): ...: arg=np.lib.arraypad._prepend_const(arg,1,0,i) ...: arg=np.lib.arraypad._append_const(arg,2,2,i) ...: In [606]: arg Out[606]: array([[0, 0, 0, 0, 0, 0, 2, 2], [0, 1, 1, 1, 1, 1, 2, 2], [0, 1, 1, 1, 1, 1, 2, 2], [0, 1, 1, 1, 1, 1, 2, 2], [0, 2, 2, 2, 2, 2, 2, 2], [0, 2, 2, 2, 2, 2, 2, 2]]) </code></pre>
Catch anything and save it into a variable <p>I'm wondering if there is a keyword for "all" in python <code>except</code>. I've ran into this seemingly simple problem:</p> <pre><code>try: #do stuff except any as error: print('error: {err}'.format(err=error)) </code></pre> <p>I know that you can do <code>except:</code> to catch all errors, but I don't know how to add an <code>as</code> keyword to get a <code>print</code>able object. I want to catch any error and be able to get an object for use in printing or something else.</p>
<p>You can catch almost anything this way:</p> <pre><code>try: #do stuff except Exception as error: print('error: {err}'.format(err=error)) </code></pre> <p>But to catch really everything, you can do this:</p> <pre><code>import sys try: #do stuff except: err_type, error, traceback = sys.exc_info() print('error: {err}'.format(err=error)) </code></pre>
Notepad++ and autocompletion <p>I'm using mainly <strong><a href="https://notepad-plus-plus.org/" rel="nofollow">Notepad++</a></strong> for my C++ developing and recently i'm in need for some kind of <em>basic autocompletion</em>, nothing fuzzy, just want to type some letters and get my <strong>function declaration</strong> instead of having a manual opened all of the time..</p> <p>The integrated autocompletion feature of my Notepad++ version (6.9.2) gives the declaration of basic C functionality like say <strong><a href="http://www.cplusplus.com/reference/cstdio/fopen" rel="nofollow">fopen</a></strong> and parses my <em>current file</em> user defined functions, but without declaration.</p> <p>I guess it's normal for a text editor to not give easily such information since it has nothing to parse i.e. other files where your declarations are (as it's not an IDE), but i don't want either to mess again with MSVC just for the sake of autocomplete.</p> <p>Is there an easy, not so-hackish way to add some basic C++ and/or user defined autocomplete?</p> <p><strong>UPDATE</strong></p> <p>Adding declarations the "hard way" in some file <strong>cpp.xml</strong> is a no-no for me as i have a pretty big base of ever changing declarations. Is there a way to just input say some list of <em>h/cpp</em> files and get declarations? or this falls into <em>custom plugin</em> area ?</p>
<p>Edit the <strong><em>cpp.xml</em></strong> file and add all the keywords and function descriptions you'd like. Just make sure you add them in alphabetical order or they will not show up.</p> <p>Another option is to select <strong><em>Function and word completion</em></strong> in the <strong><em>Auto-Completion</em></strong> area of the <strong><em>Settings-->Preferences</em></strong> dialog. NPP will suggest every "word" in the current file that starts with the first N letters you type (you choose a value for N in the Auto-Completion controls).</p>
how to display and then change array of images by set number of click of a button <p>I'm working on Xcode 8 and Swift 3.</p> <p>So far I have connected a button with a label. The label is set at 0 and by clicking it, it will change the number by 1.</p> <p>Now what I'm trying to do is I want to set an array of images to be displayed after clicking it.</p> <p>So image 1 shown at 0 then image 2 shown once the button is clicked 1-10 times,</p> <p>then image 3 shown after button is clicked 20-30 times,</p> <p>then image 4 is shown after 30-40 clicks/taps of the button.</p> <p>Also the other images are hidden time the respected number of clicks.</p>
<p>Here's a pseudo code for array of JPEGs:</p> <pre><code>var arrayOfPictures: [UIImage] = [] arrayOfPictures.append(UIImage(named:"Image1.jpg")!) arrayOfPictures.append(UIImage(named:"Image2.jpg")!) arrayOfPictures.append(UIImage(named:"Image3.jpg")!) </code></pre> <p>Here's a pseudo code for button's method:</p> <pre><code>var counter: Int = 0 @IBAction func showPicture(sender: AnyObject?) { counter += 1 if counter == 0 { arrayOfPictures[0] } else if counter &gt;= 1 &amp;&amp; counter &lt;= 10 { arrayOfPictures[1] } else if counter &gt;= 11 &amp;&amp; counter &lt;= 20 { arrayOfPictures[2] } else if .................... ............................ } </code></pre> <p>¡Hope this helps!</p>
Parse no response with nested/chained saves <p>So I have two objects which I am saving. However, I want to store a reference to one of the object (lets call it a) on the other (b) so I am saving 'a' first and then once the save is complete, saving object 'b' after setting the reference into its proper field. However, though it seems like response.success line is being hit, the success/error function is not triggered on the caller. It just hangs and timesout.</p> <p>The caller code looks as follows </p> <pre><code> Parse.Cloud.run('createObject', params).then( (success) =&gt; { //neither are called, timeout results console.log("Success!"); }, (error) =&gt; { //neither are called, timeout results console.log("Error!"); } ); </code></pre> <p>The snippet of code from 'createObject' that causes no response to be sent</p> <pre><code> newA.save().then(function(objA) { newB.set('refA', objA); return newB.save(); }, function(error) { response.error( utils.sformat( 'Error saving new A with params {1}: {0}', JSON.stringify(request.params), JSON.stringify(error) ) ); }).then(function(objB) { response.success({ b: objB }); }, function(error) { response.error( utils.sformat( 'Error saving new B with params {1}: {0}', JSON.stringify(request.params), JSON.stringify(error) ) ); }); </code></pre> <p>Now if I do something like a batch save and have an array of objectA and objectB and call Parse.Object.saveAll, it goes through and there is a response... but I can't exactly use that if I want that reference to be set. I'm puzzled as to why there the response does not get sent when saves are chained/nested like that.</p> <p>The biggest issue I have is that the objects both get created and saved 100% correctly and properly. So I'm really not sure why this code hangs.</p> <p>Edit: I forgot to mention but objectA has an aftersave trigger. But atm all it does is print out some test lines and disabling it hasn't seem to have changed anything.</p>
<p>It actually works. The problem was that I had a function within the response.success call that was being made to format the object before sending it back but I was getting a nullpointexception due to something I was trying to access. I didn't turn on verbose logging so parse never told me that this was happening.</p> <p>The code above works fine as it stands.</p>
count number of 0 with floodfill algorithm <p>I wanted to count number of 0 and 1 from a 2d array with floodfill algorithm....But unfortunetly...it's showing the wrong result.</p> <p>I have a matrix like this</p> <pre><code>0,1,1,0,1 1,0,1,1,0 1,0,1,1,0 1,0,1,1,0 1,0,1,1,0 </code></pre> <p>It supposed to show number of 0 = 10 and 1 =15</p> <p>but it showing number of 0 = 4 and 1 = 21</p> <p>here is my code</p> <pre><code>int[][] input; public static int[,] reult; public static int count = 0,col,row; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string path; OpenFileDialog file = new OpenFileDialog(); if (file.ShowDialog() == DialogResult.OK) { input = File.ReadLines(file.FileName) .Skip(0) .Select(l =&gt; l.Split(',') .Select(n =&gt; int.Parse(n)) .ToArray()) .ToArray(); } reult = JaggedToMultidimensional(input); int p = reult.GetLength(0); int q = reult.GetLength(1); row = p-1; col = q - 1; int one = p * q; int zero = apply(row, col); label1.Text = "" + zero; label2.Text = "" + (one - zero); } public T[,] JaggedToMultidimensional&lt;T&gt;(T[][] jaggedArray) { int rows = jaggedArray.Length; int cols = jaggedArray.Max(subArray =&gt; subArray.Length); T[,] array = new T[rows, cols]; for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; cols; j++) { array[i, j] = jaggedArray[i][j]; } } return array; } private static int apply(int x, int y) { int currentColor = getValueAt(x, y); if (currentColor == 0) { visit(x, y); count++; if (x &lt; row) apply(x + 1, y); if(y&lt;col) apply(x, y + 1); if(x&gt;0) apply(x - 1, y); if (y&gt;0) apply(x, y - 1); } return count; } private static int getValueAt(int x, int y) { if (x &lt; 0 || y &lt; 0 || x &gt; row || y &gt; col) { return -1; } else { return reult[x,y]; } } private static void visit(int x, int y) { reult[x,y] = 1; } </code></pre>
<pre><code>int zero = apply(row, col); </code></pre> <p>In your flood fill algorithm, you are only going in four direction and cover the area which match your criteria. And fortunately <code>[row,col]</code> index has <code>0</code> and it count all four 0 from <code>[row, col]</code>. Now think what if <code>apply(row,col)</code> have <code>1</code> on that <code>row, col</code> index.</p> <p>To get this thing right, you need to loop through whole matrix and call <code>apply(i,j)</code> where ever you find an <code>array[i,j]==0</code></p> <p>Change this line </p> <pre><code>int zero = apply(row, col); </code></pre> <p>to </p> <pre><code>int zero = 0; for(int i=0; i&lt;=row; i++) { for(int j=0; j&lt;=col; j++) { if(array[i][j]==0) { count =0; zero+= apply(row, col); } } } </code></pre> <p>Hope this helps.</p>
Checking With Assertion <p>The methods setDates and setTimes have as preconditions that none of their arguments are null. This is to be checked by means of an assertion. (This means that if the precondition is not met, the program will fail at the assertion, and an AssertionError will be thrown.)</p> <p>here is my code: </p> <pre><code>public class Section { /** * Default section number. */ private static final String DEFAULT_SECTION_NUMBER = ""; /** * Constant for building Strings with newline characters within them. */ private static final String LINE_SEPARATOR = System. getProperty("line.separator"); /** * The maximum number of students permitted into a section. */ private static final int MAXIMUM_STUDENTS_PER_SECTION = 30; /** * Valid length for a sectionNumber string. */ private static final int SECTION_NUMBER_LENGTH = 3; /** * Shared variable for keeping count of the number of section objects in * existence. */ private static int count = 0; /** * The date at which the section is finished. */ private Date endDate; /** * The end time for the meeting of the section. */ private Time2 endTime; /** * The list of students in the class. This declaration uses the Java 7 facility * of not repeating the generic type if that type can be inferred by the * compiler. */ private final List&lt;Student&gt; roster = new ArrayList&lt;&gt;(); /** * The three-character designation of the section (called a * &amp;ldquo;number&amp;rdquo;). */ private String sectionNumber = DEFAULT_SECTION_NUMBER; /** * The date on which the section starts to meet. */ private Date startDate; /** * The time of day at which the section meets. */ private Time2 startTime; /** * The course of which this is a section. */ private final Course thisCourse; /** * Constructor. * * @param course the course of which this is a section * @param sectionNumber the section number (within the course) of this section * @throws SectionException */ public Section(Course course, String sectionNumber) throws SectionException { /* Increment the collective count of all Section objects that have been created. Do this first as the object already exists. */ ++count; this.thisCourse = course; try { if( isValidSectionNumber(sectionNumber) ) this.sectionNumber = sectionNumber; } catch (Exception ex) { throw new SectionException("Error in constructor", ex); } } /** * Add a student to the course. * * @param student the student object to be added. If the course is full, the * student is not added */ public void addStudent(Student student) { if( roster.size() != MAXIMUM_STUDENTS_PER_SECTION ) roster.add(student); } /** * Get details about the current state of this section, including the course of * which it is part, the dates it starts and ends, times, etc., and the current * count of the enrollment. * * @return the section details */ public String getDetails() { return String.join(LINE_SEPARATOR, "Section: " + this.toString(), "Course: " + thisCourse.getDetails(), "Dates: " + startDate + " to " + endDate, "Times: " + startTime + " to " + endTime, "Enrollment: " + roster.size()); } /** * Create a string that represents the information about the students in the * course. * * @return a string that represents the information about the students in the * course */ public String getRoster() { /* The following commented-out code is the obvious way to do this, using String concatenation (and this is acceptable). However, the recommended Java approach to this kind of operation is to use a StringJoiner (new class in Java 8), as this uses less garbage collection resources. */ // String result = ""; // for( Student student : roster ) // { // result += ( result.isEmpty() ? "" : LINE_SEPARATOR) + student; // } // return result; StringJoiner stringJoiner = new StringJoiner(LINE_SEPARATOR); for( Student student : roster ) stringJoiner.add(student.toString()); return stringJoiner.toString(); } /** * Get a count of the number of students registered (on the roster) for this course. * * @return a count of the number of students registered for this course */ public int getRosterCount() { return roster.size(); } /** * Get the section number for this course. * * @return the section number for this course */ public String getSectionNumber() { return sectionNumber; } /** * Set the start and end dates for the section. * * @param startDate the start date * @param endDate the end date */ public void setDates(Date startDate, Date endDate) { /* There is no requirement to validate these. */ this.startDate = startDate; this.endDate = endDate; } /** * Set the start time and the end time for the meetings of the section. * * @param startTime the start time for meetings of the section * @param endTime the end time for the meetings of the section */ public void setTimes(Time2 startTime, Time2 endTime) { /* There is no requirement to validate these. */ this.startTime = startTime; this.endTime = endTime; } /** * Section number (prefixed) * * @return Section number (prefixed) */ @Override public String toString() { return thisCourse.toString() + "-" + sectionNumber; } /** * Finalization. Reduce the instance count by 1. * * @throws Throwable standard interface. */ @SuppressWarnings("FinalizeDeclaration") @Override protected void finalize() throws Throwable { /* Decrement the count of the collective total of all Section objects. */ --count; super.finalize(); } /** * Get a count of how many total Section objects are currently in existence. * * @return a count of how many Section objects are currently in existence */ public static int getSectionCount() { return count; } /** * Validate the sectionNumber string. It must be of the correct length. * * @param sectionNumber the sectionNumber string * @return true if the string if valid, otherwise false */ private static boolean isValidSectionNumber(String sectionNumber) { return sectionNumber != null &amp;&amp; sectionNumber.length() == SECTION_NUMBER_LENGTH; } } </code></pre> <p>would i simply place 'assert' before this.startDate = startDate; and so forth??? my book only has one example and it is for ensuring a value is between 0 and 10.</p> <p>this is the example my book uses:</p> <pre><code>public class AssertTest { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number between 0 and 10: "); int number = input.nextInt(); //assert that the value is &gt;= 0 and &lt;= 10 assert (number &gt;= 0 &amp;&amp; number &lt;= 10) : "bad number: " + number; System.out.printf("You entered %d%n", number); } } </code></pre> <p>so could i say</p> <pre><code>assert this.startDate = startDate assert this.endDate = endDate </code></pre> <p>and so on?</p>
<p>First of all the methods setTime and setDates are public what suggests that they may be used outside of the package. Given that you have no control over parameters - using assert would not be considered as the best practice. You should rather use Runtime Exceptions such as IllegalArgumentException when value can be supplied externally (and you have no control over it):</p> <pre><code>if (startDate == null || endDate == null) throw new IllegalArgumentException("Non-null arguments are required"); </code></pre> <p>The syntax for the Assert would be as follows:</p> <pre><code>assert startDate != null; assert endDate != null; </code></pre> <p>You can also use the following syntax in order to output additional information when assertion fails:</p> <pre><code>assert startDate != null : "startDate was set to null" assert endDate != null : "endDate was set to null" </code></pre>
How to avoid using literal strings to narrow disjoint unions in flow <p>All the examples I find online for narrowing the disjoint union in flowtype uses string literals, like <a href="https://flowtype.org/docs/disjoint-unions.html#_" rel="nofollow">the official one</a>. I would like to know if there is a way to check against a value from an enum like:</p> <pre><code>const ACTION_A = 'LITERAL_STRING_A'; const ACTION_B = 'LITERAL_STRING_B'; type ActionA = { // This is not allowed type: ACTION_A, // type: 'LITERAL_STRING_A' is allowed dataA: ActionAData, } type ActionB = { // This is not allowed type: ACTION_B, // type: 'LITERAL_STRING_B' is allowed dataB: ActionBData, } type Action = ActionA | ActionB; function reducer(state: State, action: Action): State { // Want to narrow Action to ActionA or ActionB based on type switch (action.type) { // case 'LITERAL_STRING_A': -- successfully narrow the type case ACTION_A: // doesn't work // action.dataA is accessible ... } ... } </code></pre> <p>Unfortunately you can't do these because strings are ineligible as type annotations.</p> <p>If there is any other way around this that doesn't force typing the string literals everywhere I would love to know.</p> <p>If there isn't a way around this, also accept suggestions on a higher level how to not need to define these disjoint sets for redux actions.</p>
<p>I'm not in my best shape right now, so sorry if I read your question wrong. I'll try to help anyway. Is this what you're looking for?</p> <pre><code>const actionTypes = { FOO: 'FOO', BAR: 'BAR' } type ActionType = $Keys&lt;actionTypes&gt; // one of FOO, BAR function buzz(actionType: ActionType) { switch(actionType) { case actionTypes.FOO: // blah } </code></pre> <p>This should work. Sorry if my syntax is a bit off.</p> <p>If you're asking how to avoid listing all action types in <code>type Action = ActionA | ActionB</code> then sorry, I don't know, I think this is the way you do it. If I recall correctly, a slightly nicer syntax for defining long unions was recently introduce in Flow:</p> <pre><code>type Action = | ActionA | ActionB | ActionC </code></pre> <p>Also, if you don't need individual action types, you can just do</p> <pre><code>type Action = | {type: ACTION_A; dataA: ActionAData;} | {type: ACTION_B; dataB: ActionBData;} </code></pre>
PHP function duplicating data <p>I am trying to make a comment section with MySQL and PHP. But, for some reason, whenever I refresh the page, the data gets duplicated. This happens every time I refresh the page.</p> <p>Example</p> <p><a href="https://i.stack.imgur.com/A3HEe.png" rel="nofollow"><img src="https://i.stack.imgur.com/A3HEe.png" alt="img1"></a></p> <p><a href="https://i.stack.imgur.com/6zh8h.png" rel="nofollow"><img src="https://i.stack.imgur.com/6zh8h.png" alt="img2"></a></p> <p>It shouldn't be doing this, but it does. I think it has something to do with the <code>setComment()</code> function, but I'm not sure.</p> <p>index.php</p> <pre><code>&lt;?php include 'dbh_comments.inc.php'; include 'comments.inc.php'; ?&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Comments&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="comment_styles.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;?php echo"&lt;form method='POST' action='".setComment($conn)."'&gt; &lt;input type='hidden' name='uid' value='Anonymous'&gt; &lt;textarea name='message'&gt;&lt;/textarea&gt;&lt;br/&gt; &lt;button type='submit' name='comment_submit'&gt;Comment&lt;/button&gt; &lt;/form&gt;"; ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>comments.inc.php</p> <pre><code>&lt;?php function setComment($conn) { if(isset($_POST['comment_submit']) &amp;&amp; isset($_POST['message']) !== '') { $uid = $_POST['uid']; $message = $_POST['message']; $sql = "INSERT INTO comments (uid, message) VALUES ('$uid', '$message')"; $result = mysqli_query($conn, $sql); } } function getComments($conn) { $sql = "SELECT * FROM comments"; $result = $conn-&gt;query($sql); while ($row = $result-&gt;fetch_assoc()) { echo $row['message']; } } getComments($conn); </code></pre>
<p>Yea, you are right, the problem is there:</p> <pre><code>&lt;?php echo"&lt;form method='POST' action='".setComment($conn)."'&gt; &lt;input type='hidden' name='uid' value='Anonymous'&gt; &lt;textarea name='message'&gt;&lt;/textarea&gt;&lt;br/&gt; &lt;button type='submit' name='comment_submit'&gt;Comment&lt;/button&gt; &lt;/form&gt;"; ?&gt; </code></pre> <p>function <code>setComment</code> is called everytime you visit page and save new row to DB</p>
QTextLayout manual line breaking <p>I'm trying to render lines one by one using <code>QTextLayout</code>. I've tried to set <code>wrapMode</code> to <code>QTextOption::ManualWrap</code> and call <code>QTextLine::setNumColumns</code> for each line but the whole text appears in a single line.</p> <p>I've also tried to set <code>wrapMode</code> to <code>QTextOption::WrapAnywhere</code> and this time the text is broken into lines but the empty lines (the ones which consist only of <code>\n</code>) are not visible.</p> <p>I've tried to link against both <code>Qt4</code> and <code>Qt5</code> with no results.</p> <p>What am I doing wrong?</p>
<p><a href="http://doc.qt.io/qt-5/qtextline.html" rel="nofollow">QTextLine</a> is used for single line text. If you want multiple lines then use <a href="http://doc.qt.io/qt-5/qtextedit.html" rel="nofollow">QTextEdit</a>.</p>
Datatables doesnt get fit width columns on print? <p>I try to print datatables, but why when I print it doesnt get fit width coulmns,? here's my result <a href="https://postimg.org/image/i0eue3xhh/" rel="nofollow">Screenshot from 2016-10-17 06-38-39.png</a></p> <p>any way to add in my code.? I'm totaly newbie</p>
<p>Assign your table columns a width.</p>
android.view.InflateException: Binary XML file line #69: Error inflating class, when using a custom font for edittext <p>please am trying to use a custom font which i did, but my app crashes when its suppose to start the LoginActivity. have searched but could not find a solution the issue. this is the error msg......</p> <p>E/AndroidRuntime: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.squaresoft.spotr/com.squaresoft.spotr.LoginActivity}: android.view.InflateException: Binary XML file line #69: Error inflating class com.squaresoft.customfonts.MyEditText at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135) at android.app.ActivityThread.access$700(ActivityThread.java:140) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4946) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1036) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:803) at dalvik.system.NativeStart.main(Native Method) Caused by: android.view.InflateException: Binary XML file line #69: Error inflating class com.squaresoft.customfonts.MyEditText at android.view.LayoutInflater.createView(LayoutInflater.java:613) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687) at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) at android.view.LayoutInflater.inflate(LayoutInflater.java:489) at android.view.LayoutInflater.inflate(LayoutInflater.java:396) at android.view.LayoutInflater.inflate(LayoutInflater.java:352) at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:308) at android.app.Activity.setContentView(Activity.java:1924) at com.squaresoft.spotr.LoginActivity.onCreate(LoginActivity.java:34) at android.app.Activity.performCreate(Activity.java:5206) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)  at android.app.ActivityThread.access$700(ActivityThread.java:140)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)  at android.os.Handler.dispatchMessage(Handler.java:99)  at android.os.Looper.loop(Looper.java:137)  at android.app.ActivityThread.main(ActivityThread.java:4946)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:511)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1036)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:803)  at dalvik.system.NativeStart.main(Native Method)  Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Constructor.constructNative(Native Method) at java.lang.reflect.Constructor.newInstance(Constructor.java:417) at android.view.LayoutInflater.createView(LayoutInflater.java:587) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)  at android.view.LayoutInflater.inflate(LayoutInflater.java:489)  at android.view.LayoutInflater.inflate(LayoutInflater.java:396)  at android.view.LayoutInflater.inflate(LayoutInflater.java:352)  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:308)  at android.app.Activity.setContentView(Activity.java:1924)  at com.squaresoft.spotr.LoginActivity.onCreate(LoginActivity.java:34)  at android.app.Activity.performCreate(Activity.java:5206)  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)  at android.app.ActivityThread.access$700(ActivityThread.java:140)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)  at android.os.Handler.dispatchMessage(Handler.java:99)  at android.os.Looper.loop(Looper.java:137)  at android.app.ActivityThread.main(ActivityThread.java:4946)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:511)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1036)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:803)  at dalvik.system.NativeStart.main(Native Method)  Caused by: java.lang.RuntimeException: native typeface cannot be made at android.graphics.Typeface.(Typeface.java:265) at android.graphics.Typeface.createFromAsset(Typeface.java:239) at com.squaresoft.customfonts.MyEditText.init(MyEditText.java:30) at com.squaresoft.customfonts.MyEditText.(MyEditText.java:20) at java.lang.reflect.Constructor.constructNative(Native Method)  at java.lang.reflect.Constructor.newInstance(Constructor.java:417)  at android.view.LayoutInflater.createView(LayoutInflater.java:587)  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)  at android.view.LayoutInflater.inflate(LayoutInflater.java:489)  at android.view.LayoutInflater.inflate(LayoutInflater.java:396)  at android.view.LayoutInflater.inflate(LayoutInflater.java:352)  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:308)  at android.app.Activity.setContentView(Activity.java:1924)  at com.squaresoft.spotr.LoginActivity.onCreate(LoginActivity.java:34)  at android.app.Activity.performCreate(Activity.java:5206)  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)  at android.app.ActivityThread.access$700(ActivityThread.java:140)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)  at android.os.Handler.dispatchMessage(Handler.java:99)  at android.os.Looper.loop(Looper.java:137)  at android.app.ActivityThread.main(ActivityThread.java:4946)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:511)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1036)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:803)  at dalvik.system.NativeStart.main(Native Method) </p> <p>for my LoginActivity.....</p> <pre><code>package com.squaresoft.spotr; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class LoginActivity extends Activity { EditText email, pass; Button log; TextView signin, fb, account; TextView signup; SQLiteDBHelper dbhelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //Referencing UserEmail, Password EditText and TextView for SignUp fb = (TextView)findViewById(R.id.fb); account = (TextView)findViewById(R.id.account); email = (EditText) findViewById(R.id.emailT); pass = (EditText) findViewById(R.id.passwordT); log = (Button) findViewById(R.id.buttonsignin); signup = (TextView)findViewById(R.id.signup); signin = (TextView)findViewById(R.id.signin); //Opening SQLite Pipeline dbhelper = new SQLiteDBHelper(this); dbhelper = dbhelper.open(); log.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email1 = email.getText().toString(); String pass1 = pass.getText().toString(); // fetch the Password form database for respective user name String storedPassword = dbhelper.getSinlgeEntry(email1); // check if the Stored password matches with Password if (pass1.equals(storedPassword)) { Toast.makeText(LoginActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show(); Intent intent = new Intent(LoginActivity.this,Home.class); startActivity(intent); } else { Toast.makeText(LoginActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show(); email.setText(""); pass.setText(""); } } }); // Intent For Opening RegisterAccountActivity signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(LoginActivity.this, SignUp.class); startActivity(intent); } }); } @Override protected void onDestroy() { super.onDestroy(); // Close The Database dbhelper.close(); } } </code></pre> <p>the xml for login...</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" &gt; &lt;FrameLayout android:layout_width="match_parent" android:layout_height="260dp"&gt; &lt;ImageView android:layout_width="match_parent" android:layout_height="260dp" android:background="@drawable/banner"/&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_gravity="center|bottom" android:background="#80000000"&gt; &lt;TextView android:id="@+id/signin" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="Sign in" android:textColor="#087272" android:textSize="16dp" android:layout_gravity="center" android:gravity="center" android:padding="16dp"/&gt; &lt;TextView android:id="@+id/signup" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="Sign up" android:textColor="#fff" android:textSize="16dp" android:padding="16dp"/&gt; &lt;/LinearLayout&gt; &lt;/FrameLayout&gt; &lt;com.squaresoft.customfonts.MyEditText android:id="@+id/emailT" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="E-mail" android:inputType="text" android:textColor="#000" android:background="#f0f0f4" android:padding="12dp" android:layout_marginTop="20dp" android:layout_marginBottom="10dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:drawableLeft="@drawable/ic_shapes_2" android:drawablePadding="16dp" /&gt; &lt;com.squaresoft.customfonts.MyEditText android:id="@+id/passwordT" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Password" android:inputType="textPassword" android:background="#f0f0f4" android:textColor="#000" android:layout_marginTop="10dp" android:layout_marginBottom="20dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:padding="12dp" android:drawablePadding="16dp" android:drawableLeft="@drawable/ic_tool_6" /&gt; &lt;com.squaresoft.customfonts.MyRegulerText android:id="@+id/buttonsignin" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/rounded1" android:layout_marginBottom="5dp" android:layout_marginLeft="70dp" android:layout_marginRight="70dp" android:textAlignment="center" android:padding="14dp" android:text="Sign In" android:textSize="16dp" android:textColor="#fff" /&gt; &lt;com.squaresoft.customfonts.MyRegulerText android:id="@+id/fb" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/rounded" android:layout_marginTop="10dp" android:layout_marginBottom="20dp" android:layout_marginLeft="70dp" android:layout_marginRight="70dp" android:textAlignment="center" android:padding="14dp" android:text="Facebook Connect" android:textColor="#fff" android:textSize="16dp" /&gt; &lt;com.squaresoft.customfonts.MyTextView android:id="@+id/account" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Don't have an account?" android:textSize="16dp" android:layout_gravity="center" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>final the java class for MyEditText</p> <pre><code>package com.squaresoft.customfonts; import android.content.Context; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.EditText; public class MyEditText extends EditText { public MyEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public MyEditText(Context context, AttributeSet attrs) { super(context, attrs); init(); } public MyEditText(Context context) { super(context); init(); } private void init() { if (!isInEditMode()) { Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/Lato-Light.ttf"); setTypeface(tf); } } } </code></pre> <p>thanks for your help. </p>
<p>seems like error happends at LoginActivity:line 34, but line 34 is space in your code copy.</p>
Gradle Multi-Project Setup with Dependencies -> Could not resolve all dependencies <p>I've got a small multi-project setup with gradle (also new to it), but it doesn't compile. I can run it inside of the IDE, but when I want to compile it, it fails. When I then try to use one of the dependencies from the Engine project in the Game project it even fails inside of the IDE. More details further down.</p> <pre><code>:Engine:compileJava UP-TO-DATE :Engine:processResources UP-TO-DATE :Engine:classes UP-TO-DATE :Engine:jar :compileJava FAILURE: Build failed with an exception. * What went wrong: Could not resolve all dependencies for configuration ':compileClasspath'. &gt; Could not find org.lwjgl:lwjgl:3.0.1-SNAPSHOT. Searched in the following locations: https://jcenter.bintray.com/org/lwjgl/lwjgl/3.0.1-SNAPSHOT/maven-metadata.xml https://jcenter.bintray.com/org/lwjgl/lwjgl/3.0.1-SNAPSHOT/lwjgl-3.0.1-SNAPSHOT.pom https://jcenter.bintray.com/org/lwjgl/lwjgl/3.0.1-SNAPSHOT/lwjgl-3.0.1-SNAPSHOT.jar Required by: project : &gt; project :Engine &gt; Could not find org.lwjgl:lwjgl-egl:3.0.1-SNAPSHOT. Searched in the following locations: https://jcenter.bintray.com/org/lwjgl/lwjgl-egl/3.0.1-SNAPSHOT/maven-metadata.xml https://jcenter.bintray.com/org/lwjgl/lwjgl-egl/3.0.1-SNAPSHOT/lwjgl-egl-3.0.1-SNAPSHOT.pom https://jcenter.bintray.com/org/lwjgl/lwjgl-egl/3.0.1-SNAPSHOT/lwjgl-egl-3.0.1-SNAPSHOT.jar Required by: project : &gt; project :Engine &gt; Could not find org.lwjgl:lwjgl-glfw:3.0.1-SNAPSHOT. Searched in the following locations: https://jcenter.bintray.com/org/lwjgl/lwjgl-glfw/3.0.1-SNAPSHOT/maven-metadata.xml https://jcenter.bintray.com/org/lwjgl/lwjgl-glfw/3.0.1-SNAPSHOT/lwjgl-glfw-3.0.1-SNAPSHOT.pom https://jcenter.bintray.com/org/lwjgl/lwjgl-glfw/3.0.1-SNAPSHOT/lwjgl-glfw-3.0.1-SNAPSHOT.jar Required by: project : &gt; project :Engine &gt; Could not find org.lwjgl:lwjgl-jemalloc:3.0.1-SNAPSHOT. Searched in the following locations: https://jcenter.bintray.com/org/lwjgl/lwjgl-jemalloc/3.0.1-SNAPSHOT/maven-metadata.xml https://jcenter.bintray.com/org/lwjgl/lwjgl-jemalloc/3.0.1-SNAPSHOT/lwjgl-jemalloc-3.0.1-SNAPSHOT.pom https://jcenter.bintray.com/org/lwjgl/lwjgl-jemalloc/3.0.1-SNAPSHOT/lwjgl-jemalloc-3.0.1-SNAPSHOT.jar Required by: project : &gt; project :Engine &gt; Could not find org.lwjgl:lwjgl-openal:3.0.1-SNAPSHOT. Searched in the following locations: https://jcenter.bintray.com/org/lwjgl/lwjgl-openal/3.0.1-SNAPSHOT/maven-metadata.xml https://jcenter.bintray.com/org/lwjgl/lwjgl-openal/3.0.1-SNAPSHOT/lwjgl-openal-3.0.1-SNAPSHOT.pom https://jcenter.bintray.com/org/lwjgl/lwjgl-openal/3.0.1-SNAPSHOT/lwjgl-openal-3.0.1-SNAPSHOT.jar Required by: project : &gt; project :Engine &gt; Could not find org.lwjgl:lwjgl-opencl:3.0.1-SNAPSHOT. Searched in the following locations: https://jcenter.bintray.com/org/lwjgl/lwjgl-opencl/3.0.1-SNAPSHOT/maven-metadata.xml https://jcenter.bintray.com/org/lwjgl/lwjgl-opencl/3.0.1-SNAPSHOT/lwjgl-opencl-3.0.1-SNAPSHOT.pom https://jcenter.bintray.com/org/lwjgl/lwjgl-opencl/3.0.1-SNAPSHOT/lwjgl-opencl-3.0.1-SNAPSHOT.jar Required by: project : &gt; project :Engine &gt; Could not find org.lwjgl:lwjgl-opengl:3.0.1-SNAPSHOT. Searched in the following locations: https://jcenter.bintray.com/org/lwjgl/lwjgl-opengl/3.0.1-SNAPSHOT/maven-metadata.xml https://jcenter.bintray.com/org/lwjgl/lwjgl-opengl/3.0.1-SNAPSHOT/lwjgl-opengl-3.0.1-SNAPSHOT.pom https://jcenter.bintray.com/org/lwjgl/lwjgl-opengl/3.0.1-SNAPSHOT/lwjgl-opengl-3.0.1-SNAPSHOT.jar Required by: project : &gt; project :Engine &gt; Could not find org.lwjgl:lwjgl-opengles:3.0.1-SNAPSHOT. Searched in the following locations: https://jcenter.bintray.com/org/lwjgl/lwjgl-opengles/3.0.1-SNAPSHOT/maven-metadata.xml https://jcenter.bintray.com/org/lwjgl/lwjgl-opengles/3.0.1-SNAPSHOT/lwjgl-opengles-3.0.1-SNAPSHOT.pom https://jcenter.bintray.com/org/lwjgl/lwjgl-opengles/3.0.1-SNAPSHOT/lwjgl-opengles-3.0.1-SNAPSHOT.jar Required by: project : &gt; project :Engine &gt; Could not find org.lwjgl:lwjgl-stb:3.0.1-SNAPSHOT. Searched in the following locations: https://jcenter.bintray.com/org/lwjgl/lwjgl-stb/3.0.1-SNAPSHOT/maven-metadata.xml https://jcenter.bintray.com/org/lwjgl/lwjgl-stb/3.0.1-SNAPSHOT/lwjgl-stb-3.0.1-SNAPSHOT.pom https://jcenter.bintray.com/org/lwjgl/lwjgl-stb/3.0.1-SNAPSHOT/lwjgl-stb-3.0.1-SNAPSHOT.jar Required by: project : &gt; project :Engine &gt; Could not find org.lwjgl:lwjgl-vulkan:3.0.1-SNAPSHOT. Searched in the following locations: https://jcenter.bintray.com/org/lwjgl/lwjgl-vulkan/3.0.1-SNAPSHOT/maven-metadata.xml https://jcenter.bintray.com/org/lwjgl/lwjgl-vulkan/3.0.1-SNAPSHOT/lwjgl-vulkan-3.0.1-SNAPSHOT.pom https://jcenter.bintray.com/org/lwjgl/lwjgl-vulkan/3.0.1-SNAPSHOT/lwjgl-vulkan-3.0.1-SNAPSHOT.jar Required by: project : &gt; project :Engine * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. BUILD FAILED Total time: 9.375 secs </code></pre> <p>My file hirachy is quite simple:</p> <blockquote> <p>Project\Engine </p> <p>Project\Game</p> </blockquote> <p>My Game project should use the Engine project, so that I can easily change things in the Engine project without having to build a new .jar file for it and the Game project just works with it (like if you would for example add it as a dependency project in eclipse) and when compiling the Game project it should compile the Engine project to get the required jar for the Game project.</p> <p>Currently it works the way that the Game project has it's dependencies on the Engine project and this works quite nice in my IDE (well, atleast when the Engine project is importet), but as soon as I run the build it fails as the error shows above. It also fails in the IDE when I want to have access to a class which is a dependency in the Engine project, but not in the Game project where the complete Engine project is the dependency.</p> <p>The build.gradle file of the Game project.</p> <pre><code>// Apply the java plugin to add support for Java apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' // In this section you declare where to find the dependencies of your project repositories { // Use 'jcenter' for resolving your dependencies. // You can declare any Maven/Ivy/file repository here. jcenter() } // In this section you declare the dependencies for your production and test code dependencies { // The production code uses the SLF4J logging API at compile time //compile 'org.slf4j:slf4j-api:1.7.21' // Declare the dependency for your favourite test framework you want to use in your tests. // TestNG is also supported by the Gradle Test task. Just change the // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add // 'test.useTestNG()' to your build script. //testCompile 'junit:junit:4.12' compile project(':Engine') runtime project(':Engine') } </code></pre> <p>The settings.gradle file of the Game project:</p> <pre><code>include 'Engine' project (':Engine').projectDir = new File('../Engine') rootProject.name = 'Game' </code></pre> <p>Then I've got here the build.gradle file of the Engine project:</p> <pre><code>apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' sourceCompatibility = 1.8 targetCompatibility = 1.8 // In this section you declare where to find the dependencies of your project repositories { // Use 'jcenter' for resolving your dependencies. // You can declare any Maven/Ivy/file repository here. jcenter() maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } } task wrapper(type: Wrapper) { gradleVersion = '3.1' } sourceSets { main.java.srcDir "src/main/java" } project.ext.lwjglVersion = "3.0.1-SNAPSHOT" import org.gradle.internal.os.OperatingSystem switch ( OperatingSystem.current() ) { case OperatingSystem.WINDOWS: project.ext.lwjglNatives = "natives-windows" break case OperatingSystem.LINUX: project.ext.lwjglNatives = "natives-linux" break case OperatingSystem.MAC_OS: project.ext.lwjglNatives = "natives-macos" break } dependencies { // LWJGL dependencies START compile "org.lwjgl:lwjgl:${lwjglVersion}" compile "org.lwjgl:lwjgl-egl:${lwjglVersion}" compile "org.lwjgl:lwjgl-glfw:${lwjglVersion}" compile "org.lwjgl:lwjgl-jemalloc:${lwjglVersion}" compile "org.lwjgl:lwjgl-openal:${lwjglVersion}" compile "org.lwjgl:lwjgl-opencl:${lwjglVersion}" compile "org.lwjgl:lwjgl-opengl:${lwjglVersion}" compile "org.lwjgl:lwjgl-opengles:${lwjglVersion}" compile "org.lwjgl:lwjgl-stb:${lwjglVersion}" compile "org.lwjgl:lwjgl-vulkan:${lwjglVersion}" // LWJGL natives runtime "org.lwjgl:lwjgl:${lwjglVersion}:${lwjglNatives}" runtime "org.lwjgl:lwjgl-glfw:${lwjglVersion}:${lwjglNatives}" runtime "org.lwjgl:lwjgl-jemalloc:${lwjglVersion}:${lwjglNatives}" runtime "org.lwjgl:lwjgl-openal:${lwjglVersion}:${lwjglNatives}" runtime "org.lwjgl:lwjgl-stb:${lwjglVersion}:${lwjglNatives}" // LWJGL dependencies END } </code></pre> <p>So why am I getting this error and how can I solve it in a way that I can run and build is project on Linux, Windows and Mac with the IDEs Eclipse and Intellij? The error occurs only when running</p> <blockquote> <p>gradlew build</p> </blockquote> <p>inside the Game project. Building the engine project works just fine. It works also fine when I run the Game project inside of for example eclipse, but when I want to build it or want to use a class to which the Engine project has access in the Game project, it fails.</p>
<p>EDIT (Better answer)</p> <p>I would organize projects differently.</p> <p>Try to use this hierarchy : </p> <pre><code>Project/ | +- Game/ +- Engine/ +- build.gradle +- settings.gradle </code></pre> <p>In your settings.gradle</p> <pre><code>include ':Game' include ':Engine' </code></pre> <p>In your build.gradle of project root</p> <pre><code>// In this section you declare where to find the dependencies of your project repositories { // Use 'jcenter' for resolving your dependencies. // You can declare any Maven/Ivy/file repository here. jcenter() maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } } </code></pre> <p><code>repositories</code> node of your child projects are not needed anymore. </p> <p>settings.gradle of your game project is just</p> <pre><code>rootProject.name = 'Game' </code></pre>
Php floating if statement Confused <pre><code>function is_decimal( $it ) { return is_numeric( $it ) &amp;&amp; floor( $it ) != $it; } if (is_decimal == true){ echo "Decimal"; } </code></pre> <p>This gives me an error even though the int is not a decimal (float). Can someone help me. Thanks It works fine for a decimal but not for an int.</p>
<p>just use <code>if(is_numeric( $spaces )){ ... }</code> work for int, float even if they are represented by string</p>
Setting CircularImageView border color programmatically <p>I am using the <a href="https://github.com/lopspower/CircularImageView" rel="nofollow">CircularImageView</a> library. I have a <code>CircularImageView</code> in my <code>ViewHolder</code>, and I want to change its border color on click.</p> <p>My <code>onBindViewHolder</code>:</p> <pre><code>public void onBindViewHolder(ThumbnailAdapter.ViewHolder holder, int position) { ... //getting the relevant user from dataset and other irrelevant stuff if(selectedUsers.size() == 0 || selectedUsers.contains(user)) { holder.thumbnail.setBorderColor(R.color.selected); } else { holder.thumbnail.setBorderColor(R.color.not_selected); } holder.thumbnail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (selectedUsers.contains(user)) { selectedUsers.remove(user); } else { selectedUsers.add(user); } notifyDataSetChanged(); } }); } </code></pre> <p>The weird thing is that the first coloring works (the border color is indeed not the one predefined in the xml), but any further change does not affect the view (though the event is called and the value is changed). I tried to change also the drawable to eliminate a <code>RecyclerView</code>-related problem, and it works as expected.</p> <p>Am I doing anything wrong? Maybe there's a bug in the library (if so, I couldn't find it)? Any help will be appreciated!</p> <p><strong>EDIT:</strong> More adapter code:</p> <pre><code>public ThumbnailAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.thumbnail, parent, false); return new ThumbnailAdapter.ViewHolder(v); } static class ViewHolder extends RecyclerView.ViewHolder { CircularImageView thumbnail; ViewHolder(View v) { super(v); thumbnail = (CircularImageView) v.findViewById(R.id.user_thumbnail); } } private List&lt;User&gt; mDataSet; private List&lt;User&gt; selectedUsers; public ThumbnailAdapter(List&lt;User&gt; dataSet) { mDataSet = dataSet; selectedUsers = new ArrayList&lt;&gt;(); } </code></pre> <p>Setting the adapter:</p> <pre><code> mAdapter = new ThumbnailAdapter(users); mRecyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)); mRecyclerView.setAdapter(mAdapter); </code></pre>
<p>I got it working, try this:</p> <p><a href="https://i.stack.imgur.com/3cyfp.png" rel="nofollow"><img src="https://i.stack.imgur.com/3cyfp.png" alt="enter image description here"></a></p> <pre><code>public void onBindViewHolder(RecyclerView.ViewHolder mholder, int position) { final User user = mList.get(position); final ViewHolder holder = (ViewHolder) mholder; if(selectedUsers.size() == 0 || selectedUsers.contains(user)) { //holder.thumbnail.setBorderColor(Color.GREEN); setBorder(holder.thumbnail, true); } else { //holder.thumbnail.setBorderColor(Color.RED); setBorder(holder.thumbnail, false); } holder.thumbnail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (selectedUsers.contains(user)) { selectedUsers.remove(user); } else { selectedUsers.add(user); } //notifyItemChanged(position); notifyDataSetChanged(); } }); } @Override public int getItemCount() { return mList.size(); } public void setBorder(CircularImageView circularImageView, boolean selected) { // Set Border if(selected) { circularImageView.setBorderColor(context.getResources().getColor(R.color.colorPrimary)); circularImageView.setBorderWidth(50); circularImageView.setBackgroundColor(0xffffffff); } else { circularImageView.setBorderColor(context.getResources().getColor(R.color.colorAccent)); circularImageView.setBorderWidth(50); circularImageView.setBackgroundColor(0xffffffff); } // Add Shadow with default param //circularImageView.addShadow(); // or with custom param //circularImageView.setShadowRadius(1); //circularImageView.setShadowColor(Color.WHITE); } </code></pre> <p>Something else you should do for performance improvement: look inside your <code>View.OnClickListener()</code> switch the <code>notifyDataSetChanged()</code> which will force a complete full layout on the <code>LayoutManager</code> for the precision method <code>notifyItemChanged(position);</code> which will perform the task you want without redrawing everything</p> <p>Hope this helps! =)</p>
XPath query for list of UML class attributes that are not associations <p>I have a UML model developed with Rational Software Architect v9.1.2. I'm crafting a BIRT report with which I would like to show all of the class attributes that are NOT associations. I have the following XPath query:</p> <pre><code>resolveURI($classURI)/ownedAttribute[not(@association)] </code></pre> <p>This query returns all (2) of the attributes on the sample class <em>EmailAddress</em>, screen shot and xmi model fragment attached.</p> <p><a href="https://i.stack.imgur.com/yV3wt.png" rel="nofollow"><img src="https://i.stack.imgur.com/yV3wt.png" alt="Diagram Fragment"></a></p> <p><a href="https://i.stack.imgur.com/z7efz.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/z7efz.jpg" alt="Model XMI fragment"></a></p> <p>It seems that the association attribute is not recognized. This might be a namespace issue, but I'm not sure. Can anyone offer help?</p>
<p>First thing I'd try is changing the qualifier to check for nullness - e.g.</p> <p>resolveURI($classURI)/ownedAttribute[@association = null]</p> <p>Never know.. might work! :)</p> <p>cheers Steve</p>
How to decrypt a "sha512" encrypted variable? <p>I have this code: </p> <p><code>$password = vancab123;</code></p> <p><code>password_hash(base64_encode( hash('sha512',$password, true) ), PASSWORD_DEFAULT );</code></p> <p><strong>Database stored value:</strong></p> <p><code>$password = $2y$10$jUa8ZEFBX5lfsBmySUnJFeSSyKwQ1v/emazJZPh8MwJ0g0lLbmjYC;</code></p> <p><strong>My Problem:</strong></p> <p>I used that on "remember me" function. If the user used that function his/her credentials (email and password) will be saved for 7 days using cookie. </p> <p>My problem is because the email and password will automatically fill up the email and password text boxes, the password text box characters is too long because it was hashed. </p> <p>How can I match the length of the hashed password to the original/unhashed password?</p>
<p>And you dont need to jump through all those hoops to use <code>password_hash</code> and this is how to check that an entered password matches the previously hashed password</p> <blockquote> <p>The point of a HASH is it cannot (within a sensable time frame) be converted back to its original value. Instead you have to compare it using password_verify() to the unhashed value the user enters when they return and attempt to login using the same password.</p> </blockquote> <pre><code>$password = 'vancab123'; $hashed_pwd = password_hash($password); // test the hashed password if ( password_verify($password, $hashed_pwd) ) { //password entered is OK } else { //password entered is WRONG } </code></pre> <p>ADDITION after you clarified your question:</p> <blockquote> <p>Read this for a Remember me functionality <a href="http://stackoverflow.com/questions/244882/what-is-the-best-way-to-implement-remember-me-for-a-website">What is the best way to implement &quot;remember me&quot; for a website?</a></p> </blockquote>
Median of three, pivot <p>I'm looking for the <strong>median of three</strong>, using this for a pivot in a QuickSort. I would not like to import any statistics library because I believe it creates a bit of overhead which I would like to reduce as much as possible.</p> <pre><code>def median(num_list): if (num_list[0] &gt; num_list[len(num_list) - 1]) and (num_list[0] &lt; num_list[int(len(num_list)//2)]): return num_list[0] elif (num_list[int(len(num_list)//2)] &gt; num_list[len(num_list) - 1]) and (num_list[0] &gt; num_list[int(len(num_list)//2)]): return num_list[int(len(num_list)//2)] else: return num_list[len(num_list) - 1] </code></pre> <p>this seems to be returning the last else statement every time, I'm stumped...</p>
<p>Let Python do the work for you. Sort the three elements, then return the middle one.</p> <pre><code>def median(num_list): return sorted([num_list[0], num_list[len(num_list) // 2], num_list[-1]])[1] </code></pre>
Determine if peer has closed reading end of socket <p>I have a socket programming situation where the client shuts down the writing end of the socket to let the server know input is finished (via receiving EOF), but keeps the reading end open to read back a result (one line of text). It would be useful for the server to know that the client has successfully read the result and closed the socket (or at least shut down the reading end). Is there a good way to check/wait for such status?</p>
<p><code>getsockopt</code> with <code>TCP_INFO</code> seems the most obvious choice, but it's not cross-platform.</p> <p>Here's an example for Linux:</p> <pre><code>import socket import time import struct import pprint def tcp_info(s): rv = dict(zip(""" state ca_state retransmits probes backoff options snd_rcv_wscale rto ato snd_mss rcv_mss unacked sacked lost retrans fackets last_data_sent last_ack_sent last_data_recv last_ack_recv pmtu rcv_ssthresh rtt rttvar snd_ssthresh snd_cwnd advmss reordering rcv_rtt rcv_space total_retrans pacing_rate max_pacing_rate bytes_acked bytes_received segs_out segs_in notsent_bytes min_rtt data_segs_in data_segs_out""".split(), struct.unpack("BBBBBBBIIIIIIIIIIIIIIIIIIIIIIIILLLLIIIIII", s.getsockopt(socket.IPPROTO_TCP, socket.TCP_INFO, 160)))) wscale = rv.pop("snd_rcv_wscale") # bit field layout is up to compiler # FIXME test the order of nibbles rv["snd_wscale"] = wscale &gt;&gt; 4 rv["rcv_wscale"] = wscale &amp; 0xf return rv for i in range(100): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("localhost", 7878)) s.recv(10) pprint.pprint(tcp_info(s)) </code></pre> <p>I doubt a true cross-platform alternative exists.</p> <p>Fundamentally there are quite a few states:</p> <ul> <li>you wrote data to socket, but it was not sent yet</li> <li>data was sent, but not received</li> <li>data was sent and losts (relies on timer)</li> <li>data was received, but not acknowledged yet</li> <li>acknowledgement not received yet</li> <li>acknowledgement lost (relies on timer)</li> <li>data was received by remote host but not read out by application</li> <li>data was read out by application, but socket still alive</li> <li>data was read out, and app crashed</li> <li>data was read out, and app closed the socket</li> <li>data was read out, and app called <code>shutdown(WR)</code> (almost same as closed)</li> <li>FIN was not sent by remote yet</li> <li>FIN was sent by remote but not received yet</li> <li>FIN was sent and got lost</li> <li>FIN received by your end</li> </ul> <p>Obviously your OS can distinguish quite a few of these states, but not all of them. I can't think of an API that would be this verbose...</p> <p>Some systems allow you to query remaining send buffer space. Perhaps if you did, and socket was already shut down, you'd get a neat error?</p> <p>Good news is just because socket is shut down, doesn't mean you can't interrogate it. I can get all of <code>TCP_INFO</code> after shutdown, with <code>state=7</code> (closed). In some cases report <code>state=8</code> (close wait).</p> <p><a href="http://lxr.free-electrons.com/source/net/ipv4/tcp.c#L1961" rel="nofollow">http://lxr.free-electrons.com/source/net/ipv4/tcp.c#L1961</a> has all the gory details of Linux TCP state machine.</p>
Send notification when requesting data from api <p>I am trying to create an alert system for my app with a background service and notifications but I actually don't know where to start this thing.</p> <p>What I have already done: I have created an API which returns an integer. The user sets a goal in my app which will be stored as a variable of course.</p> <p>What I want to do: I want to create a background service which checks if the variable the user has set is the same as the integer the API returns, this should be checked every minute or so. Once they are equal, there should be a notification telling the user his 'alert' has been finished.</p> <p>Now, the thing is, I have never worked with background services yet and I can't seem to be able to find a good guide which helps me.</p> <p>Thanks,</p> <p>Bjarn</p>
<p>Get into RXJava, run a Service and combine it with a NotificationManager</p>
in c# for type safe tree implementation (typesafe node) <p>I am looking for /tring to implement a type safe tree implementation in C#.</p> <p>How can a type safe tree be implemented, without using interfaces (which force to reimplement the tree functionality all over the place) and without using casts?</p> <p>I have the idea of using tree as common base class, but then type safety is gone. My current approach is usage generics. But I am missing some conversion back to the base type.</p> <p>Below is a reduced/nonworking example. The idea is that the returned Nodes support the tree functions, and at the same time they also support their base types behaviour. I could use the below class without and inherit from Node, but then then I loose type safety on one hand, and also get problems with inheritance, as the Nodes have already parent classes.</p> <p>I also toyed with class extensions, but I haven't got anything that is close to a possible solution.</p> <p>I think i need one small hint on how to continue. Thank you in Advance.</p> <pre><code>public class Node&lt;T&gt; // . { public Node&lt;T&gt; parent; public List&lt;Node&lt;T&gt;&gt; children; protected Node() { children = new List&lt;Node&lt;T&gt;&gt;(); parent = null; } protected Node(Node&lt;T&gt; parent) : this() { this.parent = parent; parent.addChildren(this); } protected void addChildren(Node&lt;T&gt; child) { children.Add(child); } public Node&lt;T&gt; getRoot() // returns root node public List&lt;Node&lt;T&gt;&gt; flatten() // return 1d-list of all nodes. } </code></pre>
<blockquote> <p>I have the idea of using tree as common base class, but then type safety is gone. My current approach is usage generics. But I am missing some conversion back to the base type.</p> </blockquote> <p>Then constraint the generic type to your base type:</p> <pre><code>public class Node&lt;T&gt; where T: BaseType { ... } </code></pre> <p>Now you can create any tree of the type <code>Node&lt;MyDerivedType&gt;</code> as long as <code>MyDerivedType</code> derives from <code>BaseType</code>.</p> <p>On a side not, I'd consider modifying the following in your implementation:</p> <ol> <li><p><code>Children</code> should be a property, do not expose a field unless its readonly. Furthermore, you should not expose it as a <code>List</code>; that would let anyone add or remove nodes directly which can violate invariants assumed in your implementation. Return an <code>IEnumerable&lt;T&gt;</code> instead:</p> <pre><code>private readonly List&lt;T&gt; children; public IEnumerable&lt;T&gt; Children =&gt; children.Select(c =&gt; c); </code></pre> <p>You could return <code>children</code> directly as its implicitly convertible to <code>IEnumerable&lt;T&gt;</code>; the problem is that anyone can simply cast it back to <code>List&lt;T&gt;</code> and modify it. Projecting it protects you from this conversion.</p></li> <li><p>Same happens with <code>Flatten</code> (the first <em>f</em> should be capitalized btw). Consider returning an <code>IEnumerable&lt;T&gt;</code> too.</p></li> </ol>
How to use environment variables in ReactJS imported CSS? <p>I created a simple React app using <a href="https://github.com/facebookincubator/create-react-app" rel="nofollow">https://github.com/facebookincubator/create-react-app</a>.</p> <p>I am trying to specify a configurable URL to a component's CSS like this:</p> <pre><code>.Cell { background-image: url({process.env.REACT_APP_STATIC_URL}./someImage.png); } </code></pre> <p>And here's the component:</p> <pre><code>import React from 'react'; import './Cell.css' class Cell extends React.Component { render() { return ( &lt;div className="Cell"&gt; {this.props.name} &lt;/div&gt; ); } } </code></pre> <p>But it doesn't look like the process variable trickles down to the imported CSS. How would I go about doing this?</p>
<p>If you want to use js variables in CSS, try React inline-style instead of plain css file.</p> <p><a href="https://facebook.github.io/react/tips/inline-styles.html" rel="nofollow">https://facebook.github.io/react/tips/inline-styles.html</a></p> <p>If you want to separate CSS and JS, you might need a CSS preprocessor to manage your global variables.</p>
Why does my app crash with a NullPointerException, and why is my adapter (probably) null? <p>When my app tries to get the position on the adapter, it crashes, because apparently my adapter isn't getting populated correctly.</p> <p>The data is coming in fine through Retrofit, and my custom adapter (<code>NewsAdapter</code>, based on ArrayAdapter) was getting populated before, but I had to make some adjustments to it and I can't get it working at all now.</p> <p>The idea is to get each news source available, get the articles for each specific news source, and then populate my GridView with those articles. Here is my code:</p> <p><code>NewsAdapter</code>:</p> <pre><code>public class NewsAdapter extends ArrayAdapter&lt;Articles_Map&gt; { Context mContext; ArrayList&lt;Articles_Map&gt; articles; public NewsAdapter(Context c, int resource) { super(c, resource); this.mContext = c; } public NewsAdapter(Context c, int resource, ArrayList&lt;Articles_Map&gt; articles) { super(c, resource, articles); this.mContext = c; this.articles = articles; } @Override public View getView(int position, View convertView, ViewGroup parent) { // get the property we are displaying Articles_Map article = articles.get(position); // get the inflater and inflate the XML layout for each item LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.article_layout, null); ImageView thumbnail = (ImageView) view.findViewById(R.id.thumbnail); TextView title = (TextView) view.findViewById(R.id.title); TextView description = (TextView) view.findViewById(R.id.description); Picasso.with(mContext).load(article.urlToImage).into(thumbnail); title.setText(article.title); description.setText(article.description); return view; } } </code></pre> <p><code>NewsAPI_Map</code>:</p> <pre><code>public class NewsAPI_Map { String status; String source; ArrayList&lt;Articles_Map&gt; articles; public NewsAPI_Map(String status, String source, ArrayList&lt;Articles_Map&gt; articles) { this.status = status; this.source = source; this.articles = articles; } } </code></pre> <p><code>Articles_Map</code>:</p> <pre><code>public class Articles_Map { String title; String description; String url; String urlToImage; public Articles_Map(String title, String description, String url, String urlToImage) { this.title = title; this.description = description; this.url = url; this.urlToImage = urlToImage; } } </code></pre> <p><code>ListNewsActivity.java</code>:</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { /* ... */ // parameters for Sources endpoint String category = "sport"; String language = "en"; String country = "us"; // Sources endpoint Sources_Interface client_sources = NewsAPI_Adapter.createService(Sources_Interface.class); Call&lt;Sources_Map&gt; call_sources = client_sources.getData(category, language, country); call_sources.enqueue(new Callback&lt;Sources_Map&gt;() { @Override public void onResponse(Call&lt;Sources_Map&gt; call_sources, Response&lt;Sources_Map&gt; response) { if (response.body() != null) { final NewsAdapter nAdapter = new NewsAdapter(ListNewsActivity.this, R.layout.article_layout); for (Sources_Content source : response.body().sources) { if (source.sortBysAvailable.contains("latest")) { // Articles endpoint NewsAPI_Interface client = NewsAPI_Adapter.createService(NewsAPI_Interface.class); Call&lt;NewsAPI_Map&gt; call = client.getData(source.id, "apiKeyHere"); call.enqueue(new Callback&lt;NewsAPI_Map&gt;() { @Override public void onResponse(Call&lt;NewsAPI_Map&gt; call, Response&lt;NewsAPI_Map&gt; response) { if (response.body() != null) { ExpandableHeightGridView gv_content = (ExpandableHeightGridView) findViewById(R.id.gv_content); nAdapter.addAll(response.body().articles); System.out.println("Count: " + nAdapter.getCount() + "\n" + "Body: " + response.body().articles + "\n"); gv_content.setAdapter(nAdapter); gv_content.setExpanded(true); } } @Override public void onFailure(Call&lt;NewsAPI_Map&gt; call, Throwable t) { System.out.println("An error ocurred!\n" + "URL: " + call.request().url() + "\n" + "Cause: " + t.getCause().toString()); } }); } } } } @Override public void onFailure(Call&lt;Sources_Map&gt; call_sources, Throwable t) { System.out.println("An error ocurred!"); } }); } </code></pre> <p>Logs:</p> <pre><code>E/AndroidRuntime: FATAL EXCEPTION: main Process: pt.ismai.a26800.readr, PID: 8398 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference at pt.ismai.a26800.readr.NewsAdapter.getView(NewsAdapter.java:38) at android.widget.AbsListView.obtainView(AbsListView.java:2346) at android.widget.GridView.onMeasure(GridView.java:1065) at pt.ismai.a26800.readr.ExpandableHeightGridView.onMeasure(ExpandableHeightGridView.java:37) at android.view.View.measure(View.java:18804) at android.support.v4.widget.NestedScrollView.measureChildWithMargins(NestedScrollView.java:1411) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at android.support.v4.widget.NestedScrollView.onMeasure(NestedScrollView.java:479) at android.view.View.measure(View.java:18804) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954) at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:700) at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90) at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1364) at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:765) at android.view.View.measure(View.java:18804) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135) at android.view.View.measure(View.java:18804) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465) at android.widget.LinearLayout.measureVertical(LinearLayout.java:748) at android.widget.LinearLayout.onMeasure(LinearLayout.java:630) at android.view.View.measure(View.java:18804) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at android.view.View.measure(View.java:18804) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465) at android.widget.LinearLayout.measureVertical(LinearLayout.java:748) at android.widget.LinearLayout.onMeasure(LinearLayout.java:630) at android.view.View.measure(View.java:18804) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643) at android.view.View.measure(View.java:18804) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2112) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1228) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1464) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1119) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6060) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858) at android.view.Choreographer.doCallbacks(Choreographer.java:670) at android.view.Choreographer.doFrame(Choreographer.java:606) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844) at android.os.Handler.handleCallback(Handler.java:746) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5443) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) </code></pre>
<p>You are basically using the first constructor which means you need to pass your <code>ArrayList&lt;Articles_Map&gt;</code>. Using your first constructor makes your Array uninitialized and that's causing your the <code>Nullpointer Exception</code>. </p> <pre><code>final NewsAdapter nAdapter = new NewsAdapter(ListNewsActivity.this, R.layout.article_layout); </code></pre> <p>While your requirements is the second one.</p> <pre><code>public NewsAdapter(Context c, int resource, ArrayList&lt;Articles_Map&gt; articles) { super(c, resource, articles); this.mContext = c; this.articles = articles; } </code></pre> <p>You need to use the other overloaded constructor by supplying the <code>ArrayList&lt;Articles_Map&gt;</code> instance e.g.</p> <pre><code>final NewsAdapter nAdapter = new NewsAdapter(ListNewsActivity.this, R.layout.article_layout, articles); </code></pre> <p>Update Code</p> <pre><code>public class NewsAdapter extends ArrayAdapter&lt;Articles_Map&gt; { Context mContext; ArrayList&lt;Articles_Map&gt; articles; public NewsAdapter(Context c, int resource) { super(c, resource); this.mContext = c; this.articles = new ArrayList&lt;&gt;(); } public void add(Articles_Map m){ articles.add(m); notifyDataSetChanged(); } ... more code ... } </code></pre> <p>I added the code <code>add(Articles_Map m)</code> so that you can use it in your callback, in this case you do not need to reinitialize your Adapter.</p>
Can't pass random variable to tf.image.central_crop() in Tensorflow <p>In Tensorflow I am training from a set of PNG files and I wish to apply data augmentation. I have successfully used <code>tf.image.random_flip_left_right()</code></p> <p>But I get an error when I try to use <code>tf.image.central_crop()</code>. basically I would like the central_fraction to be drawn from a uniform distribution (0.8,1.0].</p> <p>Here is my code. Where did I go wrong? Should <code>frac</code> be a <code>tf.random_uniform()</code>?</p> <pre><code>filename_queue = tf.train.string_input_producer( tf.train.match_filenames_once("./images/*.png")) image_reader = tf.WholeFileReader() # Read an entire image file _, image_file = image_reader.read(filename_queue) image = tf.image.decode_png(image_file, channels=3, dtype=tf.uint8, name="PNGDecompressor") image.set_shape([800,400,3]) frac = random.uniform(0.8,1.0) image = tf.image.central_crop(image, central_fraction = frac) # THIS FAILS # image = tf.image.central_crop(image, central_fraction = 0.8) # THIS WORKS image = tf.image.resize_images(image, [256, 128]) image.set_shape([256,128,3]) image = tf.cast(image, tf.float32) * (1. / 255) - 0.5 # Convert from [0, 255] -&gt; [-0.5, 0.5] floats. image = tf.image.per_image_whitening(image) image = tf.image.random_flip_left_right(image, seed=42) # Start a new session to show example output. with tf.Session() as sess: tf.initialize_all_variables().run() coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) t_image= sess.run([image]) [...] coord.request_stop() coord.join(threads) </code></pre> <p>Fails with error:</p> <pre><code>TypeError: Fetch argument 0.9832154064713503 has invalid type &lt;class 'float'&gt;, must be a string or Tensor. (Can not convert a float into a Tensor or Operation.) </code></pre>
<p>I solved my own problem defining the following function. I adjusted the code provided in tf.image.central_crop(image, central_fraction). The function RandomCrop will crop an image taking a central_fraction drawn from a uniform distribution. You can just specify the min and max fraction you want. You can replace random_uniform distribution to a different one obviously.</p> <pre><code>def RandomCrop(image,fMin, fMax): from tensorflow.python.ops import math_ops from tensorflow.python.ops import array_ops from tensorflow.python.framework import ops image = ops.convert_to_tensor(image, name='image') if fMin &lt;= 0.0 or fMin &gt; 1.0: raise ValueError('fMin must be within (0, 1]') if fMax &lt;= 0.0 or fMax &gt; 1.0: raise ValueError('fMin must be within (0, 1]') img_shape = array_ops.shape(image) depth = image.get_shape()[2] my_frac2 = tf.random_uniform([1], minval=fMin, maxval=fMax, dtype=tf.float32, seed=42, name="uniform_dist") fraction_offset = tf.cast(math_ops.div(1.0 , math_ops.div(math_ops.sub(1.0,my_frac2[0]), 2.0)),tf.int32) bbox_h_start = math_ops.div(img_shape[0], fraction_offset) bbox_w_start = math_ops.div(img_shape[1], fraction_offset) bbox_h_size = img_shape[0] - bbox_h_start * 2 bbox_w_size = img_shape[1] - bbox_w_start * 2 bbox_begin = array_ops.pack([bbox_h_start, bbox_w_start, 0]) bbox_size = array_ops.pack([bbox_h_size, bbox_w_size, -1]) image = array_ops.slice(image, bbox_begin, bbox_size) # The first two dimensions are dynamic and unknown. image.set_shape([None, None, depth]) return(image) </code></pre>
NodeJS Mongoose Passport local strategy query Mongodb gives error, <p>I have a Passport local strategy try to query a user in mongodb: </p> <pre><code>passport.use(new LocalStrategy( function(username, password, done){ console.log("username and password is &gt;&gt;&gt;&gt;&gt;", username, password); var findOne = Q.nbind(User.findOne, User); findOne({"username": username}) .then(function(user){ console.log("inside findone user&gt;&gt;&gt;&gt;&gt;", err, user); if (!user) { return done( null, false, {messge: 'This user is not registered.'}); } if (!user.comparePasswords(password)){ return done(null, false, {message: 'This password is not correct'}); } return done(null, user); }) .fail(function(err){ console.log("failed at here"); return done(null, false, {message: "Server have difficulty"}); }) } )); </code></pre> <p>"failed at here" is printed, which means there's error accessing mongodb. However, I write the very similar function in my signup function, and every thing works fine: </p> <pre><code>exports.signup = function(req, res, next){ console.log("hit the signup function"); var findOne = Q.nbind(User.findOne, User); findOne({username: req.body.username}) .then(function(user){ console.log("user from query is &gt;&gt;&gt;&gt;&gt;", user); if (!user){ // user doesn't exist, create a new one\ var create = Q.nbind(User.create, User); var newUser = {username: req.body.username, password: req.body.password}; return create(newUser); } else { // user already exist, redirect to sign in page res.send(409, 'already exist'); //res.redirect('/signin'); } }) .then(function(user){ res.json(200,user); }) .fail(function(err){ //next(err); console.log("error is &gt;&gt;&gt;&gt;", err); res.redirect('/signin'); }) }; </code></pre> <p>I have created a user through signup. so it will give me 409 when i try to sign up with the same user. However, when I try to sign in with that user, the passport local strategy reports error accessing mongodb. Any thoughts? You are welcome to take a look at the repo: <a href="https://github.com/7seven7lst/chatterApp" rel="nofollow">https://github.com/7seven7lst/chatterApp</a> The passport config can be found in: <a href="https://github.com/7seven7lst/chatterApp/blob/master/lib/routes.js" rel="nofollow">https://github.com/7seven7lst/chatterApp/blob/master/lib/routes.js</a> and the signup can be found in: <a href="https://github.com/7seven7lst/chatterApp/blob/master/lib/controllers/user.js" rel="nofollow">https://github.com/7seven7lst/chatterApp/blob/master/lib/controllers/user.js</a></p>
<pre><code>.then(function(user){ console.log("inside findone user&gt;&gt;&gt;&gt;&gt;", err, user); </code></pre> <p>The error is being thrown because that <code>err</code> isn't defined.</p> <p>If you log the actual error that the <code>fail</code> function:</p> <pre><code>.fail(function(err){ console.log("failed at here", err); return done(null, false, {message: "Server have difficulty"}); }) </code></pre> <p>you will see:</p> <pre><code>ReferenceError: err is not defined at /Users/dting/chatterApp/lib/routes.js:16:49 </code></pre>
Packing a Form as a reusable Control like FolderBrowser <p>I have created a form that emulates a <code>FolderBrowseDialog</code>, but with some added features I wanted. It's tested and working, so now I want to make it into a control. My problem is that as soon as I inherit from <code>UserControl</code> instead of <code>Form</code>, I no longer have a <code>Close()</code> method, and I no longer have a <code>FormClosing</code> event. When I click on the OK or Cancel button, how do I close the form and return control to the calling object?</p>
<p>To make it a reusable component, instead of trying to derive it from <code>Control</code>, create a <a href="https://msdn.microsoft.com/en-us/library/system.componentmodel.component.aspx" rel="nofollow"><code>Component</code></a> which uses that form. This way it can show in toolbox and you can drop an instance of your component on design surface like other components. </p> <p>Your component should contain some properties which you want to expose from the dialog, also contain a <code>ShowDialog</code> method which created your form using some properties (like title, initial directory) and the shows your custom form as dialog and sets some properties (like selected folder) and returns the dialog result. For example:</p> <pre><code>using System.ComponentModel; using System.Windows.Forms; public partial class MyFolderBrowser : Component { public string Text { get; set; } public string SelectcedFolder { get; set; } public DialogResult ShowDialog() { using (var f = new YourCustomForm() { Text = this.Text }) { var result = f.ShowDialog(); if (result == DialogResult.OK) SelectcedFolder = f.SelectedFolder; return result; } } } </code></pre>
iOS Button Vector Image doesn't automatically adjust to screen size <p>I am currently trying to introduce myself to Xcode, IB and Vector images. I am struggling with the auto layout and having the buttons adjust to screen size. </p> <p>As you can see the buttons are same size in the iPhone 6s and iPad Pro.</p> <p><img src="http://i.imgur.com/bX0WHx5.png" alt="iPhone 6s"></p> <p>And here is the iPad Pro 12.9" size of the buttons:</p> <p><img src="http://i.imgur.com/NkSwwbb.png" alt="iPad Pro"></p> <p>The vector images I use are universal .pdf images at the size of 50x41. And here are the settings to those:</p> <p><img src="http://i.imgur.com/QxW2Dsu.png" alt="settings"></p> <p>How do I get these images to adjust properly from screen size to screen size?</p> <p>Thanks a lot for your help!</p>
<p>What constraints do you have to change the size of the imageView? I would expect to see a constraint between the top two images (and the bottom two) that forces a constant gap.</p> <p>The constraints on each image's width should then have a lower priority so they get stretched on a bigger screen. Then you want to constrain the height of each image to its width so they stay 1:1 (I'm guessing), and therefore stretch vertically if they are stretched horizontally.</p>
How to read .data file into R <p>I have tried to load the data from <a href="http://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/hungarian.data" rel="nofollow">http://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/hungarian.data</a> into R using the following piece of code</p> <pre><code>hData &lt;- read.table(file.choose(), sep = "\t", dec = ",", fileEncoding = "UTF-16") </code></pre> <p>but its not populating the exact data. The data has 76 attributes in it and the details about it are given here: <a href="http://archive.ics.uci.edu/ml/datasets/Heart+Disease" rel="nofollow">http://archive.ics.uci.edu/ml/datasets/Heart+Disease</a>.</p> <p>Can someone tell me what am I doing incorrect?</p>
<p>The file contains extra line breaks that are causing issues. If you chop them out with regex, you can read it in:</p> <pre><code># read file into a single string x &lt;- readr::read_file('http://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/hungarian.data') # or in base, x &lt;- paste(readLines(url('http://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/hungarian.data')), collapse = '\n') # gsub out line breaks that follow numbers (not "name") and read data df &lt;- read.table(text = gsub('(\\d)\\n', '\\1 ', x)) head(df, 2) ## V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22 V23 V24 V25 ## 1 1254 0 40 1 1 0 0 -9 2 140 0 289 -9 -9 -9 0 -9 -9 0 12 16 84 0 0 0 ## 2 1255 0 49 0 1 0 0 -9 3 160 1 180 -9 -9 -9 0 -9 -9 0 11 16 84 0 0 0 ## V26 V27 V28 V29 V30 V31 V32 V33 V34 V35 V36 V37 V38 V39 V40 V41 V42 V43 V44 V45 V46 V47 V48 ## 1 0 0 150 18 -9 7 172 86 200 110 140 86 0 0 0 -9 26 20 -9 -9 -9 -9 -9 ## 2 0 0 -9 10 9 7 156 100 220 106 160 90 0 0 1 2 14 13 -9 -9 -9 -9 -9 ## V49 V50 V51 V52 V53 V54 V55 V56 V57 V58 V59 V60 V61 V62 V63 V64 V65 V66 V67 V68 V69 V70 V71 ## 1 -9 -9 -9 -9 -9 -9 12 20 84 0 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 1 1 1 ## 2 -9 -9 -9 -9 -9 -9 11 20 84 1 -9 -9 2 -9 -9 -9 -9 -9 -9 -9 1 1 1 ## V72 V73 V74 V75 V76 ## 1 1 1 -9 -9 name ## 2 1 1 -9 -9 name </code></pre> <p>If there doesn't happen to be a conveniently different data type at the end, you can use <code>scan</code> to make a vector, then <code>split</code> and reassemble:</p> <pre><code># download data and split into a character vector x &lt;- scan(url('http://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/hungarian.data'), character()) # split and assemble data.frame df &lt;- data.frame(split(x, 1:76), stringsAsFactors = FALSE) # fix types df[] &lt;- lapply(df, type.convert, as.is = TRUE) </code></pre> <p>or pass <code>scan</code> a model of the types of what a single row should be to read directly into a list:</p> <pre><code>x &lt;- scan(url('http://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/hungarian.data'), c(replicate(75, numeric()), list(character()))) df &lt;- as.data.frame(x) names(df) &lt;- paste0('V', 1:76) # replace ugly names </code></pre> <p>If getting the type structure correct is too complicated, read everything in as character with <code>replicate(76, character())</code> and use <code>type.convert</code> like the previous option.</p> <p>Alternately, use <code>readLines</code>, <code>split</code> to create a list with the correct strings for each row grouped, and <code>paste</code> it all back together to use <code>read.table</code>:</p> <pre><code>x &lt;- readLines(url('http://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/hungarian.data')) df &lt;- read.table(text = paste(sapply(split(x, rep(seq(length(x) / 10), each = 10)), paste, collapse = ' '), collapse = '\n')) </code></pre>
How to programmaticaly trigger refresh primeNG datatable when a button is clicked <p>I have a refresh button that is outside the primeNG datatable. How do I programmaticaly trigger to refresh the datatable?</p> <p>something like this:</p> <pre><code>&lt;div class="pull-right"&gt; &lt;button id="FilterBtnId" (click)="???"&gt; &lt;/button&gt; &lt;/div&gt; &lt;p-dataTable #datatable [value]="datasource" [(selection)]="jobs" [totalRecords]="totalRecords" selectionMode="multiple" resizableColumns="true" [pageLinks]="10" [rows]="10" [rowsPerPageOptions]="[10, 25, 50, 100]" [paginator]="true" [responsive]="true" [lazy]="true" (onLazyLoad)="getNewDatasource($event)" (onRowSelect)="onRowSelect($event)" &gt; &lt;p-column [style]="{'width':'40px'}" selectionMode="multiple"&gt;&lt;/p-column&gt; &lt;p-column *ngFor="let col of dt.colDefs" [field]="col.field" [header]="col.headerName" [sortable]="true"&gt; &lt;/p-column&gt; &lt;/p-dataTable&gt; </code></pre>
<p>The <a href="https://angular.io/docs/ts/latest/guide/forms.html#!#add-a-hero-and-reset-the-form" rel="nofollow">Angular form guide</a> contains a small trick that could be used as a <em>workaround</em>, it consists on recreating the dom by adding <code>*ngIf</code> to the element to control its visibility</p> <pre><code>visible: boolean = true; updateVisibility(): void { this.visible = false; setTimeout(() =&gt; this.visible = true, 0); } &lt;button (click)="updateVisibility()"&gt; &lt;p-dataTable *ngIf="visible"&gt; </code></pre>
Microsoft.ACE.OLEDB16.0 provider not registered on local machine <p>I'm working on an app using Visual Studio 2013 and Access 2016 and I believe I have everything connected correctly, but when I try to debug the program every time the database is supposed to be used the title message pops up. I have downloaded a lot of different patches, even though I have Access downloaded on my machine. I have also toyed around with using 12.0 and 15.0 in my connection string and none of them have worked. Does anyone have any idea of something to download to show that I have it downloaded? I'll also add my data base control class incase there is a problem with how I wrote it.</p> <pre><code>Imports System.Data.OleDb Public Class DBControl Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB12.0;Data Source=StableMe.accdb;") Private DBCmd As OleDbCommand Public DBDA As OleDbDataAdapter Public DBDT As DataTable Public params As New List(Of OleDbParameter) Public recordCt As Integer Public exception As String Public Sub ExecQuery(query As String) recordCt = 0 exception = "" Try DBCon.Open() DBCmd = New OleDbCommand(query, DBCon) For Each p As OleDbParameter In params DBCmd.Parameters.Add(p) Next params.Clear() DBDT = New DataTable DBDA = New OleDbDataAdapter(DBCmd) recordCt = DBDA.Fill(DBDT) Catch ex As Exception exception = ex.Message End Try If DBCon.State = ConnectionState.Open Then DBCon.Close() End If End Sub Public Sub AddParams(name As String, value As Object) Dim newParam As New OleDbParameter(name, value) params.Add(newParam) End Sub </code></pre> <p>End Class</p>
<p>In the connection string</p> <pre class="lang-none prettyprint-override"><code>Provider=Microsoft.ACE.OLEDB12.0 </code></pre> <p>is not a valid provider name because it is missing a period. It should be</p> <pre class="lang-none prettyprint-override"><code>Provider=Microsoft.ACE.OLEDB.12.0 </code></pre>
File Access in python <p>Whenever I go to load a text file for my program it displays the info in the text file yet when I input the roster function it does not display the text file and show it is available to be modified. Is it something with how I created the text file in the first place or is my coding for <code>loadData</code> not written correctly i think i may be confused on the difference between just setting up a function just to read back the file instead of actually opening the text file to be able to modify it.</p> <pre><code>dict_member = {} players = dict_member class Players: def __init__(self, name, number, jersey): self.name = name self.number = number self.jersey = jersey def display(self): print('Printing current members\n') for number, player in dict_member.items(): print(player.name + ', ' + player.number + ', ' + player.jersey) def add(self): nam = input("Enter Player Name\n ") numb = input("Enter Player Number\n ") jers = input("Enter Jersey Number\n ") dict_member[nam] = Players(nam, numb, jers) def remove(self, name): if name in dict_member: del dict_member[name] def edit(self, name): if name in dict_member: nam = input("Enter Different Name\n") num = input("Enter New Number\n ") jers = input("Enter New Jersey Number\n ") del dict_member[name] dict_member[name] = Players(nam, num, jers) else: print("No such player exists") def saveData(self): roster = input("Filename to save: ") print("Saving data...") with open(roster, "r+") as rstr: for number, player in dict_member.items(): rstr.write(player.name + ', ' + player.number + ', ' + player.jersey) print("Data saved.") rstr.close() def loadData(self): dict_member = {} roster = input("Filename to load: ") file = open(roster, "r") while True: inLine = file.readline() if not inLine: 'break' inLine = inLine[:-1] name, number, jersey = inLine.split(",") dict_member[name] = (name, number, jersey) print("Data Loaded Successfully.") file.close() return dict_member def display_menu(): print("") print("1. Roster ") print("2. Add") print("3. Remove ") print("4. Edit ") print("5. Save") print("6. Load") print("9. Exit ") print("") return int(input("Selection&gt; ")) print("Welcome to the Team Manager") player_instance = Players(None, None, None) menu_item = display_menu() while menu_item != 9: if menu_item == 1: player_instance.display() elif menu_item == 2: player_instance.add() elif menu_item == 3: m = input("Enter Player to Remove\n") player_instance.remove(m) elif menu_item == 4: m = input("Enter Player to Edit\n") player_instance.edit(m) elif menu_item == 5: player_instance.saveData() elif menu_item == 6: player_instance.loadData() menu_item = display_menu() print("Exiting Program...") </code></pre>
<p>you didnt load your data into <code>dict_member</code> before displaying the roster </p> <p>when you load your data in the loadData function you redefine <code>dict_member</code> so it will "shadow" the outer <code>dict_member</code> so when the <code>display</code> function is called <code>dict_member</code> will always be empty</p> <p>so you probably want to remove this line </p> <pre><code>def loadData(self): # **remove this line ---&gt;** dict_member = {} roster = input("Filename to load: ") file = open(roster, "r") while True: inLine = file.readline() if not inLine: break inLine = inLine[:-1] name, number, jersey = inLine.split(",") dict_member[name] = (name, number, jersey) print("Data Loaded Successfully.") file.close() return dict_member </code></pre>
Luhn's Algorithm Pseudocode to code <p>Hey guys I'm fairly new to the programming world. For a school practice question I was given the following text and I'm suppose to convert this into code. I've spent hours on it and still can't seem to figure it out but I'm determine to learn this. I'm currently getting the error</p> <pre><code> line 7, in &lt;module&gt; if i % 2 == 0: TypeError: not all arguments converted during string formatting </code></pre> <p>What does this mean? I'm still learning loops and I'm not sure if it's in the correct format or not. Thanks for your time. </p> <pre><code># GET user's credit card number # SET total to 0 # LOOP backwards from the last digit to the first one at a time # IF the position of the current digit is even THEN # DOUBLE the value of the current digit # IF the doubled value is more than 9 THEN # SUM the digits of the doubled value # ENDIF # SUM the calculated value and the total # ELSE # SUM the current digit and the total # ENDIF # END loop # IF total % 10 == 0 THEN # SHOW Number is valid # ELSE # SHOW number is invalid # ENDIF creditCard = input("What is your creditcard?") total = 0 for i in creditCard[-1]: if i % 2 == 0: i = i * 2 if i &gt; 9: i += i total = total + i else: total = total + i if total % 10 == 0: print("Valid") else: print("Invalid") </code></pre>
<p>well, i can see 2 problems:</p> <p>1)when you do:</p> <pre><code>for i in creditCard[-1] </code></pre> <p>you dont iterate on the creditCard you simply take the last digit. you probably meant to do </p> <pre><code>for i in creditCard[::-1] </code></pre> <p>this will iterate the digits from the last one to the first one</p> <p>2) the pseudocode said to double the number if its POSITION is even, not if the digit itself is even</p> <p>so you can do this:</p> <pre><code>digit_count = len(creditCard) for i in range(digit_count -1, -1, -1): digit = creditCard[i] </code></pre> <p>or have a look at the <code>enumerate</code> built-in function</p> <p>edit:</p> <p>complete sample:</p> <pre><code>creditCard = input("What is your creditcard?") total = 0 digit_count = len(creditCard) for i in range(0, digit_count, -1): digit = creditCard[i] if i % 2 == 0: digit = digit * 2 if digit &gt; 9: digit = digit / 10 + digit % 10 # also noticed you didnt sum the digits of the number total = total + digit if total % 10 == 0: print("Valid") else: print("Invalid") </code></pre>
Pig Latin String Encryption <p>I am writing a program that takes a string, splits it into words, converts the words into pig latin, and then returns the result string. I have it working to a certain point.</p> <p>For example if I enter these words that do not start with a vowel into the program I get:<br/><br/> pig -> igpay <br/> trash -> rashtay<br/> duck -> uckday<br/><br/> (for words that do not start with vowels, they have their first letter removed, added to the end of the word along with "ay")<br/><br/></p> <p>It also works when the word starts with a vowel (just take the word and add "yay" to the end).<br/></p> <p>For example if I enter these words into the program I get:<br/><br/> eat -> eatyay <br/> areyay -> areyay<br/> omelet -> omeletyay<br/><br/></p> <p>Now the issue I am having is if I combine 2 words, one that starts with a vowel and one that doesn't, it prints out both like they both start with vowels.<br/></p> <p>For example if I enter these words into the program I get:<br/><br/> pig -> pigyay (should be igpay)<br/> eat -> eatyay (correct)<br/><br/></p> <p>It might be worth mentioning that the methods "isVowel" &amp; "pigLatinEncrypt" are required to have in this program. Please disregard the other methods that are in the program.</p> <pre><code>public static void main(String[] args) { // TODO code application logic here String input, message; int ans1, ans2, key; input = JOptionPane.showInputDialog("1. to decrypt a message\n2. to encrypt a message"); ans1 = Integer.parseInt(input); input = JOptionPane.showInputDialog("1. for an entire message reversal encryption\n" + "2. for a Pig-Latin encryption\n3. for a simple Caesar style encryption"); ans2 = Integer.parseInt(input); if (ans2 == 3) { input = JOptionPane.showInputDialog("Please enter a key for encryption"); key = Integer.parseInt(input); } input = JOptionPane.showInputDialog("Please enter the message to encrypt or decrypt"); message = input; if (ans2 == 1) { reverseEncryptandDecrypt(message); } if (ans2 == 2) { String[] words = message.split(" "); if (ans1 == 2) { boolean isVowel = isVowel(words); pigLatinEncrypt(words, isVowel); } if (ans1 == 1) { pigLatinDecrypt(message); } } } public static void reverseEncryptandDecrypt(String message) { char[] stringToCharArray = message.toCharArray(); System.out.print("You entered the message: "); for (char c : stringToCharArray) { System.out.print(c); } int i = stringToCharArray.length - 1, j = 0; char[] reverse = new char[stringToCharArray.length]; while (i &gt;= 0) { reverse[j] = stringToCharArray[i]; i--; j++; } System.out.print("\n\nThe result is: "); for (char c : reverse) { System.out.print(c); } System.out.println(); } public static void pigLatinEncrypt(String[] words, boolean isVowel) { for (String word : words) { if (isVowel == true) { System.out.print(word + "yay "); } else { System.out.print(word.substring(1) + word.substring(0, 1) + "ay "); } } } public static boolean isVowel(String[] words) { boolean isVowel = false; for (String word : words) { if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o") || word.startsWith("u")) { isVowel = true; } } return isVowel; } </code></pre> <p>}</p>
<p>This method:</p> <pre><code>public static void pigLatinEncrypt(String[] words, boolean isVowel) </code></pre> <p>takes an array of words and a <em>single</em> <code>isVowel</code> boolean. Thus, if there is more than one word, and some, but not all, of them begin with vowels, there's no way to tell the method that. </p> <p>You'll need to change the method definition. Either it should take only one word <code>String</code> (simplest), or it needs to take an array of <code>isVowel</code> booleans that correspond to the array of word</p> <p><strong>Edit:</strong> When I wrote this, I didn't look carefully at the rest of your code. But the <code>isVowel</code> method has the same problem: it takes an array of words, but returns a <em>single</em> boolean. This can't work, for the same reason--if some of the words start with vowels and some don't, what would the method return?</p> <p>If you can make the <code>isVowel</code> method take a single <code>String</code> argument, that would be simplest. Then you'd call it multiple times. If you want to make <code>isVowel</code> return a <code>boolean[]</code>, the method would do something like</p> <pre><code>boolean[] result = new boolean[words.length]; </code></pre> <p>to create an array of <code>boolean</code> that has the same number of elements as <code>words</code>.</p>
Doctrine not saving a one to one referenced field <p>I have a RequestForEstimate entity that at some point in my logic gets to the point where I create a PurchaseOrder and I need to insert a RequestId in the PurchaseOrder table. I have it reference by using the One to One association in doctrine. For some reason the DB call is successful however when I check the table it looks like the request_estimate_id field is null. Here is my logic:</p> <p>RequestForEstimate entity:</p> <pre><code>&lt;?php namespace InboundBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * RequestForEstimate * * @ORM\Table(name="request_for_estimate") * @ORM\Entity(repositoryClass="InboundBundle\Repository\RequestForEstimateRepository") */ class RequestForEstimate { /** * @var int * * @ORM\Column(name="request_id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var \DateTime * * @ORM\Column(name="create_time", type="datetime") */ private $createTime; /** * @var \DateTime * * @ORM\Column(name="update_time", type="datetime") */ private $updateTime; /** * @ORM\ManyToOne(targetEntity="RequestStatus", cascade={"persist"}) */ private $status; /** * @ORM\ManyToOne(targetEntity="CoreBundle\Entity\Product") * @ORM\JoinColumn(name="product_id", referencedColumnName="product_id") */ private $product; /** * @var int * * @ORM\Column(name="quantity", type="integer") */ private $quantity = 0; /** * @var string * * @ORM\Column(name="price_per_unit", type="decimal", precision=10, scale=2) */ private $pricePerUnit = 0; /** * @var string * * @ORM\Column(name="shipping_cost", type="decimal", precision=10, scale=2) */ private $shippingCost = 0; /** * @var string * * @ORM\Column(name="package_cost", type="decimal", precision=10, scale=2) */ private $packageCost = 0; /** * @var string * * @ORM\Column(name="other_fees", type="decimal", precision=10, scale=2) */ private $otherFees = 0; /** * @var integer * * @ORM\Column(name="deposit_required", type="integer") */ private $depositRequired = 0; /** * Get id * * @return int */ public function getId() { return $this-&gt;id; } /** * Set product * * @param integer $product * * @return RequestForEstimate */ public function setProduct($product) { $this-&gt;product = $product; return $this; } /** * Get product * * @return int */ public function getProduct() { return $this-&gt;product; } /** * Set quantity * * @param integer $quantity * * @return RequestForEstimate */ public function setQuantity($quantity) { $this-&gt;quantity = $quantity; return $this; } /** * Get quantity * * @return int */ public function getQuantity() { return $this-&gt;quantity; } /** * Set pricePerUnit * * @param string $pricePerUnit * * @return RequestForEstimate */ public function setPricePerUnit($pricePerUnit) { $this-&gt;pricePerUnit = $pricePerUnit; return $this; } /** * Get pricePerUnit * * @return string */ public function getPricePerUnit() { return $this-&gt;pricePerUnit; } /** * Set shippingCost * * @param string $shippingCost * * @return RequestForEstimate */ public function setShippingCost($shippingCost) { $this-&gt;shippingCost = $shippingCost; return $this; } /** * Get shippingCost * * @return string */ public function getShippingCost() { return $this-&gt;shippingCost; } /** * Set otherFees * * @param string $otherFees * * @return RequestForEstimate */ public function setOtherFees($otherFees) { $this-&gt;otherFees = $otherFees; return $this; } /** * Get otherFees * * @return string */ public function getOtherFees() { return $this-&gt;otherFees; } /** * Set requestId * * @param \InboundBundle\Entity\RequestForEstimate $requestId * * @return RequestForEstimate */ public function setRequestId(\InboundBundle\Entity\RequestForEstimate $requestId = null) { $this-&gt;requestId = $requestId; return $this; } /** * Get requestId * * @return \InboundBundle\Entity\RequestForEstimate */ public function getRequestId() { return $this-&gt;requestId; } /** * Set productId * * @param \InboundBundle\Entity\Product $productId * * @return RequestForEstimate */ public function setProductId(\InboundBundle\Entity\Product $productId = null) { $this-&gt;productId = $productId; return $this; } /** * Get productId * * @return \InboundBundle\Entity\Product */ public function getProductId() { return $this-&gt;productId; } /** * Constructor */ public function __construct() { } /** * Set depositRequired * * @param string $depositRequired * * @return RequestForEstimate */ public function setDepositRequired($depositRequired) { $this-&gt;depositRequired = $depositRequired; return $this; } /** * Get depositRequired * * @return string */ public function getDepositRequired() { return $this-&gt;depositRequired; } /** * Set packageCost * * @param string $packageCost * * @return RequestForEstimate */ public function setPackageCost($packageCost) { $this-&gt;packageCost = $packageCost; return $this; } /** * Get packageCost * * @return string */ public function getPackageCost() { return $this-&gt;packageCost; } /** * Set status * * @param \InboundBundle\Entity\RequestStatus $status * * @return RequestForEstimate */ public function setStatus(\InboundBundle\Entity\RequestStatus $status = null) { $this-&gt;status = $status; return $this; } /** * Get status * * @return \InboundBundle\Entity\RequestStatus */ public function getStatus() { return $this-&gt;status; } /** * Set createTime * * @param \DateTime $createTime * * @return RequestForEstimate */ public function setCreateTime($createTime) { $this-&gt;createTime = $createTime; return $this; } /** * Get createTime * * @return \DateTime */ public function getCreateTime() { return $this-&gt;createTime; } /** * Set updateTime * * @param \DateTime $updateTime * * @return RequestForEstimate */ public function setUpdateTime($updateTime) { $this-&gt;updateTime = $updateTime; return $this; } /** * Get updateTime * * @return \DateTime */ public function getUpdateTime() { return $this-&gt;updateTime; } } </code></pre> <p>PurchaseOrder entity:</p> <pre><code>&lt;?php namespace InboundBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * PurchaseOrder * * @ORM\Table(name="purchase_order") * @ORM\Entity(repositoryClass="InboundBundle\Repository\PurchaseOrderRepository") */ class PurchaseOrder { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\OneToOne(targetEntity="RequestForEstimate", cascade={"persist"}) * @ORM\JoinColumn(name="request_estimate_id", referencedColumnName="request_id") */ private $requestId; /** * @var \DateTime * * @ORM\Column(name="create_time", type="datetime") */ private $createTime; /** * @var \DateTime * * @ORM\Column(name="update_time", type="datetime") */ private $updateTime; /** * @var int * * @ORM\Column(name="status", type="integer") */ private $status; /** * @var \DateTime * * @ORM\Column(name="ship_date", type="date", nullable=true) */ private $shipDate; /** * Get id * * @return int */ public function getId() { return $this-&gt;id; } /** * Set createTime * * @param \DateTime $createTime * * @return PurchaseOrder */ public function setCreateTime($createTime) { $this-&gt;createTime = $createTime; return $this; } /** * Get createTime * * @return \DateTime */ public function getCreateTime() { return $this-&gt;createTime; } /** * Set updateTime * * @param \DateTime $updateTime * * @return PurchaseOrder */ public function setUpdateTime($updateTime) { $this-&gt;updateTime = $updateTime; return $this; } /** * Get updateTime * * @return \DateTime */ public function getUpdateTime() { return $this-&gt;updateTime; } /** * Set status * * @param integer $status * * @return PurchaseOrder */ public function setStatus($status) { $this-&gt;status = $status; return $this; } /** * Get status * * @return int */ public function getStatus() { return $this-&gt;status; } /** * Set shipDate * * @param \DateTime $shipDate * * @return PurchaseOrder */ public function setShipDate($shipDate) { $this-&gt;shipDate = $shipDate; return $this; } /** * Get shipDate * * @return \DateTime */ public function getShipDate() { return $this-&gt;shipDate; } /** * Set requestForEstimate * * @param \InboundBundle\Entity\RequestForEstimate $requestForEstimate * * @return PurchaseOrder */ public function setRequestForEstimate(\InboundBundle\Entity\RequestForEstimate $requestForEstimate = null) { $this-&gt;requestForEstimate = $requestForEstimate; return $this; } /** * Get requestForEstimate * * @return \InboundBundle\Entity\RequestForEstimate */ public function getRequestForEstimate() { return $this-&gt;requestForEstimate; } /** * Set requestId * * @param $requestId * * @return PurchaseOrder */ public function setRequestId($requestId) { $this-&gt;request_id = $requestId; return $this; } /** * Get requestId * * @return \InboundBundle\Entity\RequestForEstimate */ public function getRequestId() { return $this-&gt;request_id; } } </code></pre> <p>My controller:</p> <pre><code> /** * @Route("request-for-estimate/confirm/{id}", name="request_confirm") */ public function confirmRequest(RequestForEstimate $RequestForEstimate) { $repo = $this-&gt;getDoctrine()-&gt;getRepository('InboundBundle:RequestStatus'); $status = $repo-&gt;findOneById('6'); $RequestForEstimate-&gt;setupdateTime(new \DateTime()); $RequestForEstimate-&gt;setstatus($status); $PurchaseOrder = new PurchaseOrder(); $PurchaseOrder-&gt;setRequestId($RequestForEstimate); $PurchaseOrder-&gt;setupdateTime(new \DateTime()); $PurchaseOrder-&gt;setcreateTime(new \DateTime()); $PurchaseOrder-&gt;setstatus(1); $em1 = $this-&gt;getDoctrine()-&gt;getManager(); $em1-&gt;persist($PurchaseOrder); $em1-&gt;flush(); $em = $this-&gt;getDoctrine()-&gt;getManager(); $em-&gt;persist($RequestForEstimate); $em-&gt;flush(); return $this-&gt;redirectToRoute('requests_for_estimate_view'); } </code></pre>
<p>I will give you an example from one of my projects. The whole trick is in entities setters and cascaders configurations. Hope it will help.</p> <p>Entities:</p> <pre><code>class Agreement { // ... /** * @ORM\OneToOne(targetEntity="AppBundle\Entity\Requisites", mappedBy="agreement", cascade={"persist"}) */ private $requisites; // ... public function setRequisites(Requisites $requisites = null) { $this-&gt;requisites = $requisites; $requisites-&gt;setAgreement($this); return $this; } public function getRequisites() { return $this-&gt;requisites; } } class Requisites { // ... /** * @ORM\OneToOne(targetEntity="AppBundle\Entity\Agreement", inversedBy="requisites") * @ORM\JoinColumn(name="Agreement_id", referencedColumnName="id") */ private $agreement; // ... public function setAgreement(Agreement $agreement = null) { $this-&gt;agreement = $agreement; return $this; } public function getAgreement() { return $this-&gt;agreement; } } </code></pre> <p>Controller:</p> <pre><code>if (null === $agreement-&gt;getRequisites()) { $agreement-&gt;setRequisites(new Requisites()); } $entityManager = $this-&gt;getDoctrine()-&gt;getManager(); $entityManager-&gt;persist($agreement); $entityManager-&gt;flush(); </code></pre>
Laravel can't update database? <p>This is a weird error. I can add a new record to the database fine with a new UserEdit method, but if I try to update a record. Nothing. It doesn't even file a blank value, or issue an error. </p> <p>What am I missing? To try to eliminate issues, I tried running the core update method in the documentation like so: </p> <pre><code>protected function create() { $save = UserEdit::find(715); $save-&gt;First_Name = 'Jeffrey'; $save-&gt;Last_Name = 'Way'; $save-&gt;save(); $id = UserEdit::find(715)-&gt;toArray(); return view('NewUser', compact('id')); //return $array; } </code></pre> <p>This problem is the same as my earlier question <a href="http://stackoverflow.com/questions/40038692/laravel-form-not-submitting-data-to-database">here</a>, but I didn't think it appropriate to double up the questions and this is technically a different problem. My blade just prints an array of the user data at the moment so I know if it's working or not:</p> <p>@extends('layout')</p> <pre><code>@section('content') &lt;h1&gt; Add Your Information {{ $id['name'] }}&lt;/h1&gt; &lt;div class="col-md-6"&gt; @foreach ($id as $key=&gt;$value) {{ $value }}&lt;br&gt; @endforeach &lt;/div&gt; @stop </code></pre> <p>The Routes:</p> <pre><code>&lt;?php Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', 'HomeController@index'); Route::get('NewUser', 'UserEntryController@create'); Route::post('NewUser', 'UserEntryController@UserForm'); Route::post('NewUser', 'UserEntryController@UserForm')-&gt;name('submit'); </code></pre> <p>I'm assuming I'm missing some crucial minor detail, but for the life of me, can't find what. Anybody got an idea where to look?</p>
<pre><code>public function store(Request $request) { $user = new UserEdit; //$user-&gt;name = $request-&gt;name; $user-&gt;First_Name = "foo"; $user-&gt;Last_Name = "bar"; $user-&gt;save(); return $user; } </code></pre> <p>Try this function, maybe you had a mistake in your code.</p>