title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
Rotate a singly linked list in Java
<p>My functions:</p> <pre><code>import java.util.Collection; import java.util.Collections; public class LinkedList { private Node head; private int listCount; // konstruktor na povrzanata lista public LinkedList() { // ova e prazna lista, pa zatoa 'head' pokazuva kon nov jazok bez elementi (null) head = new Node(null); listCount = 0; } // dodavame element (data) na krajot od listata public void add(Object data) { Node temp = new Node(data); Node current = head; head.setData(temp.getData()); // pocnuvajki od 'head' (pocetniot element) pominuvame niz site lemenenti while(current.getNext() != null) { current = current.getNext(); } current.setNext(temp); // go zgolemuvame brojot na elementi vo listata listCount++; } // dodavame element (data) na posebno opredelena pozicija (index) public void add(Object data, int index) { Node temp = new Node(data); Node current = head; head.setData(temp.getData()); // odime do baraniot index, ili do posledniot element od listata (do koj stigneme prvo) for (int i = 1; i &lt; index &amp;&amp; current.getNext() != null; i++) { current = current.getNext(); } // go postavuvame sledniot element na novata jazla // da pokazuva kon sledniot element na ovaa jazla temp.setNext(current.getNext()); // a sega go postavuvame sledniot element na ovaa jazla // da pokazuva kon novata jazla current.setNext(temp); // go nakacuvame vkupniot broj na elementi vo listata listCount++; } // vraka element na opredelena pozicija vo listata public Object get(int index) { if(index &lt;= 0) { return null; } Node current = head.getNext(); for(int i = 1; i &lt; index; i++) { if(current.getNext() == null) { return null; } current = current.getNext(); } return current.getData(); } // go vrakame brojot na elementi vo listata public int size() { return listCount; } // go brisime elementot na opredelenata pozicija vo listata public boolean remove(int index) { if(index &lt; 1 || index &gt; size()) { return false; } Node current = head; for(int i = 1; i &lt; index; i++) { if(current.getNext() == null) { return false; } current = current.getNext(); } current.setNext(current.getNext().getNext()); // go namaluvame brojot na elementi vo listata listCount--; return true; } public boolean contains(Object data) { Node temp = new Node(data); Node current = head; for(int i = 0; i &lt; size(); i++) { if(temp.getData().equals(current.getData())) { return true; } else { current = current.getNext(); } } return false; } public Node inserAfter(Object data, Node n) { Node temp = new Node(data); Node current = n.getNext(); temp.setNext(current); n.setNext(temp); return temp; } public void rotateLeft() { Node temp = head; //head = head.getNext(); //Node tail = head.getNext(); if (head != null) { //otherwise it is empty list //Node temp = head; if (head.getNext() != null) { //otherwise it is single item list head = head.getNext(); } } Node tail; if (head.getNext() != null) { //more than 2 items in the list tail = head.getNext(); } else { //only 2 items in the list tail = head; } while(tail.getNext() != null) { if (tail.getNext() != null) { tail = tail.getNext(); } //tail = tail.getNext(); } tail.setNext(temp); temp.setNext(null); } public void rotateRight() { Node temp = null; Node current = head; while(current.getNext() != null) { temp = current; current = current.getNext(); } current.setNext(head); head = current; temp.setNext(null); } public void reverse() { Node reversedPart = null; Node current = head; while(current != null) { Node next = current.next; current.next = reversedPart; reversedPart = current; current = next; } head = reversedPart; } public Node copyList(Node source) { Node copyHead = null; Node copyTail = null; Node temp = new Node(source); Node current = head.getNext(); for(int i = 0; i &lt; size(); i++) { Node newNode = new Node(temp.getData()); if(copyHead == null) { copyHead = newNode; copyTail = copyHead; } else { copyTail.setNext(newNode); copyTail = copyTail.getNext(); } } return copyHead; } public Object setDataIndexOf(Object data, int index) { Node node = nodeAt(index); if(node == null) { return null; } else { Object old = node.getData(); node.setData(data); return old; } } public Object dataAt(int index) { Node current = head.getNext(); if(index &lt; 1 || index &gt; size()) { return null; } for(int i = 0; i &lt; index; i ++) { if(i != index - 1) { current = current.getNext(); } } return current.getData(); } public Node nodeAt(int index) { Node current = head.getNext(); if(index &lt; 1 || index &gt; size()) { return null; } for(int i = 0; i &lt; index; i++) { if(i != index - 1) { current = current.getNext(); } } return current; } public int indexOf(Object data) { Node temp = new Node(data); Node current = head.getNext(); for(int i = 0; i &lt; size(); i++) { if(current.getData().equals(temp.getData())) { return i; } current = current.getNext(); } return -1; } public Object min() { Integer min = (Integer)head.getData(); Node current = head; while(current.getNext() != null) { if((Integer)current.getData() &lt; min) { min = (Integer)current.getData(); } current = current.getNext(); } return min; } public Object max() { Integer max = (Integer)head.getData(); Node current = head; while(current.getNext() != null) { if((Integer)current.getData() &gt; max) { max = (Integer)current.getData(); } current = current.getNext(); } return max; } public void removeSecondAppear(Object data) { Node temp = new Node(data); Node current = head; Node previous = null; boolean found = false; while(current != null) { if(current.getData().equals(temp.getData()) &amp;&amp; current.getData() != null) { if(found == true) { previous.setNext(current.getNext()); break; } else if(found == false) { found = true; } } else{ found = false; } previous = current; current = current.getNext(); } } public String toString() { Node current = head.getNext(); String output = ""; while(current != null) { output += "[" + current.getData().toString() + "]"; current = current.getNext(); } return output; } } </code></pre> <p>My node:</p> <pre><code>public class Node { Node next; Object data; public Node(Object _data) { next = null; data = _data; } public Node(Object _data, Node _next) { next = _next; data = _data; } public Object getData() { return data; } public void setData(Object _data) { data = _data; } public Node getNext() { return next; } public void setNext(Node _next) { next = _next; } } </code></pre> <p>I'm trying to create a function to rotate a singly linked in list in Java. I have made two functions for left and right.</p> <p>My left function seems to work, but not fully. For example. If my list contains the elements: 1 2 3</p> <p>Then my rotateLeft will make the list into 2 3. The 1 will be gone. But it should come on the position of previous 3.</p> <p>As for the rotateRight, the function is not functioning properly for some reason, been trying a few hours and can't find the solution.</p> <pre><code> LinkedList LL = new LinkedList(); LL.add("1"); LL.add("2"); LL.add("3"); LL.add("4"); LL.add("4"); LL.add("5"); LL.rotateLeft(); </code></pre> <p>2, 3, 4, 4, 5, null is the output. My add method is the following:</p> <pre><code>public void add(Object data) { Node temp = new Node(data); Node current = head; while(current.getNext() != null) { current = current.getNext(); } current.setNext(temp); listCount++; } </code></pre>
1
5,324
Card trick Java
<p>I have been working on this program for over 30 hours and I am almost as lost now as when i first started. I've finally been able to print out 7 rows of 3 cards but i still have a few issues with my program. </p> <ol> <li><p>I need to have the cards line up on the word "of"</p></li> <li><p>when i call my PrintDeck() function it is supposed to print out all the cards in the deck but it does not.</p></li> <li><p>I cannot for the life of me figure out how to pick up the columns of cards in order to do the trick, If teh user chooses column 1 i'm supposed to pick it up second and then deal them out again in 7 rows of 3 columns. Then ask them to pick their card 2 more time and do the same thing.</p></li> </ol> <p>Any help you could offer would be greatly appreciated. I know some of the code is not very pretty but it has to be that way for the assignment in order for me to get credit :/ Thank you so much for all your help.</p> <p>instructions: here is a doc if the link works ----> <a href="http://word.office.live.com/wv/WordView.aspx?FBsrc=https://www.facebook.com/attachments/doc_preview.php?mid=id.376414855713455&amp;id=05ba139ea8f82045adb02272e74d6bf2&amp;metadata&amp;access_token=1850923532%3aAQBxvI0QdjuXTt48&amp;title=Cardtrick%20Instructions%20-%20Java" rel="nofollow">instructions doc</a> Program Requirements:</p> <p>Your program must generate its own random deck of cards using the following technique:</p> <ul> <li><p>generate a random integer for each card</p></li> <li><p>display a string value for each card ("Ace of Diamonds")</p></li> <li><p>use the rand() function to generate integer card values</p></li> <li><p>use the srand(time(0)) command (only once at the beginning of the program) to generate a truly random deck once the program has been tested and runs properly.</p></li> </ul> <p>Each value must be converted to the format of as done in the example above. Whenever your program displays the cards they must line up as they do above, on the word "of".<br> Your program must deal the cards out by row and pick them up by column (3 times to make it work properly).<br> Your program must ask the player is he/she wants to printout the entire deck before playing. Each card must be printed out formatted as above.<br> Your program must ask the player if he/she wants to play again, and continue playing as many times as the player wants.<br> The program must ask the player for his/her name and refer to the player by name throughout the playing of the game.<br> Your program code must be logically organized using functions. You also must use the starter file provided. You will GET A ZERO (0) if you do not use the starter file! </p> <p>The starter file provided: CardtrickStarterFile.java if this pastes weird here is a pastebin link: <a href="http://pastebin.com/rsZY2vKq" rel="nofollow">http://pastebin.com/rsZY2vKq</a></p> <pre><code>import java.util.Scanner; import java.lang.String; import java.util.Random; public class CardTrickStarterFile { private static Random rand = new Random(); private static String PlayAgain; public static void main(String[] args) { /* declare and initialize variables */ int column = 0, i = 0; /* Declare a 52 element array of integers to be used as the deck of cards */ int[] deck = new int[52]; /* Declare a 7 by 3 array to receive the cards dealt to play the trick */ int[][] play = new int[7][3]; /* Declare a Scanner object for input */ Scanner input = new Scanner(System.in); /* Generate a random seed for the random number generator. */ /* Openning message. Ask the player for his/her name */ System.out.println("\nHello, I am a computer program that is so smart"); System.out.println("I can even perform a card trick. Here's how.\n"); System.out.println("To begin the card trick type in your name: "); String name = input.nextLine(); char firstL = name.charAt(0); firstL = Character.toUpperCase(firstL); name = replaceCharAt(name, 0, firstL); /* Capitalize the first letter of the person's name. */ System.out.println("\nThank you " + name); do { /* Build the deck */ BuildDeck(deck); /* Ask if the player wants to see the entire deck. If so, print it out. */ System.out.println("Ok " + name + ", first things first. Do you want to see what "); System.out.println("the deck of cards looks like (y/n)? "); String SeeDeck = input.nextLine(); switch (SeeDeck) { case "y": PrintDeck(deck); break; case "n": System.out.println("Ok then let us begin."); Deal(deck,play); break; default: break; } System.out.printf("\n%s, pick a card and remember it...\n", name); /* Begin the card trick loop */ for(i = 0; i &lt; 3; i++) { /* Begin the trick by calling the function to deal out the first 21 cards */ /* Include error checking for entering which column */ do { /* Ask the player to pick a card and identify the column where the card is */ System.out.print("\nWhich column is your card in (0, 1, or 2)?: "); column = input.nextInt(); } while(column &lt; 0 || column &gt; 2); /* Pick up the cards, by column, with the selected column second */ } /* Display the top ten cards, then reveal the secret card */ /* if the player wants to play again */ System.out.printf("%s, would you like to play again (y/n)? ", name); String PlayAgain = input.nextLine(); } while(PlayAgain == "y"); /* Exiting message */ System.out.println("\nThank you for playing the card trick!\n"); return; } public static String replaceCharAt(String s, int pos, char c) { return s.substring(0,pos) + c + s.substring(pos+1); } public static void BuildDeck( int deck[]) { int[] used = new int[52]; int i = 0; int card = 0; /* Generate cards until the deck is full of integers */ while(i &lt; deck.length) { /* generate a random number between 0 and 51 */ card = rand.nextInt(52); /* Check the used array at the position of the card. If 0, add the card and set the used location to 1. If 1, generate another number */ if(used[card] == 0) { used[card] = 1; deck[i] = card; i++; } } } public static void PrintDeck( int deck[] ) { for (int i=0; i &lt; 52; i++){ PrintCard(i); } /* Print out each card in the deck */ } public static void Deal( int deck[], int play[][] ) { int card = 0; /* deal cards by passing addresses of cardvalues from the deck array to the play array */ System.out.println("\n Column 0 Column 1 Column 2"); System.out.println("======================================================="); for(int row = 0; row &lt; play.length; row++){ for(int col = 0; col &lt; play[row].length; col++){ play[row][col]=deck[card]; card++; System.out.printf("%s", PrintCard(play[row][col]) + " "); } System.out.println(); } } public static String PrintCard( int card ) { int rank = (card % 13); int suit = (card / 13); String[] suits = { "Clubs", "Hearts", "Diamonds", "Spades" }; String[] ranks = { "King", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen"}; return (ranks[rank] + " of " + suits[suit]); } public static void PickUp( int deck[], int play[][], int column ) { int card = 0, row = 0; return; } public static void SecretCard( int deck[] ) { int card = 0; System.out.println("\nFinding secret card..."); for(card = 0; card &lt; 10; card++) PrintCard(deck[card]); System.out.println("\nYour secret card is: "); PrintCard(deck[card]); return; } } </code></pre>
1
2,655
MYSQL SUM & GRAND TOTAL
<p>I am trying to get a GRAND TOTAL for the following mysql query. But am not having any luck, I am not so good at mysql yet.</p> <pre><code>SELECT SUM(ep_price) FROM orders WHERE date_shipped BETWEEN '2017-04-01' and '2017-04-30' GROUP BY order_number </code></pre> <p>Query:</p> <pre><code>Result: '152989', '93670.39999999998' '157669', '159.5' '165955', '45195' '166054', '5030' '166410', '29700' '167023', '4530' '167110', '9647.2' '167152', '56620' '167477', '46087.14' '167483', '1690' '167545', '3295' '167563', '9144.550000000001' '167566', '35036.67999999999' '167736', '2015' '167853', '1277.5' '167971', '3695' '167982', '5690.4' '168063', '4316.4' '168101', '3400' '168330', '4686.9' '168435', '725' '168454', '4002.5' '168455', '6372' '168477', '1941' '168590', '3625.5' '168593', '18560.4' '168704', '238' '168706', '119' '168870', '3340' '168962', '2800' '169019', '2050' '169203', '1940' '169207', '7500.51' '169209', '3888.4' '169212', '10006.5' '169214', '5580' '169230', '2742.5' '169235', '33490.2' '169371', '12400' '169413', '671.6' '169529', '2345' '169642', '17480' '169689', '1500' '169731', '1602.9' '169835', '567' '169893', '535.2' '169895', '431' '170015', '143.2' '170031', '431.8' '170050', '233.7' '170093', '3465' '170157', '3070' '170159', '6040' '170176', '746.5' '170260', '3195' '170318', '4081.06' '170323', '5400' '170324', '2865' '170418', '1815' '170419', '3984' '170451', '29775.2' '170483', '184.7' '170484', '996.4' '170486', '1363.8' '170549', '9975.75' '170566', '5350' '170599', '5978.5' '170600', '5480.42' '170603', '1309.95' '170612', '9979.7' '170619', '2194' '170620', '32490' '170661', '4075' '170721', '1910' '170735', '4950' '170756', '19450' '170758', '9250' '170763', '285.8' '170821', '1875' '170849', '4950' '170859', '3212.84' '170865', '132.6' '170991', '583.1' '170992', '155.2' '171108', '181.6' '171111', '180.9' '171113', '1481.1' '171120', '332.8' '171135', '3869.3199999999997' '171200', '1175' '171204', '288.1' '171205', '261.5' '171206', '256.6' '171208', '221.6' '171209', '815' '171217', '14903.6' '171262', '3910' '171269', '545' '171272', '273.1' '171303', '976.25' '171305', '3600' '171309', '195.2' '171310', '16959.13' '171354', '1215' '171382', '4500' '171386', '86.9' '171407', '511.5' '171410', '2744.4' '171412', '5634' '171416', '5287.5' '171417', '2063.3999999999996' '171423', '150.2' '171513', '4370.4' '171566', '2747' '171567', '134.7' '171670', '2067' '171676', '348.8' '171677', '437.5' '171717', '198' '171728', '165.5' '171767', '17430' '171771', '865.8000000000001' '171774', '3627.5' '171831', '13987.5' '171834', '142.4' '171836', '1108.2' '171837', '5199' '171956', '254.9' '171958', '1286.8' '171962', '5586.4' '171963', '4128.9' '172067', '1690' '172068', '5705' '172069', '893.75' '172074', '3795' '172174', '1242' '172214', '1411.2' '172215', '568.8' '172217', '1848.2' '172219', '1985' '172220', '22436' '172244', '166.1' '172245', '325.9' '172246', '2395' '172329', '1885.5' '172333', '197.8' '172338', '297.2' '172341', '1126.5' '172342', '138.3' '172352', '388.3' '172355', '160' '172382', '244.2' '172442', '3628.71' '172448', '1050' '172452', '213.2' '172466', '292.6' '172467', '180' '172469', '407.1' '172515', '965' '172539', '3812.5' '172602', '1649' '172631', '514' '172632', '552.8' '172834', '250.7' '172835', '360' '172836', '0' '172840', '0' '172844', '815' '172846', '2970' '172902', '4635' '172997', '143.9' '172998', '174.7' '173132', '210' '173255', '290' '173260', '565.9' '173277', '115' '173545', '672.1' '173546', '225' '173562', '215' '173606', '445.6' '173611', '228.4' '173646', '238.61' '173690', '755' '173694', '15400' '173706', '0' '174028', '855' </code></pre> <p>So how can I add all of these order_numbers together in a grand total?</p> <p>I will have multiple entries with the same order_number and ep_price but the distinction is the job_number. That's why I am using the GROUP BY order_number.</p> <p>Thank you for your help.</p>
1
2,175
Bootstrap 3 RC2 custom navbar fixed top goes on two line
<p>I am using Bootstrap 3 RC2, and I am trying to make a navbar fixed to top, but without being full width. I have copied the "navbar-fixed-top" declarations in the css, and created mine. On IE (10), this works well, but on Chrome (28) the bar goes on two lines.</p> <p>Have I missed something to have navbar's content always on same line ?</p> <p>Thanks.</p> <p>The bootply : <a href="http://bootply.com/74981" rel="nofollow">http://bootply.com/74981</a></p> <p>The CSS :</p> <pre><code>.navbar-custom { border-width: 0 0 1px; position: fixed; top: 0; right: 100px; z-index: 1030; } .navbar-custom .navbar-form { padding-right: 0; } .navbar-custom { border-radius: 0; -webkit-border-bottom-right-radius: 5px; -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomright: 5px; -moz-border-radius-bottomleft: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; } </code></pre> <p>The html :</p> <pre><code>&lt;nav class="navbar navbar-inverse navbar-custom" role="navigation"&gt; &lt;!-- Brand and toggle get grouped for better mobile display --&gt; &lt;div class="navbar-header"&gt; &lt;button class="navbar-toggle" type="button" data-target=".navbar-ex1-collapse" data-toggle="collapse"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a title="Accueil" class="navbar-brand" href="/"&gt; Flammy &lt;/a&gt; &lt;/div&gt; &lt;!-- Collect the nav links, forms, and other content for toggling --&gt; &lt;div class="collapse navbar-collapse navbar-ex1-collapse"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li&gt;&lt;a href="#"&gt;News&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Events&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a class="dropdown-toggle" href="#" data-toggle="dropdown"&gt;Games &lt;b class="caret"&gt;&lt;/b&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Game 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Game 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Game 3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a class="dropdown-toggle" href="#" data-toggle="dropdown"&gt;Projects &lt;b class="caret"&gt;&lt;/b&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Big project 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Big project 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Big project 3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Forums&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;form class="navbar-form navbar-right" action="/Account/Logout" method="post"&gt; &lt;div class="btn-group"&gt; &lt;a class="btn btn-default" href="#"&gt;Register&lt;/a&gt; &lt;a class="btn btn-default" href="#"&gt;Login&lt;/a&gt; &lt;div class="btn-group"&gt; &lt;button title="Language" class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown"&gt; &lt;i class="glyphicon glyphicon-flag"&gt;&lt;/i&gt; &lt;/button&gt; &lt;ul class="dropdown-menu pull-right"&gt; &lt;li&gt;&lt;a href="#"&gt;Language&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Language&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Language&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;!-- /.navbar-collapse --&gt; &lt;/nav&gt; </code></pre>
1
2,161
php check post contains a variable
<p>this is my page when i run it i got the excption which sayes that the <code>formSubmit</code> is not define . i know that i have to check if the <code>post</code> contents that variable but i couldn't know the solution </p> <pre><code> &lt;?php if($_POST['formSubmit'] == "Submit") { $errorMessage = ""; if(empty($_POST['formPassword'])) { $errorMessage .= "&lt;li&gt; You forgot to enter your password!&lt;/li&gt;"; } if(empty($_POST['formName'])) { $errorMessage .= "&lt;li&gt; You forgot to enter a name!&lt;/li&gt;"; } $varPassword = $_POST['formPassword']; $varName = $_POST['formName']; if(empty($errorMessage)) { require('Document1.php'); User::add_user($varName, $varPassword); exit; //header("Location: normal.php"); } } ?&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;SIGN UP&lt;/title&gt; &lt;style type="text/css"&gt; &lt;!-- .style1 { font-size: xx-large; color: #0000CC; } --&gt; &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;p align="center"&gt;&lt;br&gt; &lt;span class="style1"&gt;SIGN UP&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;form action="myform1.php" method="post"&gt; &lt;p&gt; What is Your NAME ?&lt;br&gt; &lt;input type="text" name="formName" maxlength="50" value="" /&gt; &lt;/p&gt; &lt;p&gt; What is Your PASSWORD ?&lt;br&gt; &lt;input type="text" name="formPassword" maxlength="50" value="" /&gt; &lt;/p&gt; &lt;?php /* ?&gt; &lt;p&gt; What is Your Email ?&lt;br&gt; &lt;input type="text" name="formEmail" maxlength="50" value="" /&gt; &lt;/p&gt; */ ?&gt; &lt;input type="submit" name="formSubmit" value="Submit" /&gt; &lt;input type=reset value = "delete fields "&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <h3> any help would be appreicated </h3>
1
1,262
dreamweaver php mysql + profile page
<p>hey guys i am creating a website with login and registration and profile page hat will be created by default as soon as the user register in the form then log in these information will be displayed as a profile info in the profile page that is unique to each user. the username will specify each user and his profile page .these are some php files, anyone have an idea how to display the only the information that belong to the specified user and not all information of all the users. </p> <h1>registerForm.php</h1> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Registration Page&lt;/title&gt; &lt;link href="style/stylesheet.css" rel="stylesheet" type="text/css" /&gt; &lt;/head&gt; &lt;?php require_once('header.php'); ?&gt; &lt;body&gt; &lt;h2 class="RegisterTitleForm"&gt;Registration Form&lt;/h2&gt; &lt;h3 class="requiredField"&gt;* Requierd Field!!&lt;/h3&gt; &lt;table width="280" border="0" align="center"&gt; &lt;form action="registerProcess.php" method="post" id="registerForm"&gt; &lt;tr&gt; &lt;input type="hidden" name="uid" id="uid" /&gt; &lt;td style="text-align: right"&gt;&lt;label for="firstname"&gt;&lt;span class="Fields"&gt;First Name&lt;/span&gt; &lt;span class="requiredField"&gt;*&lt;/span&gt;&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="firstname" id="firstname" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style="text-align: right"&gt;&lt;label for="lasttname" class="Fields"&gt;Last Name&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="lastname" id="lastname" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="Fields" style="text-align: right"&gt;&lt;label for="birthdate"&gt;Birth Date&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="date" name="birthdate" value= "YYYY_MM_DD" onfocus="if (this.value == 'YYYY_MM_DD') {this.value = '';}" onblur="if (this.value == '') {this.value = 'YYYY_MM_DD';}" type="text" id="birthdate" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="Fields" style="text-align: right"&gt;&lt;label for="phonenumber"&gt;Phone Number&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="tel" name="phonenumber" value="000-0-000 000" onfocus="if (this.value == '000-0-000 000') {this.value = '';}" onblur="if (this.value == '') {this.value = '000-0-000 000';}" type="text" id="phonenumber" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="Fields" style="text-align: right"&gt;&lt;label for="gender"&gt;Gender &lt;span class="requiredField"&gt;*&lt;/span&gt;&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;p&gt; &lt;label class="Fields"&gt; &lt;input type="radio" name="genderGroup" value="Male" id="genderGroup_male" /&gt; Male&lt;/label&gt; &lt;br /&gt; &lt;label class="Fields"&gt; &lt;input type="radio" name="genderGroup" value="Female" id="genderGroup_female" /&gt; Female&lt;/label&gt; &lt;br /&gt; &lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="Fields" style="text-align: right"&gt;&lt;label for="country"&gt;Country&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;select name="country" id="country"&gt;&lt;option selected=&gt;please choose coutry&lt;option&gt;lebanon&lt;option&gt;Us&lt;option&gt;europe &lt;/select&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="Fields" style="text-align: right"&gt;&lt;label for="adress"&gt;Local Adress &lt;span class="requiredField"&gt;*&lt;/span&gt;&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="adress" id="adress" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="Fields" style="text-align: right"&gt;&lt;label for="specialisation"&gt;Specialisation &lt;span class="requiredField"&gt;*&lt;/span&gt;&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;select name="specialisation" id="specialisation"&gt; &lt;/select&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="Fields" style="text-align: right"&gt;&lt;label for="email"&gt;Email Adress&lt;span class="requiredField"&gt;*&lt;/span&gt;&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="email" name="email" id="email" /&gt;&lt;/td&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="Fields" style="text-align: right"&gt;&lt;label for="username"&gt;User Name&lt;span class="requiredField"&gt;*&lt;/span&gt;&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="username" id="username" /&gt;&lt;/td&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="Fields" style="text-align: right"&gt;&lt;label for="password"&gt;Password&lt;span class="requiredField"&gt;*&lt;/span&gt;&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="password" name="password" id="password" /&gt;&lt;/td&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="Fields" style="text-align: right"&gt;&lt;label for="password2"&gt;Re_Password&lt;span class="requiredField"&gt;*&lt;/span&gt;&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="password" name="password2" id="password2" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&lt;input type="submit" name="register" id="register" value="Register" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/form&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <h1>registerprocess.php</h1> <pre><code>&lt;?php require_once('config.php'); if(isset($_POST['register'])) { if(! get_magic_quotes_gpc() ) { $firstname = addslashes ($_POST['firstname']); $lastname = addslashes ($_POST['lastname']); $birthdate = addslashes ($_POST['birthdate']); $phonenumber = addslashes ($_POST['phonenumber']); $genderGroup = addslashes ($_POST['genderGroup']); $country = addslashes ($_POST['country']); $adress = addslashes ($_POST['adress']); $specialisation = addslashes ($_POST['specialisation']); $email = addslashes ($_POST['email']); $password2 = addslashes ($_POST['password2']); $username = addslashes ($_POST['username']); $password = addslashes ($_POST['password']); $password2 = addslashes ($_POST['password2']); } else { $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $birthdate = $_POST['birthdate']; $phonenumber = $_POST['phonenumber']; $genderGroup = $_POST['genderGroup']; $country = $_POST['country']; $adress = $_POST['adress']; $specialisation = $_POST['specialisation']; $email = $_POST['email']; $username = $_POST['username']; $password = $_POST['password']; $password2 = $_POST['password2']; } $sql = "INSERT INTO users ". "(firstname,lastname, birthdate, phonenumber, gender, country, localadress, specialisation, email, username, password, password2, joindate) ". "VALUES('$firstname','$lastname','$birthdate','$phonenumber','$genderGroup','$country','$adress','$specialisation','$email','$username','$password','$password2', NOW())"; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } echo "Entered data successfully\n"; } mysql_close($conn); ?&gt; </code></pre> <h1>loginForm.php</h1> <pre><code> &lt;?php require_once('Connections/conn.php'); ?&gt; &lt;?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION &lt; 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } ?&gt; &lt;?php // *** Validate request to login to this site. if (!isset($_SESSION)) { session_start(); } $loginFormAction = $_SERVER['PHP_SELF']; if (isset($_GET['accesscheck'])) { $_SESSION['PrevUrl'] = $_GET['accesscheck']; } if (isset($_POST['username'])) { $loginUsername=$_POST['username']; $password=$_POST['password']; $MM_fldUserAuthorization = ""; $MM_redirectLoginSuccess = "profileForm.php"; $MM_redirectLoginFailed = "registerForm.php"; $MM_redirecttoReferrer = false; mysql_select_db($database_conn, $conn); $LoginRS__query=sprintf("SELECT username, password FROM users WHERE username=%s AND password=%s", GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); $LoginRS = mysql_query($LoginRS__query, $conn) or die(mysql_error()); $loginFoundUser = mysql_num_rows($LoginRS); if ($loginFoundUser) { $loginStrGroup = ""; if (PHP_VERSION &gt;= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();} //declare two session variables and assign them $_SESSION['MM_Username'] = $loginUsername; $_SESSION['MM_UserGroup'] = $loginStrGroup; if (isset($_SESSION['PrevUrl']) &amp;&amp; false) { $MM_redirectLoginSuccess = $_SESSION['PrevUrl']; } header("Location: " . $MM_redirectLoginSuccess ); } else { header("Location: ". $MM_redirectLoginFailed ); } } ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;/head&gt; &lt;!--link CSS--&gt; &lt;link href="style/stylesheet.css" rel="stylesheet" type="text/css" /&gt; &lt;body&gt; &lt;!--&lt;?php require_once('header.php'); ?&gt;--&gt; &lt;div id="loginForm"&gt;&lt;table width="250" border="0" align="right"&gt; &lt;form id="loginForm" name="loginForm" method="POST" action="&lt;?php echo $loginFormAction; ?&gt;"&gt; &lt;tr&gt; &lt;td&gt;&lt;label for="username"&gt;User Name&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="username" id="username" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label for="password"&gt;Password&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="password" id="password" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td bgcolor="#FFFFFF"&gt;&lt;input type="submit" name="login" id="login" value="Log In" /&gt; &lt;a href="registerForm.php"&gt;&lt;strong&gt; Register&lt;/strong&gt;&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/form&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php require_once('footer.php'); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <h1>profileForm.php</h1> <p> Profile Page </p> <pre><code>&lt;body&gt; &lt;?php require_once('header.php'); ?&gt; &lt;?php $con = mysql_connect("localhost","root","root"); if(!$con) { die('Could not connect: '.mysql_error()); } mysql_select_db("testregister",$con); $username =(isset($_POST['username'])); $result =mysql_query("Select * from users"); while ($row=mysql_fetch_array($result)) { echo "&lt;table border='0'&gt; &lt;tr&gt; &lt;td&gt; First Name: &lt;/td&gt; &lt;td&gt;" .$row['firstname'] ." &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; Last Name: &lt;/td&gt; &lt;td&gt;" .$row['lastname'] ." &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; Birth Date: &lt;/td&gt; &lt;td&gt;".$row['birthdate'] ." &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; Phone Number: &lt;/td&gt; &lt;td&gt; ".$row['phonenumber'] ." &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; Gender: &lt;/td&gt; &lt;td&gt; ".$row['gender'] ." &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; Country: &lt;/td&gt; &lt;td&gt;".$row['country'] ."&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; Specialization: &lt;/td&gt; &lt;td&gt;".$row['specialisation'] ."&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; Email: &lt;/td&gt; &lt;td&gt;".$row['email'] ."&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; User Name: &lt;/td&gt; &lt;td&gt;".$row['username'] ."&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; Join Date: &lt;/td&gt; &lt;td&gt;".$row['joindate'] ."&lt;/td&gt; &lt;/tr&gt;"; } echo "&lt;/table&gt;"; mysql_close ($con); ?&gt; &lt;html&gt; &lt;body&gt; Login Successful &lt;p&gt;&lt;a href="logout.php\"&gt;Click here to logout!&lt;/a&gt;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1
6,780
iOS Undefined symbols for architecture x86_64 Xcode
<p>I have installed some third party frameworks in my app. Every thing was working fine and suddenly one day i started to get the following errors. Please note that these linker errors appear only when i try to run my app on iOS Simulator.</p> <pre><code>Undefined symbols for architecture x86_64: "_AFNetworkingOperationFailingURLResponseDataErrorKey", referenced from: ___61-[DataManager signupWithEmail:password:name:success:failure:]_block_invoke.127 in DataManager.o ___46-[DataManager favoriteLesson:success:failure:]_block_invoke.311 in DataManager.o ___48-[DataManager unfavoriteLesson:success:failure:]_block_invoke.345 in DataManager.o "_AFStringFromNetworkReachabilityStatus", referenced from: ___41-[DataManager startObservingReachability]_block_invoke in DataManager.o "_OBJC_CLASS_$_ADJConfig", referenced from: objc-class-ref in AppDelegate.o "_OBJC_CLASS_$_ADJEvent", referenced from: objc-class-ref in TrackingHelper.o "_OBJC_CLASS_$_AFCompoundResponseSerializer", referenced from: objc-class-ref in DataManager.o "_OBJC_CLASS_$_AFHTTPRequestSerializer", referenced from: objc-class-ref in DataManager.o "_OBJC_CLASS_$_AFHTTPResponseSerializer", referenced from: objc-class-ref in DataManager.o "_OBJC_CLASS_$_AFHTTPSessionManager", referenced from: objc-class-ref in DataManager.o "_OBJC_CLASS_$_AFJSONRequestSerializer", referenced from: objc-class-ref in DataManager.o "_OBJC_CLASS_$_AFJSONResponseSerializer", referenced from: objc-class-ref in DataManager.o "_OBJC_CLASS_$_AFNetworkReachabilityManager", referenced from: objc-class-ref in DataManager.o "_OBJC_CLASS_$_AFURLSessionManager", referenced from: objc-class-ref in DataManager.o "_OBJC_CLASS_$_AMTagView", referenced from: objc-class-ref in CategorySelectionViewController.o "_OBJC_CLASS_$_Adjust", referenced from: objc-class-ref in AppDelegate.o objc-class-ref in TrackingHelper.o "_OBJC_CLASS_$_CarbonTabSwipeNavigation", referenced from: objc-class-ref in MyProfileViewController.o objc-class-ref in SearchResultsContainerViewController.o "_OBJC_CLASS_$_FBSDKAccessToken", referenced from: objc-class-ref in SignUpViewController.o objc-class-ref in MyProfileViewController.o "_OBJC_CLASS_$_FBSDKAppEvents", referenced from: objc-class-ref in AppDelegate.o "_OBJC_CLASS_$_FBSDKApplicationDelegate", referenced from: objc-class-ref in AppDelegate.o "_OBJC_CLASS_$_FBSDKLoginManager", referenced from: objc-class-ref in SignUpViewController.o objc-class-ref in DataManager.o objc-class-ref in LoginViewController.o "_OBJC_CLASS_$_MGSwipeButton", referenced from: objc-class-ref in LessonsViewController.o "_OBJC_CLASS_$_MGSwipeTableCell", referenced from: _OBJC_CLASS_$_LessonTableViewCell in LessonTableViewCell.o "_OBJC_CLASS_$_Mixpanel", referenced from: objc-class-ref in AppDelegate.o objc-class-ref in InitialViewController.o objc-class-ref in DataManager.o "_OBJC_CLASS_$_WYPopoverController", referenced from: objc-class-ref in GuideViewController.o "_OBJC_METACLASS_$_MGSwipeTableCell", referenced from: _OBJC_METACLASS_$_LessonTableViewCell in LessonTableViewCell.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) </code></pre> <p>Any help will be highly appreciated. I can debug, build and archive my project, if i do it on actual device but not on simulator. I have added all these frameworks via cocapods and i am using Xcode 7.3.</p>
1
1,295
ARM Cortex-a9 event counters return 0
<p>I'm currently trying to use the event counters on an ARM Cortex-a9 (on a Xilinx zynq EPP) to count cycles. I've adapted some ARM example code from ARM for this purpose. I'm programming this bare-metal with the GNU ARM EABI compiler.</p> <p>The way I understand the use of the PMU is that you first have to enable the PMU.</p> <pre><code>void enable_pmu (void){ asm volatile( "MRC p15, 0, r0, c9, c12, 0\n\t" "ORR r0, r0, #0x01\n\t" "MCR p15, 0, r0, c9, c12, 0\n\t" ); } </code></pre> <p>then you configure the performance counter to count a certain type of event (<code>0x11</code> for cycles in this case)</p> <pre><code>void config_pmn(unsigned counter,int event){ asm volatile( "AND %[counter], %[counter], #0x1F\n\t" :: [counter] "r" (counter)); //Mask to leave only bits 4:0 asm volatile( "MCR p15, 0, %[counter], c9, c12, 5\n\t" :: [counter] "r" (counter)); //Write PMSELR Register asm volatile( "ISB\n\t"); //Synchronize context asm volatile( "MCR p15, 0, %[event], c9, c13, 1\n\t" :: [event] "r" (counter)); //Write PMXEVTYPER Register } </code></pre> <p>Then you enable the event counter</p> <pre><code>void enable_pmn(int counter){ asm volatile( "MOV r1, #0x1\n\t"); asm volatile( "MOV r1, r1, LSL %[counter]\n\t" :: [counter] "r" (counter)); asm volatile( "MCR p15, 0, r1, c9, c12, 1\n\t"); //Write PMCNTENSET Register } </code></pre> <p>after this you immediately reset the event counter</p> <pre><code>void reset_pmn(void){ asm volatile( "MRC p15, 0, r0, c9, c12, 0\n\t"); //Read PMCR asm volatile( "ORR r0, r0, #0x2\n\t"); //Set P bit (Event counter reset) asm volatile( "MCR p15, 0, r0, c9, c12, 0\n\t"); //Write PMCR } </code></pre> <p>you let your application run and read the event counter</p> <pre><code>int read_pmn(int counter){ int value; asm volatile( "AND %0,%0, #0x1F\n\t" :: "r" (counter)); //Mask to leave only bits 4:0 asm volatile( "MCR p15, 0, %[counter], c9, c12, 5\n\t" ::[counter] "r" (counter)); //Write PMSELR Register asm volatile( "ISB\n\t"); //Synchronize context asm volatile( "MRC p15, 0,%[value] , c9, c13, 2\n\t" : [value] "=r" (value)); //Read current PMNx Register return value; } </code></pre> <p>and then you disable the event counter</p> <pre><code>void disable_pmn(int counter){ asm volatile( "MOV r1, #0x1\n\t"); asm volatile( "MOV r1, r1, LSL %[counter] \n\t":: [counter] "r" (counter)); asm volatile( "MCR p15, 0, r1, c9, c12, 2\n\t"); //Write PMCNTENCLR Register } </code></pre> <p>and the pmu.</p> <pre><code>void disable_pmu (void){ asm volatile( "MRC p15, 0, r0, c9, c12, 0\n\t" "BIC r0, r0, #0x01\n\t" "MCR p15, 0, r0, c9, c12, 0\n\t" ); } </code></pre> <p>However when I try to read the value stored in the event counter I get 0. I know my PMU is configured correctly because I'm able to read the cycle counter (<code>PMCCNTR</code>) without a problem. Probably there is a problem with the way I configure the counter or the way I read it. This inline assembly stuff is pretty new to me so if somebody can point me in the right direction I would be forever grateful.</p>
1
1,680
YouCompleteMe unavailable: unable to load Python
<p>I use Linux CentOS-7-x86_64 and am trying to install YouCompleteMe with vundle. I get the error:</p> <pre><code>YouCompleteMe unavailable: unable to load Python. </code></pre> <p>however, when I type <code>vim --version</code> I get:</p> <pre><code>VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Apr 13 2020 22:48:56) Included patches: 1-577 Compiled by louqinjian@localhost.localdomain Huge version without GUI. Features included (+) or not (-): +acl -farsi +mouse_sgr +tag_binary +arabic +file_in_path -mouse_sysmouse -tag_old_static +autocmd +find_in_path +mouse_urxvt -tag_any_white +autochdir +float +mouse_xterm -tcl -autoservername +folding +multi_byte +termguicolors -balloon_eval -footer +multi_lang +terminal +balloon_eval_term +fork() -mzscheme +terminfo -browse +gettext +netbeans_intg +termresponse ++builtin_terms -hangul_input +num64 +textobjects +byte_offset +iconv +packages +textprop +channel +insert_expand +path_extra +timers +cindent +ipv6 +perl +title -clientserver +job +persistent_undo -toolbar -clipboard +jumplist +popupwin +user_commands +cmdline_compl +keymap +postscript +vartabs +cmdline_hist +lambda +printer +vertsplit +cmdline_info +langmap +profile +virtualedit +comments +libcall +python/dyn +visual +conceal +linebreak +python3/dyn +visualextra +cryptv +lispindent +quickfix +viminfo +cscope +listcmds +reltime +vreplace +cursorbind +localmap +rightleft +wildignore +cursorshape +lua +ruby +wildmenu +dialog_con +menu +scrollbind +windows +diff +mksession +signs +writebackup +digraphs +modify_fname +smartindent -X11 -dnd +mouse -sound -xfontset -ebcdic -mouseshape +spell -xim +emacs_tags +mouse_dec +startuptime -xpm +eval -mouse_gpm +statusline -xsmp +ex_extra -mouse_jsbterm -sun_workshop -xterm_clipboard +extra_search +mouse_netterm +syntax -xterm_save system vimrc file: "$VIM/vimrc" user vimrc file: "$HOME/.vimrc" 2nd user vimrc file: "~/.vim/vimrc" user exrc file: "$HOME/.exrc" defaults file: "$VIMRUNTIME/defaults.vim" fall-back for $VIM: "/usr/local/share/vim" Compilation: gcc -std=gnu99 -c -I. -Iproto -DHAVE_CONFIG_H -g -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 Linking: gcc -std=gnu99 -L. -Wl,-z,relro -fstack-protector -rdynamic -Wl,-export-dynamic -Wl,--enable-new-dtags -Wl,-rpath,/usr/lib64/perl5/CORE -L/usr/local/lib -Wl,--as-needed -o vim -lm -ltinfo -lselinux -ldl -L/usr/lib -llua -Wl,--enable-new-dtags -Wl,-rpath,/usr/lib64/perl5/CORE -fstack-protector -L/usr/lib64/perl5/CORE -lperl -lresolv -lnsl -ldl -lm -lcrypt -lutil -lpthread -lc -lruby -lpthread -lrt -ldl -lcrypt -lm </code></pre> <p>And, when I install vim with <code>.configure</code>, I include</p> <pre><code>--with-features=huge --enable-python3interp --enable-pythoninterp </code></pre> <p>What can I do to solve this?</p>
1
1,965
populating a list view with sql database items
<p>My application is based on displaying a dialog box when the user enters the "add category" button. It then should save data into an SQL Database and populate a list view with each item the user adds. I chose SQL database because I want the data to be saved when the user ends the app. How do I actually populate the list view with those items ? Here is what I have so far:</p> <pre><code>public class CategoryDatabase { public static final String KEY_ROWID = "_id"; public static final String KEY_CATEGORY = "category"; private static final String DATABASE_NAME = "DBCategory"; private static final String DATABASE_TABLE = "categoryTable"; private static final int DATABASE_VERSION = 1; private DbHelper ourHelper; private final Context ourContext; private SQLiteDatabase ourDatabase; public CategoryDatabase(Context c){ ourContext = c; } public CategoryDatabase open() throws SQLException{ ourHelper = new DbHelper(ourContext); ourDatabase = ourHelper.getWritableDatabase(); return this; } public void close(){ ourHelper.close(); } private static class DbHelper extends SQLiteOpenHelper{ public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_CATEGORY + " TEXT NOT NULL);" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); onCreate(db); } } public long createEntry(String category) { ContentValues cv = new ContentValues(); cv.put(KEY_CATEGORY, category); return ourDatabase.insert(DATABASE_TABLE, null, cv); } } </code></pre> <p>and the Main Activity:</p> <pre><code>public class MainActivity extends Activity { final Context context = this; ArrayAdapter&lt;String&gt; arrayAdapter; ArrayList&lt;String&gt; listItems = new ArrayList&lt;String&gt;(); ListView lv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); lv = (ListView)findViewById(R.id.listView1); arrayAdapter = new ArrayAdapter&lt;String&gt;(this,android.R.layout.simple_list_item_1, listItems); lv.setAdapter(arrayAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ case R.id.menu_add_cat: LayoutInflater li = LayoutInflater.from(context); View promptAdd = li.inflate(R.layout.prompt_add, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); //set prompts.xml to alertDialogBuilder alertDialogBuilder.setView(promptAdd); final EditText etAddCat = (EditText)promptAdd.findViewById(R.id.etDialogInput); //set a dialog message alertDialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /* * add a cat here * if(null != input &amp;&amp; input.length() &gt; 0){ listItems.add(input); arrayAdapter.notifyDataSetChanged(); }else{ Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show(); } */ boolean didItWork = true; try{ String category = etAddCat.getText().toString(); CategoryDatabase entry = new CategoryDatabase(MainActivity.this); entry.open(); entry.createEntry(category); entry.close(); }catch(Exception e){ didItWork = false; String error = e.toString(); Dialog d = new Dialog(MainActivity.this); d.setTitle("Dang it ! "); TextView tv = new TextView(MainActivity.this); tv.setText(error); d.setContentView(tv); d.show(); }finally{ if(didItWork){ Dialog d = new Dialog(MainActivity.this); d.setTitle("Heck yea ! "); TextView tv = new TextView(MainActivity.this); tv.setText("Success"); d.setContentView(tv); d.show(); } } } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); break; } //return super.onOptionsItemSelected(item); return true; } }// end of MainActivity </code></pre>
1
2,384
Spring Security Core Plugin 2.0-RC2 upgrade issue?
<p>I have a grails project and I just upgraded my Spring Security Core plugin to the latest version however I get the following message when trying to run the app:</p> <pre><code>| Error Compilation error: startup failed: Compile error during compilation with javac. /home/dev/.grails/2.1.0/projects/app/plugins/spring-security-ldap-1.0.6/src/java/org/codehaus/groovy/grails/plugins/springsecurity/ldap/DatabaseOnlyLdapAuthoritiesPopulator.java:20: cannot find symbol symbol : class GrailsUserDetailsService location: package org.codehaus.groovy.grails.plugins.springsecurity import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserDetailsService; ^ /home/dev/.grails/2.1.0/projects/app/plugins/spring-security-ldap-1.0.6/src/java/org/codehaus/groovy/grails/plugins/springsecurity/ldap/DatabaseOnlyLdapAuthoritiesPopulator.java:37: cannot find symbol symbol : class GrailsUserDetailsService location: class org.codehaus.groovy.grails.plugins.springsecurity.ldap.DatabaseOnlyLdapAuthoritiesPopulator private GrailsUserDetailsService _userDetailsService; ^ /home/dev/.grails/2.1.0/projects/app/plugins/spring-security-ldap-1.0.6/src/java/org/codehaus/groovy/grails/plugins/springsecurity/ldap/DatabaseOnlyLdapAuthoritiesPopulator.java:71: cannot find symbol symbol : class GrailsUserDetailsService location: class org.codehaus.groovy.grails.plugins.springsecurity.ldap.DatabaseOnlyLdapAuthoritiesPopulator public void setUserDetailsService(final GrailsUserDetailsService service) { ^ /home/dev/.grails/2.1.0/projects/app/plugins/spring-security-ldap-1.0.6/src/java/org/codehaus/groovy/grails/plugins/springsecurity/ldap/GrailsLdapAuthoritiesPopulator.java:20: cannot find symbol symbol : class GrailsUserDetailsService location: package org.codehaus.groovy.grails.plugins.springsecurity import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserDetailsService; ^ /home/dev/.grails/2.1.0/projects/app/plugins/spring-security-ldap-1.0.6/src/java/org/codehaus/groovy/grails/plugins/springsecurity/ldap/GrailsLdapAuthoritiesPopulator.java:36: cannot find symbol symbol : class GrailsUserDetailsService location: class org.codehaus.groovy.grails.plugins.springsecurity.ldap.GrailsLdapAuthoritiesPopulator private GrailsUserDetailsService _userDetailsService; ^ /home/dev/.grails/2.1.0/projects/app/plugins/spring-security-ldap-1.0.6/src/java/org/codehaus/groovy/grails/plugins/springsecurity/ldap/GrailsLdapAuthoritiesPopulator.java:147: cannot find symbol symbol : class GrailsUserDetailsService location: class org.codehaus.groovy.grails.plugins.springsecurity.ldap.GrailsLdapAuthoritiesPopulator public void setUserDetailsService(final GrailsUserDetailsService service) { ^ /home/dev/.grails/2.1.0/projects/app/plugins/spring-security-ldap-1.0.6/src/java/org/codehaus/groovy/grails/plugins/springsecurity/ldap/GrailsLdapUserDetailsManager.java:3: cannot find symbol symbol : class GrailsUserDetailsService location: package org.codehaus.groovy.grails.plugins.springsecurity import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserDetailsService; ^ /home/dev/.grails/2.1.0/projects/app/plugins/spring-security-ldap-1.0.6/src/java/org/codehaus/groovy/grails/plugins/springsecurity/ldap/GrailsLdapUserDetailsManager.java:13: cannot find symbol symbol: class GrailsUserDetailsService public class GrailsLdapUserDetailsManager extends LdapUserDetailsManager implements GrailsUserDetailsService { ^ Note: Some input files use or override a deprecated API. Note: Recompile with -Xlint:deprecation for details. 8 errors </code></pre> <p>Can someone please help with this?</p> <p>Thanks</p> <hr> <p><em><strong></em>**</strong><em>EDIT</em><strong><em>*</em>**<em>*</em></strong></p> <hr> <p>I have now gone through the plugins and core files and made sure all new Spring Security imports are correct. The app now compiles fine however when I run it and try to access the home page I get the following errors:</p> <pre><code>| Running Grails application Configuring Spring Security UI ... ... finished configuring Spring Security UI Configuring Spring Security Core ... ... finished configuring Spring Security Core | Error 2014-03-10 11:44:51,598 [pool-7-thread-1] ERROR plugins.DefaultGrailsPluginManager - Error configuring dynamic methods for plugin [springSecurityCore:2.0-RC2]: null Message: null Line | Method -&gt;&gt; 308 | compileStaticRules in grails.plugin.springsecurity.web.access.intercept.AnnotationFilterInvocationDefinition - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | 218 | initialize in '' | 738 | initializeFromAnnotations in SpringSecurityCoreGrailsPlugin | 599 | doCall in SpringSecurityCoreGrailsPlugin$_closure3 | 303 | innerRun . . . . . . . . in java.util.concurrent.FutureTask$Sync | 138 | run in java.util.concurrent.FutureTask | 895 | runTask . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker | 918 | run in '' ^ 662 | run . . . . . . . . . . . in java.lang.Thread | Server running. Browse to http://localhost:8080/my_app | Error 2014-03-10 11:49:36,541 [http-bio-8080-exec-2] ERROR [/my_app].[gsp] - Servlet.service() for servlet [gsp] in context with path [/my_app] threw exception Message: null Line | Method -&gt;&gt; 273 | isAjax in grails.plugin.springsecurity.SpringSecurityUtils - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | 45 | determineUrlToUseForThisRequest in grails.plugin.springsecurity.web.authentication.AjaxAwareAuthenticationEntryPoint | 53 | doFilter . . . . . . . . . . . in grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter | 49 | doFilter in grails.plugin.springsecurity.web.authentication.RequestHolderAuthenticationFilter | 82 | doFilter . . . . . . . . . . . in grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter | 895 | runTask in java.util.concurrent.ThreadPoolExecutor$Worker | 918 | run . . . . . . . . . . . . . . in '' ^ 662 | run in java.lang.Thread </code></pre> <p>Can someone please offer any guidance on this?</p> <p>Thanks</p>
1
2,575
Aggregate Function/Group-By Query Performance
<p>This query works (thanks to those that helped) to generate a 30-day moving average of volume.</p> <pre><code>SELECT x.symbol, x.dseqkey, AVG(y.VOLUME) moving_average FROM STOCK_HIST x, STOCK_HIST y WHERE x.dseqkey&gt;=29 AND x.dseqkey BETWEEN y.dseqkey AND y.dseqkey+29 AND Y.Symbol=X.Symbol GROUP BY x.symbol, x.dseqkey ORDER BY x.dseqkey DESC </code></pre> <p>However the performance is very bad. I am running the above against a view (STOCK_HIST) that brings two tables (A and B) together. Table A contains daily stock volume and the daily date for over 9,000 stocks dating back as far as 40 years (300+ rows, per year, per each of the 9,000 stocks). Table B is a "Date Key" table that links the date in table A to the DSEQKEY (int). </p> <p>What are my options for performance improvement? I have heard that views are convenient but not performant. Should I just copy the columns needed from table A and B to a single table and then run the above query? I have indexes on the tables A and B on the stock symbol + date (A) and DSEQKEY (B). </p> <p>Is it the view that's killing my performance? How can I improve this? </p> <p><strong>EDIT</strong></p> <p>By request, I have posted the 2 tables and the view below. Also, now there is one clustered index on the view and each table. I am open to any recommendations as this query that produces the deisred result, is still slow:</p> <pre><code>SELECT x.symbol , x.dseqkey , AVG(y.VOLUME) moving_average FROM STOCK_HIST x JOIN STOCK_HIST y ON x.dseqkey BETWEEN y.dseqkey AND y.dseqkey+29 AND Y.Symbol=X.Symbol WHERE x.dseqkey &gt;= 15000 GROUP BY x.symbol, x.dseqkey ORDER BY x.dseqkey DESC ; </code></pre> <p>HERE IS THE VIEW:</p> <pre><code>CREATE VIEW [dbo].[STOCK_HIST] WITH SCHEMABINDING AS SELECT dbo.DATE_MASTER.date , dbo.DATE_MASTER.year , dbo.DATE_MASTER.quarter , dbo.DATE_MASTER.month , dbo.DATE_MASTER.week , dbo.DATE_MASTER.wday , dbo.DATE_MASTER.day , dbo.DATE_MASTER.nday , dbo.DATE_MASTER.wkmax , dbo.DATE_MASTER.momax , dbo.DATE_MASTER.qtrmax , dbo.DATE_MASTER.yrmax , dbo.DATE_MASTER.dseqkey , dbo.DATE_MASTER.wseqkey , dbo.DATE_MASTER.mseqkey , dbo.DATE_MASTER.qseqkey , dbo.DATE_MASTER.yseqkey , dbo.DATE_MASTER.tom , dbo.QP_HISTORY.Symbol , dbo.QP_HISTORY.[Open] as propen , dbo.QP_HISTORY.High as prhigh , dbo.QP_HISTORY.Low as prlow , dbo.QP_HISTORY.[Close] as prclose , dbo.QP_HISTORY.Volume , dbo.QP_HISTORY.QRS FROM dbo.DATE_MASTER INNER JOIN dbo.QP_HISTORY ON dbo.DATE_MASTER.date = dbo.QP_HISTORY.QPDate ; </code></pre> <p>HERE IS DATE_MASTER TABLE:</p> <pre><code>CREATE TABLE [dbo].[DATE_MASTER] ( [date] [datetime] NULL , [year] [int] NULL , [quarter] [int] NULL , [month] [int] NULL , [week] [int] NULL , [wday] [int] NULL , [day] [int] NULL , [nday] nvarchar NULL , [wkmax] [bit] NOT NULL , [momax] [bit] NOT NULL , [qtrmax] [bit] NOT NULL , [yrmax] [bit] NOT NULL , [dseqkey] [int] IDENTITY(1,1) NOT NULL , [wseqkey] [int] NULL , [mseqkey] [int] NULL , [qseqkey] [int] NULL , [yseqkey] [int] NULL , [tom] [bit] NOT NULL ) ON [PRIMARY] ; </code></pre> <p>HERE IS THE QP_HISTORY TABLE:</p> <pre><code>CREATE TABLE [dbo].[QP_HISTORY] ( [Symbol] varchar NULL , [QPDate] [date] NULL , [Open] [real] NULL , [High] [real] NULL , [Low] [real] NULL , [Close] [real] NULL , [Volume] [bigint] NULL , [QRS] [smallint] NULL ) ON [PRIMARY] ; </code></pre> <p>HERE IS THE VIEW (STOCK_HIST) INDEX</p> <pre><code>CREATE UNIQUE CLUSTERED INDEX [ix_STOCK_HIST] ON [dbo].[STOCK_HIST] ( [Symbol] ASC, [dseqkey] ASC, [Volume] ASC ) </code></pre> <p>HERE IS THE QP_HIST INDEX</p> <pre><code>CREATE UNIQUE CLUSTERED INDEX [IX_QP_HISTORY] ON [dbo].[QP_HISTORY] ( [Symbol] ASC, [QPDate] ASC, [Close] ASC, [Volume] ASC ) </code></pre> <p>HERE IS THE INDEX ON DATE_MASTER</p> <pre><code>CREATE UNIQUE CLUSTERED INDEX [IX_DATE_MASTER] ON [dbo].[DATE_MASTER] ( [date] ASC, [dseqkey] ASC, [wseqkey] ASC, [mseqkey] ASC ) </code></pre> <p>I do not have any primary keys setup. Would this help performance?</p> <p><strong>EDIT</strong> - After making suggested changes the query is slower than before. What ran in 10m 44s is currently at 30m and still running.</p> <p>I made all of the requested changes except I did not change name of date in Date_Master and I did not drop the QPDate column from QP_Hist. (I have reasons for this and do not see it impacting the performance since I'm not referring to it in the query.)</p> <p>REVISED QUERY</p> <pre><code>select x.symbol, x.dmdseqkey, avg(y.volume) as moving_average from dbo.QP_HISTORY as x join dbo.QP_HISTORY as y on (x.dmdseqkey between y.dmdseqkey and (y.dmdseqkey + 29)) and (y.symbol = x.symbol) where x.dmdseqkey &gt;= 20000 group by x.symbol, x.dmdseqkey order by x.dmdseqkey desc ; </code></pre> <p>PK on QP_History</p> <pre><code>ALTER TABLE [dbo].[QP_HISTORY] ADD CONSTRAINT [PK_QP_HISTORY] PRIMARY KEY CLUSTERED ([Symbol] ASC, DMDSeqKey] ASC) </code></pre> <p>FK on QP_History</p> <pre><code>ALTER TABLE [dbo].[QP_HISTORY] ADD CONSTRAINT [FK_QP_HISTORY_DATE_MASTER] FOREIGN KEY([DMDSeqKey]) REFERENCES [dbo].[DATE_MASTER] ([dseqkey]) </code></pre> <p>PK on Date_Master</p> <pre><code>ALTER TABLE [dbo].[DATE_MASTER] ADD CONSTRAINT [PK_DATE_MASTER] PRIMARY KEY CLUSTERED ([dseqkey] ASC) </code></pre> <p>EDIT </p> <p>HERE IS THE EXECUTION PLAN</p>
1
2,559
Building a social network using Firebase
<p>I'm currently developing basic social network Android app for sharing images. Already have PHP/mySQL back-end but thinking about migrating to Firebase because of some features that I like (e.g. security, fast read/write).</p> <p>So, I have <code>users</code>, <code>posts</code>, <code>followers</code>, <code>likes</code>, <code>comments</code> (like every other social network nowadays).</p> <p>Long story short, I want to know if I'm getting this right. According to <a href="https://firebase.google.com/docs/database/android/structure-data#fanout" rel="nofollow noreferrer">this Firebase documentation</a> and its example I should include unique keys from some JSON trees to others like this (example from documentation):</p> <pre><code>// An index to track Ada's memberships { "users": { "alovelace": { "name": "Ada Lovelace", // Index Ada's groups in her profile "groups": { // the value here doesn't matter, just that the key exists "techpioneers": true, "womentechmakers": true } }, ... }, "groups": { "techpioneers": { "name": "Historical Tech Pioneers", "members": { "alovelace": true, "ghopper": true, "eclarke": true } }, ... } } </code></pre> <p>Does this mean that I will have to include keys from posts, comments, followers etc. to my users tree like this:</p> <pre><code>{ "users": { "alovelace": { "name": "Ada Lovelace", "profileImage": "http://blabla.bla?xyzooqlL.png", "about:" : "Exit light, enter night", "country": "Neverland" // Index Ada's posts in her profile "posts": { // the value here doesn't matter, just that the key exists "post123": true, "post234": true }, // all comments this user wrote "comments": { "comment123": true }, // all posts this user liked "likes": { "post123": true }, "followers": { "user123": true, "user234": true } }, ... }, "posts": { "post123": { "image": "www.bla.bla/sadsadsa.png", "description": "Hue hue hue", "likes": { "alovelace": true, "ghopper": true, "eclarke": true }, "comments": { "comment123": true, } }, "post234": { "image": "www.bla.bla/233arweeq.png", "description": "This is nice", "likes": { "eclarke": true }, "comments": { "comment234": true, } }, "comments": { "comment123": { "userId": "alovelace" "text": "cool", "date": "current" } }, ... } } </code></pre> <p>Isn't it a little too much if I have for example 5000 followers, 2000 followings, 1500 post likes? <strong>When fetching user or any other object I will also fetch all its keys within that object</strong>. Imagine fetching 15 very active users with all this data.</p> <p>If you have any suggestions how should I structure data, please let me know. <strong>Any kind of feedback will be useful.</strong></p> <p>Thanks.</p>
1
1,296
Why is my tab layout for android not working?
<p>I am trying to make a tab sliding activity for my app but I am not able to find what is going wrong.</p> <p>Here is the code for the tab activity:</p> <pre><code>public class TabActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tab); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ViewPager viewPager = findViewById(R.id.container); viewPager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager())); TabLayout tabLayout = findViewById(R.id.tabs); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_tab, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public static abstract class LayoutFragment extends Fragment { private final int layout; public LayoutFragment(@LayoutRes int layout) { this.layout = layout; } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(layout, container, false); } @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } } public static class Fragment1 extends LayoutFragment { public Fragment1() { super(R.layout.fragment_one); } } public static class Fragment2 extends Fragment { public Fragment2() { super(R.layout.fragment_two); } } public class SectionsPagerAdapter extends FragmentPagerAdapter { SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. switch (position) { case 0: return new Fragment1(); default: return new Fragment2(); } } @Override public int getCount() { return 2; } } } </code></pre> <p>The code is compiling perfectly but the tabs for fragment1 and fragment2 are not appearing at all.</p> <p>I am not able to figure out what's going wrong and where, I would appreciate any help.</p> <p><strong>Edit:</strong></p> <p>Here is my XML code:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/wallpaper" android:fitsSystemWindows="true" tools:context=".TabActivity"&gt; &lt;com.google.android.material.appbar.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="@dimen/appbar_padding_top" android:theme="@style/AppTheme.AppBarOverlay"&gt; &lt;androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:layout_weight="1" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/AppTheme.PopupOverlay" app:title="@string/app_name"&gt; &lt;/androidx.appcompat.widget.Toolbar&gt; &lt;com.google.android.material.tabs.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;com.google.android.material.tabs.TabItem android:id="@+id/tabItem" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tab1" /&gt; &lt;com.google.android.material.tabs.TabItem android:id="@+id/tabItem2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tab2" /&gt; &lt;/com.google.android.material.tabs.TabLayout&gt; &lt;/com.google.android.material.appbar.AppBarLayout&gt; &lt;androidx.viewpager.widget.ViewPager android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /&gt; </code></pre> <p></p>
1
1,983
Jenkins slave on Kubernetes fails to connect tcpSlaveAgentListener/:
<p>I am trying to use K8s to set up a Jenkins slave, passing correct agent name and secret but tries to connect to a weird url:</p> <p>Keeps creating slaves and removing them with the exact same logs.</p> <p>Master logs:</p> <pre><code>2020-02-03 21:20:39.980+0000 [id=26] INFO o.c.j.p.k.KubernetesCloud#provision: Template for label slave: jenkins-slave 2020-02-03 21:20:50.005+0000 [id=31] INFO hudson.slaves.NodeProvisioner#lambda$update$6: Kubernetes Pod Template provisioning successfully completed. We have now 3 computer(s) 2020-02-03 21:20:50.026+0000 [id=26914] INFO o.c.j.p.k.KubernetesLauncher#launch: Created Pod: toks1/jenkins-slave-ncn4x 2020-02-03 21:20:54.547+0000 [id=26922] INFO h.TcpSlaveAgentListener$ConnectionHandler#run: Connection #122 failed: java.io.EOFException 2020-02-03 21:20:54.660+0000 [id=26923] INFO h.TcpSlaveAgentListener$ConnectionHandler#run: Accepted JNLP4-connect connection #123 from /10.128.0.1:41682 2020-02-03 21:20:54.864+0000 [id=26914] INFO o.c.j.p.k.KubernetesLauncher#launch: Pod is running: toks1/jenkins-slave-ncn4x 2020-02-03 21:20:54.867+0000 [id=26914] INFO o.c.j.p.k.KubernetesLauncher#launch: Waiting for agent to connect (0/100): jenkins-slave-ncn4x 2020-02-03 21:20:55.885+0000 [id=26914] INFO o.c.j.p.k.KubernetesLauncher#launch: Waiting for agent to connect (1/100): jenkins-slave-ncn4x 2020-02-03 21:20:56.891+0000 [id=26914] INFO o.c.j.p.k.KubernetesLauncher#launch: Container is terminated jenkins-slave-ncn4x [jnlp]: ContainerStateTerminated(containerID=docker://16631d7785e73264c48e814ae56c337293d7028102e5ce7845bdb8fd96664238, exitCode=255, finishedAt=2020-02-03T21:20:55Z, message=null, reason=Error, signal=null, startedAt=2020-02-03T21:20:53Z, additionalProperties={}) 2020-02-03 21:20:56.927+0000 [id=26914] SEVERE o.c.j.p.k.KubernetesLauncher#logLastLines: Error in provisioning; agent=KubernetesSlave name: jenkins-slave-ncn4x, template=PodTemplate{inheritFrom='', name='jenkins-slave', namespace='toks1', hostNetwork=false, label='slave', nodeSelector='', nodeUsageMode=EXCLUSIVE, workspaceVolume=EmptyDirWorkspaceVolume [memory=false], containers=[ContainerTemplate{name='slave', image='docker.io/fabstao/jenkins-okd-slave:3', alwaysPullImage=true, workingDir='/home/jenkins/agent', command='', args='', resourceRequestCpu='', resourceRequestMemory='', resourceLimitCpu='', resourceLimitMemory='', envVars=[KeyValueEnvVar [getValue()=http://jenkins-gtsmex:8080 , getKey()=JENKINS_URL], KeyValueEnvVar [getValue()=slave-gts, getKey()=JENKINS_AGENT_NAME], KeyValueEnvVar [getValue()=2a1be5874407a37957eeba186c228c756ac8dbc78f0c4edb735399d15834d5ca, getKey()=JENKINS_SECRET]], livenessProbe=org.csanchez.jenkins.plugins.kubernetes.ContainerLivenessProbe@70ba28dc}]}. Container jnlp exited with error 255. Logs: INFO: Using Remoting version: 3.35 Feb 03, 2020 9:20:54 PM org.jenkinsci.remoting.engine.WorkDirManager initializeWorkDir INFO: Using /home/jenkins/agent/remoting as a remoting work directory Feb 03, 2020 9:20:54 PM org.jenkinsci.remoting.engine.WorkDirManager setupLogging INFO: Both error and output logs will be printed to /home/jenkins/agent/remoting Feb 03, 2020 9:20:54 PM hudson.remoting.jnlp.Main$CuiListener status INFO: Locating server among [http://jenkins-gtsmex-toks1.toks1.default.svc.cluster.local/ ] Feb 03, 2020 9:20:54 PM hudson.remoting.jnlp.Main$CuiListener error SEVERE: Failed to connect to http://jenkins-gtsmex-toks1.toks1.default.svc.cluster.local/tcpSlaveAgentListener/: jenkins-gtsmex-toks1.toks1.default.svc.cluster.local java.io.IOException: Failed to connect to http://jenkins-gtsmex-toks1.toks1.default.svc.cluster.local/tcpSlaveAgentListener/: jenkins-gtsmex-toks1.toks1.default.svc.cluster.local at org.jenkinsci.remoting.engine.JnlpAgentEndpointResolver.resolve(JnlpAgentEndpointResolver.java:206) at hudson.remoting.Engine.innerRun(Engine.java:527) at hudson.remoting.Engine.run(Engine.java:488) Caused by: java.net.UnknownHostException: jenkins-gtsmex-toks1.toks1.default.svc.cluster.local at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at sun.net.NetworkClient.doConnect(NetworkClient.java:175) at sun.net.www.http.HttpClient.openServer(HttpClient.java:463) at sun.net.www.http.HttpClient.openServer(HttpClient.java:558) at sun.net.www.http.HttpClient.&lt;init&gt;(HttpClient.java:242) at sun.net.www.http.HttpClient.New(HttpClient.java:339) at sun.net.www.http.HttpClient.New(HttpClient.java:357) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1220) at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:984) at org.jenkinsci.remoting.engine.JnlpAgentEndpointResolver.resolve(JnlpAgentEndpointResolver.java:203) ... 2 more </code></pre> <p>Slave logs:</p> <pre><code>Feb 03, 2020 9:27:13 PM hudson.remoting.jnlp.Main createEngine INFO: Setting up agent: slave-gts Feb 03, 2020 9:27:13 PM hudson.remoting.jnlp.Main$CuiListener &lt;init&gt; INFO: Jenkins agent is running in headless mode. Feb 03, 2020 9:27:13 PM hudson.remoting.Engine startEngine INFO: Using Remoting version: 3.40 Feb 03, 2020 9:27:13 PM hudson.remoting.Engine startEngine WARNING: No Working Directory. Using the legacy JAR Cache location: /home/jenkins/.jenkins/cache/jars Feb 03, 2020 9:27:14 PM hudson.remoting.jnlp.Main$CuiListener status INFO: Locating server among [http://jenkins-gtsmex:8080 ] Feb 03, 2020 9:27:14 PM org.jenkinsci.remoting.engine.JnlpAgentEndpointResolver resolve INFO: Remoting server accepts the following protocols: [JNLP4-connect, Ping] Feb 03, 2020 9:27:14 PM hudson.remoting.jnlp.Main$CuiListener status INFO: Agent discovery successful Agent address: jenkins-gtsmex Agent port: 50000 Identity: f5:f7:64:eb:8c:aa:57:81:07:27:2e:38:e1:93:b7:e5 Feb 03, 2020 9:27:14 PM hudson.remoting.jnlp.Main$CuiListener status INFO: Handshaking Feb 03, 2020 9:27:14 PM hudson.remoting.jnlp.Main$CuiListener status INFO: Connecting to jenkins-gtsmex:50000 Feb 03, 2020 9:27:14 PM hudson.remoting.jnlp.Main$CuiListener status INFO: Trying protocol: JNLP4-connect Feb 03, 2020 9:27:14 PM hudson.remoting.jnlp.Main$CuiListener status INFO: Remote identity confirmed: f5:f7:64:eb:8c:aa:57:81:07:27:2e:38:e1:93:b7:e5 Feb 03, 2020 9:27:14 PM hudson.remoting.jnlp.Main$CuiListener status INFO: Connected </code></pre> <p>Kubernetes: Openshift OKD 3.11 Jenkins: 2.218</p> <p>Please help</p>
1
2,657
Using ZipStream in Symfony: streamed zip download will not decompress using Archive Utility on Mac OSX
<p>I have a symfony 2.8 application and on the user clicking "download" button, I use the keys of several large (images, video) files on s3 to stream this to the browser as a zip file using ZipStream (<a href="https://github.com/maennchen/ZipStream-PHP" rel="nofollow noreferrer">https://github.com/maennchen/ZipStream-PHP</a>).</p> <p>The streaming of files and download as a zip (stored, not compressed) is successful in the browser &amp; the zip lands in Downloads. However, when attempting to open the zip in Mac OSX El Capitan using Archive Utility (native archive software on OSX), it errors out. The Error:</p> <p><strong>Unable to expand "test.zip" into "Downloads". (Error 2 - No such file or directory.)</strong></p> <p>I have seen older, identical issues on SO and attempted those fixes, specifically this post: <a href="https://stackoverflow.com/a/5574305/136151">https://stackoverflow.com/a/5574305/136151</a> and followed up on the Issues &amp; PRs in ZipStream that relates and the upstream fixes in Guzzle etc.</p> <p>Problem is, the above fixes were back in 2011 and things move on in that time. So applying the same fixes I am not getting a working result.</p> <p>Specific fixes I have tried is: 1. Setting "version to extract" to 0x000A as suggested. Also as '20' as recommended in another post. I've set the same for "version made by". 2. I tried to force the compression method to 'deflate' instead of 'stored' to see if I got a working result. A stored resulted is all I need and suitable for a zip used as container file for images &amp; video.</p> <p>I am able to extract the zip using a third party archive app called The Unarchiver. However, users won't know &amp; can't be expected to install an alternative archive app to suit my web app. Thats not an effective solution.</p> <p>Does anyone have knowledge or experience of solving this issue and can help me out with how to resolve it?</p> <p>NB: A streamed zip to browser is the required solution. Downloading assets from s3 to the server to create a zip and then stream the resulting zip to the browser is not a solution given the amount of time and overhead of such an approach.</p> <p><strong>Added info if required:</strong></p> <p><strong>Code &amp; Setup:</strong> - Files are stored on s3. - Web app is symfony 2.8 on PHP7.0 runing on ec2 with Ubuntu. - Using aws-sdk-php, create an s3client with valid credentials and I register StreamWrapper (s3client->registerStreamWrapper()) on the s3client. This is to fetch files from s3 via fopen to stream to ZipStream library:</p> <pre><code>$this-&gt;s3Client = $s3Client; $this-&gt;s3Client-&gt;registerStreamWrapper(); // Initialize the ZipStream object and pass in the file name which // will be what is sent in the content-disposition header. // This is the name of the file which will be sent to the client. // Define suitable options for ZipStream Archive. $opt = array( 'comment' =&gt; 'test zip file.', 'content_type' =&gt; 'application/octet-stream' ); $zip = new ZipStream\ZipStream($filename, $opt); $keys = array( "zipsimpletestfolder/file1.txt" ); foreach ($keys as $key) { // Get the file name in S3 key so we can save it to the zip file // using the same name. $fileName = basename($key); $bucket = 'mg-test'; $s3path = "s3://" . $bucket . "/" . $key; if ($streamRead = fopen($s3path, 'r')) { $zip-&gt;addFileFromStream($fileName, $streamRead); } else { die('Could not open stream for reading'); } } $zip-&gt;finish(); </code></pre> <p><strong>Zip Output Results:</strong></p> <ul> <li><p>Extraction on mac via Archive Utility fails with error 2</p></li> <li><p>Extraction on mac with The unarchiver works.</p></li> <li><p>Extraction on windows with 7-zip works.</p></li> <li><p>Extraction on windows with WinRar fails - says zip is corrupted.</p></li> </ul> <p>Response Headers:</p> <p><a href="https://i.stack.imgur.com/7caXn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7caXn.png" alt="enter image description here"></a></p> <p><strong>Edit</strong> I'm open to using another method of streaming files to browser as a zip that can be opened on Mac, Windows, Linux natively without using ZipStream if suggested. Just not to creating a zip file server side to subsequently stream thereafter.</p>
1
1,393
How to build a ListView and fill it from the codebehind
<p>I want to fill my <code>ListView</code> from codebehind <em>and</em> want to know how to build the fields. I saw <a href="https://stackoverflow.com/q/11407221/1919644">this</a> example, and I'd like to now if the only way to build a <code>ListView</code>s fields is using tables. If not, what would be another way to do that? I tried only filling the <code>ListView</code> with datasource, like this:</p> <pre><code>ListView1.DataSource = ds; ListView1.DataBind(); </code></pre> <p>But it gave me an error: </p> <blockquote> <p>An ItemTemplate must be defined on ListView 'ListView1'.</p> </blockquote> <p>What is the best way to use <code>ListView</code>? The error happens only when I use <code>ListView1.DataBind();</code></p> <p>PS: I'll need only <strong>one</strong> row to display, so if someone has a better control to use than <code>ListView</code>, I'm reading. </p> <p><strong>UPDATE</strong></p> <p>Now I'm trying like this: </p> <pre><code>&lt;asp:ListView ID="ListView1" runat="server"&gt; &lt;LayoutTemplate&gt; &lt;table border="0" cellpadding="1"&gt; &lt;tr style="background-color: #E5E5FE"&gt; &lt;th align="left"&gt;&lt;asp:LinkButton ID="lnkResp" runat="server"&gt;&lt;/asp:LinkButton&gt;&lt;/th&gt; &lt;th align="left"&gt;&lt;asp:LinkButton ID="lnkProj" runat="server"&gt;&lt;/asp:LinkButton&gt;&lt;/th&gt; &lt;th align="left"&gt;&lt;asp:LinkButton ID="lnkFunc" runat="server"&gt;&lt;/asp:LinkButton&gt;&lt;/th&gt; &lt;th&lt;&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/LayoutTemplate&gt; &lt;ItemTemplate&gt; &lt;tr&gt; &lt;td&gt;&lt;asp:Label runat="server" ID="lblResp"&gt;&lt;%#Eval("responsavel") %&gt;&lt;/asp:Label&gt;&lt;/td&gt; &lt;td&gt;&lt;asp:Label runat="server" ID="lblProj"&gt;&lt;%#Eval("projeto") %&gt;&lt;/asp:Label&gt;&lt;/td&gt; &lt;td&gt;&lt;asp:Label runat="server" ID="lblFunc"&gt;&lt;%#Eval("funcionalidade") %&gt;&lt;/asp:Label&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/ItemTemplate&gt; &lt;/asp:ListView&gt; </code></pre> <p>But I got a <strong>new</strong> error: </p> <p><code>An item placeholder must be specified on ListView 'ListView1'.<br> Specify an item placeholder by setting a control's ID property to "itemPlaceholder".<br> The item placeholder control must also specify runat="server".</code></p>
1
1,088
Best way to compare key and value of array(s) in Laravel
<p>Currently I have two arrays as shown in the picture below. What is the best way to compare them? Either by combining them together and compare within one array or compare the way I did?</p> <p><strong>$array1</strong></p> <p><a href="https://i.stack.imgur.com/vQDj3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vQDj3.png" alt="$array1"></a></p> <p><strong>$array2</strong></p> <p><a href="https://i.stack.imgur.com/Of8Wd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Of8Wd.png" alt="enter image description here"></a></p> <p>This is what i did to compare them</p> <pre><code>&lt;table&gt; &lt;thead&gt;&lt;tr&gt;&lt;td&gt;status&lt;/td&gt;&lt;/tr&gt;&lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; foreach($array1 as $key =&gt; $value) { foreach($array2 as $ke2 =&gt; $value2) { if($value[0] == $value2[0] &amp;&amp; $value[1] == $value2[1] &amp;&amp; $value[2] == $value2[2]) YES else NO } } &lt;/td&gt; &lt;tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p><strong>updated</strong></p> <pre><code>&lt;table&gt; &lt;thead&gt;&lt;tr&gt;&lt;td&gt;status&lt;/td&gt;&lt;/tr&gt;&lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; @foreach ($array1 as $key =&gt; $value) @if (isset($array2[$key]) &amp;&amp; $value == $array2[$key]) Yes @else No @endif @endforeach &lt;/td&gt; &lt;tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p><strong>but this display in the table like this</strong></p> <p>Status</p> <p>NoYesYes</p> <p>NoYesYes</p> <p>NoYesYes</p> <p><strong>Suppose to be</strong></p> <p>Status</p> <p>No</p> <p>Yes</p> <p>Yes</p>
1
1,129
Laravel getting value from another table using eloquent
<p>I got tables like this:</p> <p>User table:</p> <pre><code>+----+---------+------------+ | id | name | level | +----+---------+------------+ | 1 | user 1 | 1 | | 2 | user 2 | 2 | +----+---------+------------+ </code></pre> <p>Category table:</p> <pre><code>+----+---------+------------+ | id | user_id | name | +----+---------+------------+ | 1 | 1 | category 1 | | 2 | 2 | category 2 | | 3 | 2 | category 3 | +----+---------+------------+ </code></pre> <p>Product table:</p> <pre><code>+----+-------------+------------+ | id | category_id | name | +----+-------------+------------+ | 1 | 1 | product 1 | | 2 | 2 | product 2 | | 3 | 3 | product 3 | | 4 | 3 | product 4 | +----+-------------+------------+ </code></pre> <p>I want to get all the product with user_id = 2 through eloquent, and i got it through the code below:</p> <pre><code>$id = 2; $data = product::whereHas('category', function ($q) use ($id) { $q-&gt;where('user_id', $id); })-&gt;get(); </code></pre> <p>But when i want to print the category name and user name through $data, it doesnt seem to work, my code is like this:</p> <pre><code>$data-&gt;first()-&gt;category-&gt;name; $data-&gt;first()-&gt;user-&gt;name; </code></pre> <p>I can just solve this question with normal query build with JOIN, just join 3 tables together and select the desire columns and it's good to go, but i want to solve it with eloquent, i'm kinda clueless how to make it work.</p> <p>And i have another question, i got a query builder code like this:</p> <pre><code> $id = false; if(auth()-&gt;user()-&gt;level != 1){ $id = auth()-&gt;user()-&gt;id; } $data = DB::table('product') -&gt;select('product.*', 'category.name AS category_name', 'users.name AS user_name') -&gt;join('category', 'category.id', '=', 'product.category_id') -&gt;join('users', 'users.id', '=', 'category.user_id') -&gt;when($id, function($query, $id){ return $query-&gt;where('users.id', $id); }) -&gt;get(); </code></pre> <p>The idea of this code is when user level = 1, i will get all the products, but when user level != 1, i will get all the products with the user id = $id, the question is: how can i convert this to eloquent? I got an answer for myself but i think it's not good enough.</p> <p>Thanks.</p>
1
1,035
Java Swing Blank JFrame coming up?
<p>I'm new to swing, and was wondering why sometimes my application comes up as blank, and sometimes it displays the components. It seems to be sporadic. There are no exceptions thrown or anything like that. It just frequently comes up as a blank JFrame. At times when I close the application and run it again, it shows the components correctly, but it mainly comes up as blank. Am I doing something wrong in the code? I'm using the Eclipse IDE, if it matters. Here's the code:</p> <pre><code>import java.applet.Applet; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; import javax.swing.*; public class Main extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; JRadioButton randomRadioButton; JRadioButton uniqueRadioButton; JRadioButton participationRadioButton; ArrayList&lt;Student&gt; allStudents; JFrame mainFrame; public Main(){ allStudents = new ArrayList&lt;Student&gt;(); processAllStudents(); mainFrame = new JFrame(); mainFrame.setVisible(true); mainFrame.setSize(250, 400); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel componentHolder = new JPanel(); componentHolder.setLayout(new GridLayout(5,1)); JLabel titleText = new JLabel(" Randomizer"); componentHolder.add(titleText); JButton picker = new JButton("Pick a Student"); JFileChooser filePick = new JFileChooser(); filePick.addActionListener(this); ButtonGroup allRadioButtons = new ButtonGroup(); randomRadioButton = new JRadioButton("Completely Random"); uniqueRadioButton = new JRadioButton("Unique"); participationRadioButton = new JRadioButton("Complete Participation"); allRadioButtons.add(randomRadioButton); allRadioButtons.add(uniqueRadioButton); allRadioButtons.add(participationRadioButton); componentHolder.add(randomRadioButton); componentHolder.add(uniqueRadioButton); componentHolder.add(participationRadioButton); picker.addActionListener(this); componentHolder.add(picker); componentHolder.add(filePick); mainFrame.add(componentHolder); } public void actionPerformed(ActionEvent e){ if(e.getActionCommand().equals("Pick a Student")){ if(randomRadioButton.isSelected()){ Student result = getStudentRandom(); result.increment(); String resultString = new String(result.getName() + ", " + result.getFrequency()); System.out.println(resultString); JLabel resultLabel = new JLabel(resultString); JOptionPane.showMessageDialog(mainFrame, resultLabel); } else if(uniqueRadioButton.isSelected()){ Student firstStudent = getStudentRandom(); Student secondStudent = getStudentRandom(); Student result; if(firstStudent.getName().equals(secondStudent.getName())){ result = secondStudent; } else{ result = firstStudent; } result.increment(); String resultString = new String(result.getName() + ", " + result.getFrequency()); System.out.println(resultString); JLabel resultLabel = new JLabel(resultString); JOptionPane.showMessageDialog(mainFrame, resultLabel); } else if(participationRadioButton.isSelected()){ Student result = selectStudentParticipant(); result.increment(); JOptionPane.showMessageDialog(mainFrame, result.getName() + ", " + result.getFrequency()); } } else System.out.println("Error."); } public void processAllStudents(){ File f = new File("Test.txt"); Scanner scanFile = null; try { scanFile = new Scanner(f); } catch (FileNotFoundException e) { System.out.println("File Not Found"); } while(scanFile.hasNext()){ String name = scanFile.next(); int frequency = scanFile.nextInt(); Student s = new Student(name, frequency); allStudents.add(s); } } public Student getStudentRandom(){ int result = (int) (Math.random() * allStudents.size()); return allStudents.get(result); } public Student selectStudentParticipant(){ Student temp = null; //Start of bubble sort algorithm for(int i = 0; i &lt; allStudents.size() - 1; i++){ Student firstStudent = allStudents.get(i); Student secondStudent = allStudents.get(i+1); if(firstStudent.getFrequency() &gt; secondStudent.getFrequency()){ temp = firstStudent; firstStudent = secondStudent; secondStudent = temp; } } //End of bubble sort algorithm. Data structure now sorted increasing int firstRandom = (int) (Math.random() * (allStudents.size()/2) + 0.2 * allStudents.size()); //Likely to be bigger int secondRandom = (int) (Math.random() * (allStudents.size()/2)); int randomIndex = 0; //Used to represent a random index if(firstRandom &gt; secondRandom){ //More likely. Selects from first half of list randomIndex = (int) (Math.random() * allStudents.size()/2); } else if(firstRandom &lt; secondRandom){ //Possible, but less likely randomIndex = (int) ((Math.random() * allStudents.size()/2) + allStudents.size()/2); } else{ //If the two random numbers are the same randomIndex = (int) (Math.random() * allStudents.size()/2); } return allStudents.get(randomIndex); } public static void main(String[] args){ new Main(); } } </code></pre>
1
2,572
Form data on load of Blueimp jQuery File Upload
<p>It seems that I have looked everywhere and tried everything and I can not get this to work, any help would be much appreciated! I am using Blueimp's jQuery File Upload. I have changed the UploadHandler.php in the following ways to make this upload work with multiple records and places within my system. I am using PHP and MySQL.</p> <p>Added to handle_file_upload function so that the file path, file name, file type, file size, the record type, and the "job number" is uploaded to a table I created in MySQL for each different file.</p> <pre><code>$file-&gt;upload_to_db = $this-&gt;add_file($job_num, $recordtype, $file_path, $filename, $type, $file_size); </code></pre> <p>This job number is sent to the page (with the file upload) as a get variable as well as a hidden form field to send to the Handler when adding a file. The add_file function I added is as follows:</p> <pre><code>function add_file($job_num, $recordtype, $filepath, $filename, $filetype, $filesize) { $filepath = addslashes($filepath); $insert_query = $this-&gt;query("INSERT INTO fileupload (job_num, recordtype, file_path, file_name, file_type, file_size) VALUES ('".$job_num."','".$recordtype."','".$filepath."','".$filename."','".$filetype."','".$filesize."')"); return $insert_query; } </code></pre> <p>The query function:</p> <pre><code>protected function query($query) { $database = $this-&gt;options['database']; $host = $this-&gt;options['host']; $username = $this-&gt;options['username']; $password = $this-&gt;options['password']; $Link = mysql_connect($host, $username, $password); if (!$Link){ die( mysql_error() ); } $db_selected = mysql_select_db($database); if (!$db_selected){ die( mysql_error() ); } $result = mysql_query($query); mysql_close($Link); return $result; } </code></pre> <p>I have a function for the delete as well. Now, this all works fine. Every file I add is saved and the path is stored in the database. From here I had to find a way to only show the files uploaded for that record instead of showing all files for every record. I modified the get function:</p> <pre><code>public function get($print_response = true) { if ($print_response &amp;&amp; isset($_GET['download'])) { return $this-&gt;download(); } $uploads = $this-&gt;query_db(); return $this-&gt;generate_response($uploads, $print_response); } </code></pre> <p>The query_db function:</p> <pre><code>public function query_db() { $uploads_array = array(); // error_log("Job Num: ".$this-&gt;job_num."\n\n",3,"error_log.txt"); $select_result = $this-&gt;query("SELECT * FROM fileupload WHERE job_num=423424"); while($query_results = mysql_fetch_object($select_result)) { $file = new stdClass(); $file-&gt;id = $query_results-&gt;id; $file-&gt;name = $query_results-&gt;file_name; $file-&gt;size = $query_results-&gt;file_size; $file-&gt;type = $query_results-&gt;file_type; $file-&gt;url = "filepath_to_url/".$query_results-&gt;file_name; $file-&gt;thumbnail_url = "filepath_to_thumbnail/".$query_results-&gt;file_name; $file-&gt;delete_url = ""; $file-&gt;delete_type = "DELETE"; array_push($uploads_array,$file); } return $uploads_array; } </code></pre> <p>Where the filepath is correct on my system. This, again, works just fine. But as you can see from the query in the query_db function I have the job_num hard coded. I need a way to get this when the first page is loaded. I have looked for a way to do this and nothing has worked. When I submit/add other files I can use the $_REQUEST['job_num'] to get it, but not when the page is loaded. I am not very familiar with OOP PHP so some of this is new to me. </p>
1
1,377
Getting JAX-WS client work on Weblogic 9.2 with ant
<p>I've recently had lots of issues trying to deploy a JAX-WS web servcie client on Weblogic 9.2. It turns out there is no straightforward guide on how to achieve this, so I decided to put together this short wiki entry hoping it might be useful for others.</p> <p>Firstly, Weblogic 9.2 does not support web servcies using JAX-WS in general. It comes with old versions of XML-related java libraries that are incompatible with the latest JAX-WS (similar issues occur with Axis2, only Axis1 seems to be working flawlessly with Weblogic 9.x but that's a very old and unsupported library).</p> <p>So, in order to get it working, some hacking is required. This is how I did it (note that we're using ant in our legacy corporate project, you probably should be using maven which should eliminate 50% of those steps below):</p> <p>1.Download the most recent JAX-WS distribution from <a href="https://jax-ws.dev.java.net/" rel="nofollow noreferrer">https://jax-ws.dev.java.net/</a> (The exact version I got was JAXWS2.2-20091203.zip)</p> <p>2.Place the JAX-WS jars with the dependencies in a separate folder like <em>lib/webservices</em>.</p> <p>3.Create a patternset in ant to reference those jars:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;patternset id="jaxws.classpath"&gt; &lt;include name="webservices/jsr173_api.jar" /&gt; &lt;include name="webservices/jsr181-api.jar" /&gt; &lt;include name="webservices/jaxb-api.jar" /&gt; &lt;include name="webservices/jaxb-impl.jar" /&gt; &lt;include name="webservices/jaxb-xjc.jar" /&gt; &lt;include name="webservices/jaxws-tools.jar" /&gt; &lt;include name="webservices/jaxws-rt.jar" /&gt; &lt;include name="webservices/jaxws-api.jar" /&gt; &lt;include name="webservices/policy.jar" /&gt; &lt;include name="webservices/woodstox.jar" /&gt; &lt;include name="webservices/streambuffer.jar" /&gt; &lt;include name="webservices/stax-ex.jar" /&gt; &lt;include name="webservices/saaj-api.jar" /&gt; &lt;include name="webservices/saaj-impl.jar" /&gt; &lt;include name="webservices/gmbal-api-only.jar" /&gt; &lt;/patternset&gt; </code></pre> <p>4.Include the patternset in your WAR-related goal. This could look something like:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;copy todir="${wardir.lib}" includeEmptyDirs="false" flatten="true"&gt; &lt;fileset dir="${libs}"&gt; &lt;!--lots of libs here, related to your project --&gt; &lt;patternset refid="jaxws.classpath"/&gt; &lt;/fileset&gt; &lt;/copy&gt; </code></pre> <p>(not the <em>flatten="true"</em> parameter - it's important as Weblogic 9.x is by default not smart enough to access jars located in a different lcoation than WEB-INF/lib inside your WAR file)</p> <p>5.In case of clashes, Weblogic uses its own jars by default. We want it to use the JAX-WS jars from our application instead. This is achieved by preparing a <em>weblogic-application.xml</em> file and placing it in META-INF folder of the deplotyed EAR file. It should look like this:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;weblogic-application xmlns="http://www.bea.com/ns/weblogic/90" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;prefer-application-packages&gt; &lt;package-name&gt;javax.jws.*&lt;/package-name&gt; &lt;package-name&gt;javax.xml.bind.*&lt;/package-name&gt; &lt;package-name&gt;javax.xml.crypto.*&lt;/package-name&gt; &lt;package-name&gt;javax.xml.registry.*&lt;/package-name&gt; &lt;package-name&gt;javax.xml.rpc.*&lt;/package-name&gt; &lt;package-name&gt;javax.xml.soap.*&lt;/package-name&gt; &lt;package-name&gt;javax.xml.stream.*&lt;/package-name&gt; &lt;package-name&gt;javax.xml.ws.*&lt;/package-name&gt; &lt;package-name&gt;com.sun.xml.api.streaming.*&lt;/package-name&gt; &lt;/prefer-application-packages&gt; &lt;/weblogic-application&gt; </code></pre> <p>6.Remember to place that <em>weblogic-application.xml</em> file in your EAR! The ant goal for that may look similar to:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;target name="build-ear" depends="war, manifest"&gt; &lt;delete dir="${dist}"/&gt; &lt;mkdir dir="${dist}"/&gt; &lt;jar destfile="${warfile}" basedir="${wardir}"/&gt; &lt;ear destfile="${earfile}" appxml="resources/${app.name}/application.xml"&gt; &lt;fileset dir="${dist}" includes="${app.name}.war"/&gt; &lt;metainf dir="resources/META-INF"/&gt; &lt;/ear&gt; &lt;/target&gt; </code></pre> <p>7.Also you need to tell weblogic to prefer your WEB-INF classes to those in distribution. You do that by placing the following lines in your <em>WEB-INF/weblogic.xml</em> file:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;container-descriptor&gt; &lt;prefer-web-inf-classes&gt;true&lt;/prefer-web-inf-classes&gt; &lt;/container-descriptor&gt; </code></pre> <p>8.And that's it for the weblogic-related configuration. Now only set up your JAX-WS goal. The one below is going to simply generate the web service stubs and classes based on a locally deployed WSDL file and place them in a folder in your app:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;target name="generate-jaxws-client"&gt; &lt;taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport"&gt; &lt;classpath path="classpath.main"/&gt; &lt;/taskdef&gt; &lt;wsimport destdir="${src}" package="acme.somewhere.in.your.package.tree.webservices." keep="true" wsdl="http://localhost:8088/mockWebService?WSDL"&gt; &lt;/wsimport&gt; &lt;/target&gt; </code></pre> <p>Remember about the keep="true" parameter. Without it, wsimport generates the classes and... deletes them, believe it or not!</p> <p>For mocking a web service I suggest using SOAPUI, an open source project. Very easy to deploy, crucial for web servcies intergation testing.</p> <p>9.We're almost there. The final thing is to write a Java class for testing the web service, try to run it as a standalone app first (or as part of your unit tests)</p> <p>10.And then try to run the same code from withing Weblogic. It should work. It worked for me. After some 3 days of frustration. And yes, I know I should've put 9 and 10 under a single bullet-point, but the title "10 steps to deploy a JAX-WS web service under Web logic 9.2 using ant" sounds just so much better.</p> <p>Please, edit this post and improve it if you find something missing!</p>
1
2,550
MKDirectionsResponse: error, Directions not available. (USA)
<p>For learning purposes I'm trying to develop an app which will show directions to a specific point on a MKMapView.<br> However, the DirectionsResponse gives me the following error everytime, no matter the address:</p> <pre><code>2013-12-28 17:52:23.100 routingApp[378:70b] ERROR 2013-12-28 17:52:23.102 routingApp[378:70b] Directions Not Available </code></pre> <p>I only have a View Controller with a map view and the following code: </p> <p>routingAppViewController.h </p> <pre><code>@interface routingAppViewController : UIViewController @property (strong, nonatomic) IBOutlet MKMapView *mapView; @property (strong, nonatomic) MKPlacemark *destination; @end </code></pre> <p>routingAppViewController.m </p> <pre><code>#import "routingAppViewController.h" @interface routingAppViewController () @end @implementation routingAppViewController - (void)viewDidLoad { [super viewDidLoad]; NSString *Location = @"385 Mid Avenue Weston"; _mapView.showsUserLocation = YES; [self getDirections:Location]; } -(void)getDirections:(NSString *)address{ CLGeocoder *geocoder = [[CLGeocoder alloc] init]; [geocoder geocodeAddressString:address completionHandler:^(NSArray* placemarks, NSError* error){ // Check for returned placemarks if (placemarks &amp;&amp; placemarks.count &gt; 0) { CLPlacemark *topResult = [placemarks objectAtIndex:0]; // Create a MLPlacemark and add it to the map view MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult]; [self.mapView addAnnotation:placemark]; _destination = placemark; } }]; MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:_destination]; MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init]; request.source = [MKMapItem mapItemForCurrentLocation]; request.destination = mapItem; request.requestsAlternateRoutes = NO; MKDirections *directions = [[MKDirections alloc] initWithRequest:request]; [directions calculateDirectionsWithCompletionHandler: ^(MKDirectionsResponse *response, NSError *error) { if (error) { NSLog(@"ERROR"); NSLog(@"%@",[error localizedDescription]); } else { [self showRoute:response]; } }]; } -(void)showRoute:(MKDirectionsResponse *)response { for (MKRoute *route in response.routes) { [_mapView addOverlay:route.polyline level:MKOverlayLevelAboveRoads]; for (MKRouteStep *step in route.steps) { NSLog(@"%@", step.instructions); } } } - (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id &lt; MKOverlay &gt;)overlay { MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay]; renderer.strokeColor = [UIColor blueColor]; renderer.lineWidth = 5.0; return renderer; } </code></pre> <p>The error is given in the <code>getDirections</code> method.<br> I googled it and mostly the error means that the direction service is not available for this country. However i'm using an USA address, so I can't see why it's not working.</p> <p>The annotation is added correctly and my location is set to "Apple".<br> Help much appreciated!</p>
1
1,235
How to either disable scrolling in md-content or have a min-height when on mobile
<p>I'm using Angular Material's md-content directives to create a section that flexes to fill the usable vertical space and scrolls it's content. The problem is when viewing the page with a small screen, the content shrinks to the point that it effectively disappears. I'd like the md-content to stop scrolling or have a min-height so the page scrollbar shows up and the user can still see the content.</p> <p><strong>Update:</strong> Here's a plunker to demonstrate the problem: <a href="https://plnkr.co/edit/NVbEHo0CPxX5Zzi4U88U?p=preview" rel="nofollow">https://plnkr.co/edit/NVbEHo0CPxX5Zzi4U88U?p=preview</a></p> <pre><code> &lt;body layout="column"&gt; &lt;div&gt; &lt;h1&gt;Header&lt;/h1&gt; &lt;/div&gt; &lt;md-content layout="row"&gt; &lt;div flex="50"&gt;Left Column&lt;/div&gt; &lt;md-content flex="50" layout="column"&gt; &lt;h2&gt;Section Header&lt;/h2&gt; &lt;md-content layout="column" flex&gt; &lt;h3&gt;Scroll Header&lt;/h3&gt; &lt;md-content flex layout="column" style="min-height: 300px"&gt; &lt;md-content flex&gt; scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt; scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt; scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt;scrollable content&lt;br/&gt; &lt;/md-content&gt; &lt;/md-content&gt; &lt;/md-content&gt; &lt;/md-content&gt; &lt;/md-content&gt; &lt;/body&gt; </code></pre> <p>If the browser window is large, the scrollable content scrolls as expected. When you shrink the browser, the <code>md-content</code> with the scrollable content shrinks down to nothing.</p> <p><strong>Update 2:</strong> I updated my plunker with a better example. To get the desired section scrollable and have it flex to the bottom of the viewport, I have all of its parent elements as <code>md-content</code> elements with a <code>layout</code> attribute. I can set a <code>min-height</code> on the scrollable element, but when the browser is shrunk now its parent <code>md-content</code> has a scroll bar. I could put another <code>min-height</code> on <em>that</em> <code>md-content</code>, but that would require me to know the height of its content (which could be dynamic).</p> <p>Ideally, when shrinking the browser vertically, I'd like the scrollable content to only shrink to its min-height, and then change the behavior of all its parent <code>md-content</code> elements to not scroll so only the <code>body</code> scroll bar appears.</p>
1
1,557
Creating Accessible UI components in Delphi
<p>I am trying to retrieve accessible information from a standard VCL TEdit control. The get_accName() and Get_accDescription() methods return empty strings, but get_accValue() returns the text value entered into the TEdit.</p> <p>I am just starting to try to understand the MSAA and I'm a bit lost at this point. </p> <p>Does my TEdit need to have additional published properties that would be exposed to the MSA? If so would that necessitate creating a new component that descends from TEdit and adds the additional published properties such as "AccessibleName", "AccessibleDescription", etc... ?</p> <p>Also, note, I have looked at the VTVirtualTrees component which is <em>supposed</em> to be accessible, but the MS Active Accessibility Object Inspector still does not see the AccessibleName published property even on that control. </p> <p>At this point I am at a loss and would be grateful for any advice or help in this matter.</p> <pre><code>... interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, oleacc; const WM_GETOBJECT = $003D; // Windows MSAA message identifier OBJID_NATIVEOM = $FFFFFFF0; type TForm1 = class(TForm) lblFirstName: TLabel; edFirstName: TEdit; panel1: TPanel; btnGetAccInfo: TButton; accInfoOutput: TEdit; procedure btnGetAccInfoClick(Sender: TObject); procedure edFirstNameChange(Sender: TObject); private { Private declarations } FFocusedAccessibleObj: IAccessible; FvtChild: Variant; FAccProperties: TStringList; FAccName: string; FAccDesc: string; FAccValue: string; procedure DoGetAccessibleObjectFromPoint(aPoint: TPoint); public { Public declarations } procedure BeforeDestruction; override; property AccName: string read FAccName; property AccDescription: string read FAccName; property AccValue: string read FAccName; end; var Form1: TForm1; const cCRLF = #13#10; implementation {$R *.dfm} function AccessibleObjectFromPoint(ptScreen: TPoint; out ppacc: IAccessible; out pvarChildt: Variant): HRESULT; stdcall; external 'oleacc.dll' ; {------------------------------------------------------------------------------} procedure TForm1.BeforeDestruction; begin VarClear(FvtChild); FFocusedAccessibleObj := nil; end; {------------------------------------------------------------------------------} procedure TForm1.DoGetAccessibleObjectFromPoint(aPoint: TPoint); var pt: TPoint; bsName: WideString; bsDesc: WideString; bsValue: WideString; begin if (SUCCEEDED(AccessibleObjectFromPoint(aPoint, FFocusedAccessibleObj, FvtChild))) then try // get_accName returns an empty string bsName := ''; FFocusedAccessibleObj.get_accName(FvtChild, bsName); FAccName := bsName; FAccProperties.Add('Acc Name: ' + FAccName + ' | ' + cCRLF); // Get_accDescription returns an empty string bsDesc := ''; FFocusedAccessibleObj.Get_accDescription(FvtChild, bsDesc); FAccDesc := bsDesc; FAccProperties.Add('Acc Description: ' + FAccDesc + ' | ' + cCRLF); // this works bsValue := ''; FFocusedAccessibleObj.get_accValue(FvtChild, bsValue); FAccValue := bsValue; FAccProperties.Add('Acc Value: ' + FAccValue + cCRLF); finally VarClear(FvtChild); FFocusedAccessibleObj := nil ; end; end; {------------------------------------------------------------------------------} procedure TForm1.btnGetAccInfoClick(Sender: TObject); begin FAccProperties := TStringList.Create; DoGetAccessibleObjectFromPoint(edFirstName.ClientOrigin); accInfoOutput.Text := FAccProperties.Text; end; end. </code></pre>
1
1,399
VSCode with WSL2 - Delayed launching due to no response to ping
<p>Using VSCode with WSL2. Everything was alright until last week. From today, I observed that it is taking time to start the WSL. The following is the log from VSCode.</p> <pre><code>[2021-02-22 06:00:31.458] Resolving wsl+myubuntu2004, resolveAttempt: 1 [2021-02-22 06:00:31.553] Starting VS Code Server inside WSL (MyUbuntu2004) [2021-02-22 06:00:31.553] Extension version: 0.53.4, Windows build: 18363. Multi distro support: available. WSL path support: enabled [2021-02-22 06:00:31.553] No shell environment set or found for current distro. [2021-02-22 06:00:31.657] Probing if server is already installed: C:\Windows\System32\wsl.exe -d MyUbuntu2004 -e sh -c &quot;[ -d ~/.vscode-server/bin/622cb03f7e070a9670c94bae1a45d78d7181fbd4 ] &amp;&amp; printf found || ([ -f /etc/alpine-release ] &amp;&amp; printf alpine-; uname -m)&quot; [2021-02-22 06:00:31.830] Probing result: x86_64 [2021-02-22 06:00:31.831] No server install found in WSL, needs x64 [2021-02-22 06:00:31.832] Launching C:\Windows\System32\wsl.exe -d MyUbuntu2004 sh -c '&quot;$VSCODE_WSL_EXT_LOCATION/scripts/wslServer.sh&quot; 622cb03f7e070a9670c94bae1a45d78d7181fbd4 stable .vscode-server 0 '} [2021-02-22 06:00:31.957] Setting up server environment: Looking for /home/raj/.vscode-server/server-env-setup. Not found. [2021-02-22 06:00:31.957] WSL version: 5.4.72-microsoft-standard-WSL2 MyUbuntu2004 [2021-02-22 06:00:31.957] Installing VS Code Server from tar available at /mnt/c/Users/1186738/AppData/Local/Temp/vscode-remote-wsl/622cb03f7e070a9670c94bae1a45d78d7181fbd4/vscode-server-linux-x64.tar.gz [2021-02-22 06:00:32.857] Unpacking: 0% 1% 2% 3% 4% 5% 6% 7% 8% 9% 10% 11% 12% 13% 14% 15% 16% 17% 18% 19% 20% 21% 22% 23% 24% 25% 26% 27% 28% 29% 30% 31% 32% 33% 34% [2021-02-22 06:00:33.158] 35% 36% 37% 38% 39% 40% 41% 42% [2021-02-22 06:00:33.459] 43% 44% 45% 46% 47% 48% 49% 50% 51% 52% 53% 54% 55% 56% 57% 58% 59% 60% 61% 62% 63% 64% 65% 66% 67% 68% 69% 70% 71% 72% 73% 74% 75% 76% 77% 78% 79% 80% 81% 82% 83% 84% 85% 86% 87% 88% 89% 90% 91% 92% 93% 94% 95% 96% 97% 98% 99%100% [2021-02-22 06:00:33.459] Unpacked 1769 files and folders to /home/raj/.vscode-server/bin/622cb03f7e070a9670c94bae1a45d78d7181fbd4. [2021-02-22 06:00:33.459] WSL2-shell-PID: 96 [2021-02-22 06:00:33.459] Starting server: /home/raj/.vscode-server/bin/622cb03f7e070a9670c94bae1a45d78d7181fbd4/server.sh --port=0 --use-host-proxy --without-browser-env-var --enable-remote-auto-shutdown [2021-02-22 06:00:33.459] [2021-02-22 06:00:33.459] [2021-02-22 06:00:33.459] * [2021-02-22 06:00:33.459] * Visual Studio Code Server [2021-02-22 06:00:33.459] * [2021-02-22 06:00:33.459] * Reminder: You may only use this software with Visual Studio family products, [2021-02-22 06:00:33.459] * as described in the license https://aka.ms/vscode-remote/license [2021-02-22 06:00:33.459] * [2021-02-22 06:00:33.459] [2021-02-22 06:00:33.459] IP Address: 172.x.x.x [2021-02-22 06:00:33.459] Extension host agent listening on 34395 [2021-02-22 06:00:33.459] [2021-02-22 06:00:33.459] [11:30:33] Extension host agent started. [2021-02-22 06:00:33.467] Pinging 172.x.x.x:34395... [2021-02-22 06:03:34.217] 172.x.x.x:34395 no response [2021-02-22 06:03:34.217] WSL resolver response: ::1:34395 [2021-02-22 06:03:34.217] To debug connection issues, open a local browser on http://[::1]:34395/version </code></pre> <p>It can be seen that the 'Pinging 172.x.x.x:34395...' is taking 3 mins time and returning no response. This is causing a delay of 3 minutes during each launch of VSCode workspace.</p> <p>I tested connection to the above ip with port through both Windows and through WSL successfully.</p> <pre><code>PS C:\Users\Raj&gt; Test-NetConnection 172.x.x.x -port 34395 ComputerName : 172.x.x.x RemoteAddress : 172.x.x.x RemotePort : 34395 InterfaceAlias : vEthernet (WSL) SourceAddress : 172.x.x.x TcpTestSucceeded : True raj@WSL-Host:~$ nc -vz 172.x.x.x 34395 Connection to 172.x.x.x 34395 port [tcp/*] succeeded! </code></pre> <p>VSCode version details.</p> <pre><code>Version: 1.53.2 (user setup) Commit: 622cb03f7e070a9670c94bae1a45d78d7181fbd4 Date: 2021-02-11T11:48:04.245Z Electron: 11.2.1 Chrome: 87.0.4280.141 Node.js: 12.18.3 V8: 8.7.220.31-electron.0 OS: Windows_NT x64 10.0.18363 </code></pre>
1
1,904
unexpected AST Node
<p>I use the below given HQL Query:</p> <pre><code>select A.id.customerName, A.id.customerId, A.id.IZone, B.id.accountType, B.id.accountNumber, B.id.bankBranch, (DAYS(current_date)-DAYS(B.id.enrolledDate)) - (select count(distinct C.id.DWkhol) from Holiday C where C.id.ICo='01' and C.id.DWkhol between B.id.enrolledDate and current_date) from Profile A, Account B where B.id.accountNumber != ' ' and A.id.customerId= B.id.customerId; </code></pre> <p>Same query works fine in SQL developer and i am able to see the values. But I am receiving expections when i call this Query through my java class:</p> <blockquote> <p>[3/16/17 21:02:29:624 EDT] 00000027 SystemOut O 406868 [WebContainer : 1] ERROR org.hibernate.hql.PARSER - :0:0: unexpected AST node: query [3/16/17 21:02:29:626 EDT] 00000027 SystemOut O 406868 [WebContainer : 1] DEBUG org.hibernate.hql.ast.ErrorCounter - :0:0: unexpected AST node: query :0:0: unexpected AST node: query at org.hibernate.hql.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1312) at org.hibernate.hql.antlr.HqlSqlBaseWalker.arithmeticExpr(HqlSqlBaseWalker.java:2749) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2006) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:1825) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1394) at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:553) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:281) at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:229) at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:251) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:13 [3/16/17 21:02:29:626 EDT] 00000027 SystemOut O 406870 [WebContainer : 1] ERROR org.hibernate.hql.PARSER - right-hand operand of a binary operator was null [3/16/17 21:02:29:627 EDT] 00000027 SystemOut O 406870 [WebContainer : 1] DEBUG org.hibernate.hql.ast.ErrorCounter - right-hand operand of a binary operator was null right-hand operand of a binary operator was null at org.hibernate.hql.ast.tree.BinaryArithmeticOperatorNode.initialize(BinaryArithmeticOperatorNode.java:48) at org.hibernate.hql.ast.HqlSqlWalker.prepareArithmeticOperator(HqlSqlWalker.java:1033) at org.hibernate.hql.antlr.HqlSqlBaseWalker.arithmeticExpr(HqlSqlBaseWalker.java:2756) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2006) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:1825) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1394) at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:553) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:281) at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:229) at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:251) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:134)</p> </blockquote>
1
1,533
How do you use masks correctly in pygame?
<p>I have been trying to make a car football game with pygame, and have almost finished, but I would like some help with goal scoring and border detection. I wasn't able to get something to happen if the ball touched the net(I tried with the red net. Anything with the name "redsurf" is the goal). Also, when I try to make the ball and car bounce off the edge, nothing happens, but the ball strangely moves at the beginning. "Borderline" is what I am trying to use to make the ball bounce off the side". Additionally, I can't get the boosted speed to work, not sure why though. I really hope someone can help and edit my code so it works.</p> <pre><code>import pygame from pygame.math import Vector2 pygame.init() WIDTH = 1150 HEIGHT = 800 screen = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() bgImg = pygame.image.load("Football_pitch.png") redsurf = pygame.Surface((50,125)) redsurf.fill((255,0,0)) redsurfpos = Vector2(50,125) bluesurf = pygame.Surface((50,125)) bluesurf.fill((0,0,255)) bluesurfpos = Vector2(50,125) borderline = pygame.draw.rect(screen, (0,0,0),[10,10,10,10],0) BLUECAR_ORIGINAL = pygame.Surface((50, 30), pygame.SRCALPHA) pygame.draw.polygon( BLUECAR_ORIGINAL, (0, 0, 255), [(0, 30), (50, 20), (50, 10), (0, 0)]) bluecar = BLUECAR_ORIGINAL REDCAR_ORIGINAL = pygame.Surface((50, 30), pygame.SRCALPHA) pygame.draw.polygon( REDCAR_ORIGINAL, (255, 0, 0), [(0, 0), (50, 10), (50, 20), (0, 30)]) redcar = REDCAR_ORIGINAL score = 0 redspeed = 7 bluespeed = 7 ball_x = 575 ball_y = 400 dx = 1 dy = 0 BALL = pygame.Surface((30, 30), pygame.SRCALPHA) pygame.draw.circle(BALL, [0,0,0], [15, 15], 15) ball_pos = Vector2(ball_x, ball_y) ballrect = BALL.get_rect(center=ball_pos) redsurfrect = redsurf.get_rect(center=redsurfpos) bluesurfrect = redsurf.get_rect(center=bluesurfpos) ball_vel = Vector2(dx, dy) pos_red = Vector2(1000,370) vel_red = Vector2(redspeed,0) redrect = redcar.get_rect(center=pos_red) redangle = 0 pos_blue = Vector2(70,70) vel_blue = Vector2(bluespeed,0) bluerect = bluecar.get_rect(center=pos_red) blueangle = 0 mask_blue = pygame.mask.from_surface(bluecar) mask_red = pygame.mask.from_surface(redcar) mask_ball = pygame.mask.from_surface(BALL) mask_redsurfgoal = pygame.mask.from_surface(redsurf) mask_bluesurfgoal = pygame.mask.from_surface(bluesurf) run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False ball_x += dx ball_y += dy if ball_y&lt;0 or ball_y&gt;HEIGHT - 40: dy *= -1 if ball_x&lt;0 or ball_x&gt;WIDTH - 40: dx *= -1 keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: redangle += 5 vel_red.rotate_ip(-5) redcar = pygame.transform.rotate(REDCAR_ORIGINAL, redangle) redrect = redcar.get_rect(center=redrect.center) mask_red = pygame.mask.from_surface(redcar) elif keys[pygame.K_RIGHT]: redangle -= 5 vel_red.rotate_ip(5) redcar = pygame.transform.rotate(REDCAR_ORIGINAL, redangle) redrect = redcar.get_rect(center=redrect.center) mask_red = pygame.mask.from_surface(redcar) elif keys[pygame.K_l]: redspeed = 20 if keys[pygame.K_a]: blueangle += 5 vel_blue.rotate_ip(-5) bluecar = pygame.transform.rotate(BLUECAR_ORIGINAL, blueangle) bluerect = bluecar.get_rect(center=bluerect.center) mask_blue = pygame.mask.from_surface(bluecar) elif keys[pygame.K_d]: blueangle -= 5 vel_blue.rotate_ip(5) bluecar = pygame.transform.rotate(BLUECAR_ORIGINAL, blueangle) bluerect = bluecar.get_rect(center=bluerect.center) mask_blue = pygame.mask.from_surface(bluecar) pos_red += vel_red redrect.center = pos_red pos_blue += vel_blue bluerect.center = pos_blue ball_vel *= .95 ball_pos += ball_vel ballrect.center = ball_pos offset_red = redrect[0] - ballrect[0], redrect[1] - ballrect[1] offset_redgoal = ballrect[0] - redsurfrect[0], ballrect[1] - redsurfrect[1] overlap_red = mask_ball.overlap(mask_red, offset_red) offset_blue = bluerect[0] - ballrect[0], bluerect[1] - ballrect[1] overlap_blue = mask_ball.overlap(mask_blue, offset_blue) offset_rednetgoal = ballrect[0] - redsurfrect[0], ballrect[1] - redsurfrect[1] overlap_redgoal = mask_ball.overlap(redsurfrect, offset_rednetgoal) if overlap_red and overlap_blue: ball_vel = vel_red + vel_blue * 1.4 elif overlap_red: ball_vel = Vector2(vel_red) * 1.4 elif overlap_blue: ball_vel = Vector2(vel_blue) * 1.4 elif overlap_redgoal: print("goal") screen.blit(bgImg, (0, 0)) screen.blit(BALL, ballrect) screen.blit(redcar, redrect) screen.blit(bluecar, bluerect) screen.blit(redsurf, (0,340)) screen.blit(bluesurf,(1100,340)) pygame.display.flip() pygame.display.update() clock.tick(60) pygame.quit() </code></pre>
1
2,168
threejs Adding lighting to ShaderMaterial
<p>I'm creating a cube full of spheres. So I'm using a particle system. It's all working well until I try to apply a shader material to each of the particles. I've pretty much used the example at <a href="http://threejs.org/examples/#webgl_custom_attributes_particles3" rel="nofollow">http://threejs.org/examples/#webgl_custom_attributes_particles3</a>. </p> <p>It is working, but what I'm trying to do now is add lighting to the scene using directional lighting. That's where I'm not getting anywhere. I have no experience in GLSL and am just copying and pasting at the moment, testing the waters. Any help would be great. </p> <p>Here's what I have so far. </p> <pre><code>&lt;script type="x-shader/x-vertex" id="vertexshader"&gt; attribute float size; attribute vec4 ca; varying vec4 vColor; void main() { vColor = ca; vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); gl_PointSize = size * ( 150.0 / length( mvPosition.xyz ) ); gl_Position = projectionMatrix * mvPosition; } &lt;/script&gt; &lt;script type="x-shader/x-fragment" id="fragmentshader"&gt; uniform vec3 color; uniform sampler2D texture; varying vec4 vColor; void main() { vec4 outColor = texture2D( texture, gl_PointCoord ); if ( outColor.a &lt; 0.5 ) discard; gl_FragColor = outColor * vec4( color * vColor.xyz, 1.0 ); float depth = gl_FragCoord.z / gl_FragCoord.w; const vec3 fogColor = vec3( 0.0 ); float fogFactor = smoothstep( 200.0, 700.0, depth ); gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor ); } &lt;/script&gt; </code></pre> <p>and in my js:</p> <pre><code>(function addSpheres() { var cube = new THREE.Object3D(); scene.add(cube); var totalSpheres = 3840; //15*16*16 var particles = new THREE.Geometry(); var attributes = { size: { type: 'f', value: [] }, ca: { type: 'c', value: [] } }; var uniforms = { amplitude: { type: "f", value: 1.0 }, color: { type: "c", value: new THREE.Color(0xffffff) }, texture: { type: "t", value: THREE.ImageUtils.loadTexture("textures/sprites/ball.png") } }; uniforms.texture.value.wrapS = uniforms.texture.value.wrapT = THREE.RepeatWrapping; var shaderMaterial = new THREE.ShaderMaterial({ uniforms: uniforms, attributes: attributes, vertexShader: document.getElementById('vertexshader').textContent, fragmentShader: document.getElementById('fragmentshader').textContent, }); shaderMaterial.lights = true; var n = 20, n2 = n / 2; var particle; for (var i = -7; i &lt; 9; i++) { for (var j = -7; j &lt; 9; j++) { for (var k = -7; k &lt; 8; k++) { var pX = i * n - n2; var pY = j * n - n2; var pZ = k * n - n2; particle = new THREE.Vector3(pX, pY, pZ); particles.vertices.push(particle); } } } particleSystem = new THREE.ParticleSystem(particles, shaderMaterial); particleSystem.dynamic = true; // custom attributes var vertices = particleSystem.geometry.vertices; var values_size = attributes.size.value; var values_color = attributes.ca.value; for (var v = 0; v &lt; vertices.length; v++) { attributes.size.value[v] = 55; attributes.ca.value[v] = new THREE.Color(0xffffff); attributes.size.needsUpdate = true; attributes.ca.needsUpdate = true; } cube.add(particleSystem); scene.matrixAutoUpdate = false; })(); </code></pre> <p>Thanks in advance. John.</p>
1
1,341
'Position: sticky' not sticking
<p>I have created a sidebar and I am simply trying to make it stick about 15px under the header when the user scrolls down. I initially was using JS for this but it really bogged my page speed down and things got choppy. I found that position sticky should work for most browsers, however my sidebar is not sticking on scroll. </p> <p>I have read in various places to make sure there is no height set and overflow of any kind to the parent element, which it is not. So I am struggling to find the cause of the problem. I am wondering if there are other factors that I did not find online that could have an effect on <code>position:sticky</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-css lang-css prettyprint-override"><code>.btn.sidebar { backface-visibility: hidden; box-shadow: 0 0 1px rgba(0, 0, 0, 0); display: inline-block; position: relative; vertical-align: middle; width: 100%; background: rgba(255, 255, 255, .6); border-radius: 0; font-size: 22px; transition: ease .5s; } .btn.sidebar:hover { background: #97B2AC; color: #fff; } p.contact-text { color: #eee; text-align: center; } div.modal-form-sidebar { position: sticky; position: -webkit-sticky; top: 0px; font: 95% Arial, Helvetica, sans-serif; width: 320px; padding: 16px; background: #5d84a1; } .modal-form-sidebar h1 { background: rgba(255, 255, 255, .4); padding: 13px 0; font-size: 140%; font-weight: 300; text-align: center; color: #fff; margin: 0; } .modal-form-sidebar input[type="text"], .modal-form-sidebar input[type="date"], .modal-form-sidebar input[type="datetime"], .modal-form-sidebar input[type="email"], .modal-form-sidebar input[type="number"], .modal-form-sidebar input[type="search"], .modal-form-sidebar input[type="time"], .modal-form-sidebar input[type="url"], .modal-form-sidebar textarea, .modal-form-sidebar select { -webkit-transition: all 0.30s ease-in-out; -moz-transition: all 0.30s ease-in-out; -ms-transition: all 0.30s ease-in-out; -o-transition: all 0.30s ease-in-out; outline: none; box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; width: 100%; background: #fff; margin-bottom: 4%; border: 1px solid #ccc; padding: 3%; color: #555; font: 95% Arial, Helvetica, sans-serif; } .modal-form-sidebar input[type="text"]:focus, .modal-form-sidebar input[type="date"]:focus, .modal-form-sidebar input[type="datetime"]:focus, .modal-form-sidebar input[type="email"]:focus, .modal-form-sidebar input[type="number"]:focus, .modal-form-sidebar input[type="search"]:focus, .modal-form-sidebar input[type="time"]:focus, .modal-form-sidebar input[type="url"]:focus, .modal-form-sidebar textarea:focus, .modal-form-sidebar select:focus { box-shadow: 0 0 5px #5d84a1; padding: 3%; border: 1px solid #5d84a1; } .modal-form-sidebar input[type="submit"], .modal-form-sidebar input[type="button"] { box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; width: 100%; padding: 3%; background: #5d84a1; border-bottom: 2px solid #374F60; border-top-style: none; border-right-style: none; border-left-style: none; color: #fff; } .modal-form-sidebar input[type="submit"]:hover, .modal-form-sidebar input[type="button"]:hover { background: #7d9cb3; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="modal-form-sidebar"&gt; &lt;p class="contact-text"&gt;Text here&lt;/p&gt; &lt;h1&gt;Email Us&lt;/h1&gt; &lt;form action="#" id="client_capture_sidebar" method="POST" onsubmit="submitted=true;" target="hidden_iframe" role="form"&gt; &lt;input type="text" name="field1" placeholder="Your Name" /&gt; &lt;input type="email" name="field2" placeholder="Email Address" /&gt; &lt;input type="email" name="field2" placeholder="Phone Number" /&gt; &lt;textarea name="field3" placeholder="Type your Message"&gt;&lt;/textarea&gt; &lt;input type="submit" value="Send" /&gt; &lt;/form&gt; &lt;br&gt; &lt;div class="white-txt"&gt;or&lt;/div&gt; &lt;br&gt; &lt;h1&gt;Call Us&lt;/h1&gt; &lt;a class="btn sidebar" href="tel:1-222-222-2222"&gt;&lt;i class="fa fa-phone" aria-hidden="true"&gt;&lt;/i&gt;(222) 222-2222&lt;/a&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
1
1,728
Why am I receiving a "thread exiting with uncaught exception”?
<p>I'm using Parse.com for push notifications. When I receive a push notification, this class executes:</p> <pre><code>public class MyCustomReceiver extends BroadcastReceiver { protected ObjetoMensaje DatosObjecto; protected SerializacionDeDatos Sdd; protected String alert, fecha, name, tipo; private static final String TAG = "MyCustomReceiver"; @Override public void onReceive(Context context, Intent intent) { try { DatosObjecto = new ObjetoMensaje(); Sdd = new SerializacionDeDatos(); String action = intent.getAction(); String channel = intent.getExtras().getString("com.parse.Channel"); JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data")); Log.d(TAG, "got action " + action + " on channel " + channel + " with:"); Iterator&lt;?&gt; itr = json.keys(); Log.i("",""); while (itr.hasNext()) { String key = (String) itr.next(); Log.d(TAG, "..." + key + " =&gt; " + json.getString(key)); Log.d(TAG,""); } alert = json.getString("alert").toString(); name = json.getString("name").toString(); tipo = json.getString("tipo").toString(); DatosObjecto.setAlert(alert); DatosObjecto.setName(name); DatosObjecto.setTipo(tipo); Sdd.Serializa(DatosObjecto); //this line, I use for call the class "SerializacionDeDatos" } catch (JSONException e) { Log.d(TAG, "JSONException: " + e.getMessage()); } } } </code></pre> <p>These lines:</p> <pre><code> alert = json.getString("alert").toString(); name = json.getString("name").toString(); tipo = json.getString("tipo").toString(); DatosObjecto.setAlert(alert); DatosObjecto.setName(name); DatosObjecto.setTipo(tipo); </code></pre> <p>When I receive the push, I'm extracting the values of "alert", "name" and "tipo". I put them in an ObjetoMensaje Object. Code:</p> <pre><code>public class ObjetoMensaje extends Activity implements Serializable{ private static final long serialVersionUID = 5680898935329497057L; private String alert, name, tipo; protected String filename = "datos.dat"; public ObjetoMensaje(){}; public ObjetoMensaje(String alert, String name, String tipo){ super(); this.alert = alert; this.name = name; this.tipo = tipo; } public String getAlert(){ return alert; } public void setAlert(String alert){ this.alert = alert; Log.i("Set Alert", "Excitoso"); } public String getName(){ return name; } public void setName(String name){ this.name = name; Log.i("Set Name", "Excitoso"); } public String getTipo(){ return tipo; } public void setTipo(String tipo){ this.tipo = tipo; Log.i("Set tipo", "Excitoso"); } } </code></pre> <p>I want to serialize the values "alert", "name", and "tipo", so I've created a class for serialization:</p> <pre><code>public class SerializacionDeDatos extends Activity{ protected String filename = "datos.dat"; protected void Serializa(ObjetoMensaje DatosObjecto){ FileOutputStream fos; try { fos = openFileOutput(filename, Context.MODE_PRIVATE); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(DatosObjecto); oos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } </code></pre> <p>When I call the class, I get this error:</p> <pre><code>08-08 13:15:32.976: W/dalvikvm(8360): threadid=1: thread exiting with uncaught exception (group=0x4001c578) 08-08 13:15:33.070: E/AndroidRuntime(8360): FATAL EXCEPTION: main 08-08 13:15:33.070: E/AndroidRuntime(8360): java.lang.RuntimeException: Unable to start receiver mx.nivel9.apps.MyCustomReceiver: java.lang.NullPointerException 08-08 13:15:33.070: E/AndroidRuntime(8360): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1809) 08-08 13:15:33.070: E/AndroidRuntime(8360): at android.app.ActivityThread.access$2400(ActivityThread.java:117) 08-08 13:15:33.070: E/AndroidRuntime(8360): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985) 08-08 13:15:33.070: E/AndroidRuntime(8360): at android.os.Handler.dispatchMessage(Handler.java:99) 08-08 13:15:33.070: E/AndroidRuntime(8360): at android.os.Looper.loop(Looper.java:130) 08-08 13:15:33.070: E/AndroidRuntime(8360): at android.app.ActivityThread.main(ActivityThread.java:3687) 08-08 13:15:33.070: E/AndroidRuntime(8360): at java.lang.reflect.Method.invokeNative(Native Method) 08-08 13:15:33.070: E/AndroidRuntime(8360): at java.lang.reflect.Method.invoke(Method.java:507) 08-08 13:15:33.070: E/AndroidRuntime(8360): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 08-08 13:15:33.070: E/AndroidRuntime(8360): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625) 08-08 13:15:33.070: E/AndroidRuntime(8360): at dalvik.system.NativeStart.main(Native Method) 08-08 13:15:33.070: E/AndroidRuntime(8360): Caused by: java.lang.NullPointerException 08-08 13:15:33.070: E/AndroidRuntime(8360): at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:158) 08-08 13:15:33.070: E/AndroidRuntime(8360): at mx.nivel9.apps.SerializacionDeDatos.Serializa(SerializacionDeDatos.java:23) 08-08 13:15:33.070: E/AndroidRuntime(8360): at mx.nivel9.apps.MyCustomReceiver.onReceive(MyCustomReceiver.java:50) 08-08 13:15:33.070: E/AndroidRuntime(8360): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1798) 08-08 13:15:33.070: E/AndroidRuntime(8360): ... 10 more </code></pre> <p>What am I doing wrong?</p>
1
2,333
jQuery-ui / auto-complete / getJSON - How to pass the id of the element to the external PHP
<p>I'm binding the jQuery-ui autocomplete to more than one element in my page as I want to have autocomplete with the same set of options in different fields. Something like:</p> <pre><code>&lt;input class='myclass' id='myid1' name='field1' type='text' /&gt; &lt;input class='myclass' id='myid2' name='field2' type='text' /&gt; &lt;input class='myclass' id='myid3' name='field3' type='text' /&gt; </code></pre> <p>I'm using the "Multiple Remote" option from jquery-ui autocomplete, so the javascript looks something like this:</p> <pre><code>$(".myclass") // don't navigate away from the field on tab when selecting an item // don't navigate away from the field on tab when selecting an item .bind( "keydown", function(event) { if (event.keyCode === $.ui.keyCode.TAB &amp;&amp; $(this).data("autocomplete").menu.active) { event.preventDefault(); } }) .autocomplete({ source: function( request, response ) { $.getJSON("search.php" ,{ term:extractLast(request.term) } ,response); }, search: function() { // custom minLength var term = extractLast(this.value); if (term.length &lt; 1) { return false; } }, focus: function() { // prevent value inserted on focus return false; }, select: function( event, ui ) { var terms = split( this.value ); // remove the current input terms.pop(); // add the selected item terms.push(ui.item.value); // add placeholder to get the comma-and-space at the end terms.push(""); this.value = terms.join(", "); return false; } }); </code></pre> <p>It all works very nice. But I want to pass the id as a second parameter to getJSON. How can I accomplish this? </p> <p>I know how to add a second parameter to the <strong>$.getJSON</strong> statement, but I'm not being able to grab the <strong>"id"</strong> of the event trigger. I tried <strong>$(this).attr('id')</strong> but it gave me <em>undefined</em>. Any suggestions?</p> <p>Thanks.</p>
1
1,123
iphone pdf download
<pre><code> -(IBAction)click; { NSURL *url = [NSURL URLWithString:URL_TO_DOWNLOAD]; NSString *tempDownloadPath = [[self documentsDirectory] stringByAppendingPathComponent:@"test.pdf"]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setDownloadDestinationPath:[self documentsDirectory]]; [request setTemporaryFileDownloadPath:tempDownloadPath]; [request setDelegate:self]; [request startAsynchronous]; } - (void)requestFinished:(ASIHTTPRequest *)request { NSLog(@"requestFinished"); NSError *error; NSFileManager *fileManager = [[NSFileManager alloc] init]; NSLog(@"Documents directory: %@", [fileManager contentsOfDirectoryAtPath:[self documentsDirectory] error:&amp;error]); NSString *dir = [self documentsDirectory]; NSLog(dir); // NSData *responseData = [request responseData]; NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:&amp;error]; if (array == nil) { NSLog(@"array == nil"); } else { [aWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:tempDownloadPath]]]; [[self view] addSubview:aWebView]; } [fileManager release]; } - (NSString *)documentsDirectory { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); return [paths objectAtIndex:0]; } </code></pre> <p>I cant manage to check if the file exists before downloading again with an click, or actually displaying the pdf one the request has finished. Any solutions to this ?</p>
1
1,069
Flutter- Image picker package: show images one after another with delete action
<p>In my Flutter pr project, I am using <a href="https://pub.dev/packages/image_picker" rel="nofollow noreferrer">Image Picker</a> plugin to select images from the android mobile gallery or capture images with the camera and show them one after another with a delete icon below each image. On tapping the <code>RaisedButton</code> for selecting images from the gallery, the method <code>imageSelectorGallery()</code> is called. There inside the <code>setState()</code> method , I add a <code>SizedBox</code> and a <code>delete</code> icon to the <code>List</code> namely <code>images_captured</code>. I expect the <code>images_captured</code> to be rendered inside the <code>Column</code> in <code>SingleChildScrollView</code>.</p> <p>But after selecting an image from the gallery, nothing happens. I also want to tap on the <code>delete</code> icon and remove the image above it. But flutter has no data binding mechanism as I know to correlate the image with the delete button.</p> <p>Code follows:</p> <pre><code>class PrescriptionScreen extends StatefulWidget { @override State&lt;StatefulWidget&gt; createState() { return new UserOptionsState(); } } class UserOptionsState extends State&lt;PrescriptionScreen&gt; { //save the result of gallery fileUserOptions File galleryFile; //save the result of camera file File cameraFile; @override Widget build(BuildContext context) { var images_captured=List&lt;Widget&gt;(); //display image selected from gallery imageSelectorGallery() async { galleryFile = await ImagePicker.pickImage( source: ImageSource.gallery, // maxHeight: 50.0, // maxWidth: 50.0, ); print(&quot;You selected gallery image : &quot; + galleryFile.path); setState(() { var sized_box_indiv= new SizedBox( height: 200.0, width: 300.0, //child: new Card(child: new Text(''+galleryFile.toString())), //child: new Image.file(galleryFile), child: galleryFile == null ? new Text('Sorry nothing selected from gallery!!') : new Image.file(galleryFile), ); images_captured.add(sized_box_indiv); var delete_button = IconButton(icon: Icon(Icons.delete), onPressed: () {}); images_captured.add(delete_button); }); } //display image selected from camera imageSelectorCamera() async { cameraFile = await ImagePicker.pickImage( source: ImageSource.camera, //maxHeight: 50.0, //maxWidth: 50.0, ); print(&quot;You selected camera image : &quot; + cameraFile.path); setState(() {}); } return new SingleChildScrollView( child:Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: &lt;Widget&gt;[ new RaisedButton( child: new Text('Select Image from Gallery'), onPressed: imageSelectorGallery, ), new RaisedButton( child: new Text('Select Image from Camera'), onPressed: imageSelectorCamera, ), Column( children: images_captured ), ], ), ); /* }, ), );*/ } } </code></pre> <p>How to show the images selected from gallery one after another with a <code>delete</code> icon button below each of them?</p> <p>How to remove the corresponding image on tapping the <code>delete</code> icon button?</p> <p>I think if I can accomplish it for gallery, I can do it for camera capturing as well.</p> <p>I used the answer by jJuice and the images after being selected showed overflow error. The screenshot is given below:</p> <p><a href="https://i.stack.imgur.com/bbSrj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bbSrj.jpg" alt="" /></a></p> <p>My code is:</p> <pre><code>class UserOptionsState extends State&lt;PrescriptionScreen&gt; { //save the result of gallery fileUserOptions File galleryFile; //save the result of camera file File cameraFile; var images_captured=List&lt;Widget&gt;(); List&lt;File&gt; images = List&lt;File&gt;(); @override Widget build(BuildContext context) { //display image selected from gallery imageSelectorGallery() async { galleryFile = await ImagePicker.pickImage( source: ImageSource.gallery, // maxHeight: 50.0, // maxWidth: 50.0, ); images.add(galleryFile); print(&quot;You selected gallery image : &quot; + galleryFile.path); setState(() { }); } //display image selected from camera imageSelectorCamera() async { cameraFile = await ImagePicker.pickImage( source: ImageSource.camera, //maxHeight: 50.0, //maxWidth: 50.0, ); print(&quot;You selected camera image : &quot; + cameraFile.path); setState(() {}); } return new SingleChildScrollView( child:Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: &lt;Widget&gt;[ new RaisedButton( child: new Text('Select Image from Gallery'), onPressed: imageSelectorGallery, ), new RaisedButton( child: new Text('Select Image from Camera'), onPressed: imageSelectorCamera, ), new Container( // new Column( // children: &lt;Widget&gt;[ height: 1200, child:GridView.count( crossAxisSpacing: 6, mainAxisSpacing: 6, crossAxisCount: 3, children: List.generate(images.length, (index) { return Column( children: &lt;Widget&gt;[ Container( height: 200, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), ), child: ClipRRect( child: Image.file(images[index], fit: BoxFit.cover), borderRadius: BorderRadius.circular(10), ) ), GestureDetector( onTap: () { setState(() { images.removeAt(index); }); }, child: Padding( padding: const EdgeInsets.all(3.0), child: Align( alignment: Alignment.bottomCenter, child: Icon(Icons.clear, color: Colors.black, size: 20), ), ), ), ] ); } ), ), // ] ) /*displaySelectedFile(galleryFile), displaySelectedFile(cameraFile)*/ ], ), ); } Widget displaySelectedFile(File file) { return new SizedBox( height: 200.0, width: 300.0, //child: new Card(child: new Text(''+galleryFile.toString())), //child: new Image.file(galleryFile), child: file == null ? new Text('Sorry nothing selected!!') : new Image.file(file), ); } } </code></pre>
1
3,451
Control Two HTML Tables With One Scroll Bar
<p>I have two separate tables of hopefully same height side by side. I want to be able to have the two communicate with each other so that when I scroll the right table down, the left table will also scroll with it in sync. </p> <p>As of now, the only way I could think of doing this is by enclosing both of them in a div, but this messes with my sizing settings when I try so. Is there a better way of having the two tables communicate and scroll up and down at the same time?</p> <p>HTML:</p> <pre><code>&lt;!-- Scrollable y-axis line of days above the scheduler --&gt; &lt;div id="table-wrapper-days"&gt; &lt;div id="table-scroll-days"&gt; &lt;table id="dayRow" class="tableDays"&gt; &lt;tr&gt; &lt;td&gt;Monday 5/7&lt;/td&gt; &lt;td&gt;Tuesday 5/8&lt;/td&gt; &lt;td&gt;Wednesday 5/9&lt;/td&gt; &lt;td&gt;Thursday 5/10&lt;/td&gt; &lt;td&gt;Friday 5/11&lt;/td&gt; &lt;td&gt;Saturday 5/12&lt;/td&gt; &lt;td&gt;Sunday 5/13&lt;/td&gt; &lt;td&gt;Monday 5/14&lt;/td&gt; &lt;td&gt;Tuesday 5/15&lt;/td&gt; &lt;td&gt;Wednesday 5/16&lt;/td&gt; &lt;td&gt;Thursday 5/17&lt;/td&gt; &lt;td&gt;Friday 5/18&lt;/td&gt; &lt;td&gt;Saturday 5/19&lt;/td&gt; &lt;td&gt;Sunday 5/20&lt;/td&gt; &lt;td&gt;Monday 5/21&lt;/td&gt; &lt;td&gt;Tuesday 5/22&lt;/td&gt; &lt;td&gt;Wednesday 5/23&lt;/td&gt; &lt;td&gt;Thursday 5/24&lt;/td&gt; &lt;td&gt;Friday 5/25&lt;/td&gt; &lt;td&gt;Saturday 5/26&lt;/td&gt; &lt;td&gt;Sunday 5/27&lt;/td&gt; &lt;td&gt;Monday 5/28&lt;/td&gt; &lt;td&gt;Tuesday 5/29&lt;/td&gt; &lt;td&gt;Wednesday 5/30&lt;/td&gt; &lt;td&gt;Thursday 5/31&lt;/td&gt; &lt;td&gt;Friday 6/1&lt;/td&gt; &lt;td&gt;Saturday 6/2&lt;/td&gt; &lt;td&gt;Sunday 6/3&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Scrollable x-axis column of employees to the left of the scheduler --&gt; &lt;div id="table-wrapper-employees"&gt; &lt;div id="table-scroll-employees"&gt; &lt;table id="employeeCol" class="tableEmployees"&gt; &lt;tr&gt;&lt;td&gt;Employee A&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee B&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee C&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee D&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee E&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee F&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee G&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee H&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee I&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee J&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee K&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee L&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee M&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee N&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee O&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee P&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee Q&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee R&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee S&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee T&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee U&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee V&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee W&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee X&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee Y&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Employee Z&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="table-wrapper-tasks"&gt; &lt;div id="table-scroll-tasks"&gt; &lt;script&gt; var rows = document.getElementById('dayRow').getElementsByTagName("td").length; var cols = document.getElementById('employeeCol').getElementsByTagName("tr").length; var rowT = null; var drawTable = '&lt;table class="tableTasks"&gt;'; for (let i = 0; i &lt; rows; i++) { drawTable += '&lt;tr&gt;'; for(let j = 0; j &lt; cols; j++) { drawTable += '&lt;td&gt;&lt;/td&gt;'; } drawTable += '&lt;/tr&gt;'; } drawTable += '&lt;/table&gt;'; document.write(drawTable); &lt;/script&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>/* To control the style of the overall table class */ table { border: 1px solid black; text-align: center; table-layout: fixed; } th, td { border: 1px solid black; width: 140px; height: 35px; } /* Settings for Days row */ .tableDays { width: 140px; } /* Settings for Employee column */ .tableEmployees { line-height: 35px; } /* Settings for Tasks table */ .tableTasks { width:100%; margin-top:5px; empty-cells: show; height:1000px; line-height: 35px; width: 100px; } .empTaskCont { height: 500px; width: 100%; overflow-x: hidden; overflow-y: scroll; position: relative; padding-bottom: 30px; } #table-wrapper-days { position: relative; width:1064px; margin-left: 252px } #table-scroll-days { height: auto; overflow-x: scroll; } #table-wrapper-employees { position: relative; float:left; width:18%; margin-top:8px; } #table-scroll-employees { width: auto; overflow-y: scroll; max-height: 500px; } #table-wrapper-tasks { position: relative; width:81%; float:right; } #table-scroll-tasks { overflow-x: scroll; overflow-y: scroll; max-height: 522px; } .employee-mod-btn{ float:left; } </code></pre> <p>I included a jsfiddle for my code: <a href="https://jsfiddle.net/Lqzyw4u4/6/#&amp;togetherjs=5vkFrp9DEa" rel="nofollow noreferrer">https://jsfiddle.net/Lqzyw4u4/6/#&amp;togetherjs=5vkFrp9DEa</a></p> <p>Thank you for your time.</p>
1
3,245
How to git clone with maven that uses an ssh-agent?
<p>I want to clone a repository with maven and the authentication must use an existing ssh-agent.</p> <p>My current plugin configuration:</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-scm-plugin&lt;/artifactId&gt; &lt;version&gt;1.9.4&lt;/version&gt; &lt;configuration&gt; &lt;providerImplementations&gt; &lt;git&gt;jgit&lt;/git&gt; &lt;/providerImplementations&gt; &lt;/configuration&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.maven.scm&lt;/groupId&gt; &lt;artifactId&gt;maven-scm-provider-jgit&lt;/artifactId&gt; &lt;version&gt;1.9.4&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;clone-github-wiki&lt;/id&gt; &lt;goals&gt; &lt;goal&gt;checkout&lt;/goal&gt; &lt;/goals&gt; &lt;phase&gt;generate-resources&lt;/phase&gt; &lt;configuration&gt; &lt;checkoutDirectory&gt;${project.basedir}/target/github-wiki&lt;/checkoutDirectory&gt; &lt;connectionType&gt;connection&lt;/connectionType&gt; &lt;connectionUrl&gt;scm:git:git@github.com:xyz/abc.wiki.git&lt;/connectionUrl&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <p>Authentication is failing:</p> <pre><code>[INFO] --- maven-scm-plugin:1.9.4:checkout (clone-github-wiki) @ xyz-doc --- [INFO] Change the default 'git' provider implementation to 'jgit'. [INFO] Removing /home/jenkins/abc/doc/target/github-wiki [INFO] cloning [master] to /home/jenkins/abc/doc/target/github-wiki [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1.490 s [INFO] Finished at: 2015-10-14T11:45:40+02:00 [INFO] Final Memory: 15M/241M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.apache.maven.plugins:maven-scm-plugin:1.9.4:checkout (clone-github-wiki) on project xyz-doc: Cannot run checkout command : Exception while executing SCM command. JGit checkout failure! git@github.com:abc/xyz.wiki.git: Auth fail -&gt; [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: </code></pre>
1
1,169
React navigation with hooks and header function - state is not updating
<p>Trying to use react navigation with hooks and a button in the navigation header.</p> <p>I can pass the handleShowModalLogin function to the navigation header and I can see the button is clicked, but the problem is the setShowLoginModal is not updating the showLoginModal state to true. Not sure why this is not working.</p> <pre><code>import React, { useState, useEffect, useLayoutEffect } from "react"; import { Image, Platform, ScrollView, StyleSheet, Text, TouchableOpacity, View, Button, } from 'react-native'; import LoginModal from './users/LoginModal'; const HomeScreen = ({navigation}, props) =&gt; { const [showLoginModal, setShowLoginModal] = useState(false); const handleShowModalLogin = (value) =&gt; { console.log("showLoginModal button clicked: ", value) if(value === "on"){ setShowLoginModal(true); }else{ setShowLoginModal(false); } } useEffect(() =&gt; { console.log('navigation handler set with showLoginModal set:', showLoginModal) navigation.setParams({ handleShowModalLogin: handleShowModalLogin }); }, []); useEffect(() =&gt; { console.log("showLoginModal value changed: ", showLoginModal), [showLoginModal] }) return ( &lt;View style={styles.container}&gt; &lt;LoginModal showLoginModal={showLoginModal} /&gt; &lt;ScrollView style={styles.container} contentContainerStyle={styles.contentContainer}&gt; &lt;/ScrollView&gt; &lt;/View&gt; ); }; HomeScreen.navigationOptions = ({ navigation }) =&gt; ({ title: "Home", headerRight: ( &lt;View style={styles.headerComContainer}&gt; &lt;Button onPress={() =&gt; { navigation.getParam('handleShowModalLogin')('on') }} title="Login" color="#841584" accessibilityLabel="Login" /&gt; &lt;/View&gt; ) }); </code></pre> <p>Here's the login modal component.</p> <pre><code>import React, { useState } from "react"; import { Text, TouchableOpacity, View, ScrollView } from "react-native"; import Modal from 'modal-enhanced-react-native-web'; export default function LoginModal(props){ const [visibleModal, setModalVisible] = useState(props.showLoginModal); return ( &lt;View&gt; &lt;Modal isVisible={visibleModal} onBackdropPress={() =&gt; setModalVisible(false)} &gt; &lt;View&gt; &lt;Text&gt;Hello!&lt;/Text&gt; &lt;TouchableOpacity onPress={() =&gt; setModalVisible(false)}&gt; &lt;View&gt; &lt;Text&gt;Close&lt;/Text&gt; &lt;/View&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; &lt;/Modal&gt; &lt;/View&gt; ); } </code></pre>
1
1,127
JTable inside a JScrollPane not showing up properly
<p>I am working on a the GUI of a piece of code that I have been patching together. I am stuck at this part of the program where I would like a datafile the user chooses to be displayed in a <code>JTable</code> in a preview manner (i.e. the user should not be able to edit the data on the table).</p> <p>With a button click from Experiment Parameters tab (see screenshot below), I create and run a "PreviewAction" which creates a new tab, and fills it up with the necessary components. Below is the code for <code>DataPreviewAction</code>. <strong>EDIT:</strong> I also posted a <a href="http://pastebin.com/HxTZyMiW" rel="nofollow noreferrer">self-contained, minimal version</a> of this that mimics the conditions in the real project, and exhibits the same behaviour. </p> <pre><code>import java.awt.BorderLayout; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel; public class MyFrame extends JFrame { private JPanel panel1; private JTabbedPane tabs; private JButton runButton; public MyFrame() { tabs = new JTabbedPane(); panel1 = new JPanel(); runButton = new JButton("go!"); runButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { runButtonActionPerformed(evt); } }); panel1.add(runButton); tabs.addTab("first tab", panel1); this.add(tabs); pack(); } public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager .getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MyFrame.class.getName()).log( java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MyFrame.class.getName()).log( java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MyFrame.class.getName()).log( java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MyFrame.class.getName()).log( java.util.logging.Level.SEVERE, null, ex); } /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { MyFrame frame = new MyFrame(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } private void runButtonActionPerformed(java.awt.event.ActionEvent evt) { /* * Normally there is more stuff happening here but this much will do for * the sake of example */ List&lt;String[]&gt; data = new LinkedList&lt;String[]&gt;(); for (int i = 1; i &lt; 1000; i++) data.add(new String[] { "entry1", "value1", "value2", "value3" }); SwingUtilities.invokeLater(new DataPreviewAction(data, tabs)); } public class DataPreviewAction implements Runnable { private JTabbedPane contentHolder; private List&lt;String[]&gt; data; public DataPreviewAction(List&lt;String[]&gt; data, JTabbedPane comp) { this.contentHolder = comp; this.data = data; } @Override public void run() { DefaultTableModel previewModel = new DefaultTableModel() { @Override public boolean isCellEditable(int row, int column) { return false; } }; for (String[] datarow : data) { previewModel.addRow(Arrays.copyOf(datarow, datarow.length, Object[].class)); } JTable table = new JTable(previewModel); JPanel buttonPanel = new JPanel(); buttonPanel.add(new JButton("A button")); buttonPanel.add(new JLabel( "Some description for the awesome table below ")); buttonPanel.add(new JButton("another button")); JScrollPane tablePanel = new JScrollPane(table); JPanel container = new JPanel(); container.setLayout(new BorderLayout()); container.add(buttonPanel, BorderLayout.NORTH); container.add(tablePanel, BorderLayout.CENTER); contentHolder.addTab("Preview", container); contentHolder.validate(); contentHolder.repaint(); } } } </code></pre> <p>There are at least two problems here:</p> <ol> <li>The <code>JTable</code> (or the <code>JScrollPane</code>) does not render at all</li> <li>The <code>JScrollPane</code> is not as wide as the frame itself, I have no idea why</li> </ol> <p>I am not all that good in Swing so I might be missing something fundamental. I have checked that the datafile is read properly, and the data model contains the right amount of rows (1000+). SO the table should not be empty. </p> <p>Suggestions?</p> <p><img src="https://i.stack.imgur.com/8hkfU.png" alt="screenshot of the problem"></p>
1
2,178
Stackoverflow: too many recursive calls ? in C
<p>I'm trying to go through a huge graph (around 875000 nodes and 5200000 edges) but I'm getting a stackoverflow. I have a recursive function to loop through it. It will explore only the non-explored nodes so there is no way it goes into an infinite recursion. (or at least I think) My recursive function works for smaller inputs (5000 nodes).</p> <p>What should I do? Is there a maximum number of successful recursive call?</p> <p>I'm really clueless.</p> <p>EDIT: I have posted the iterative equivalent at the end as well.</p> <p>Here is the code of the recursion:</p> <pre><code>int main() { int *sizeGraph,i,**reverseGraph; // some code to initialize the arrays getGgraph(1,reverseGraph,sizeGraph); // populate the arrays with the input from a file getMagicalPath(magicalPath,reverseGraph,sizeGraph); return 0; } void getMagicalPath(int *magicalPath,int **graph,int *sizeGraph) { int i; int *exploredNode; /* ------------- creation of the list of the explored nodes ------------------ */ if ((exploredNode =(int*) malloc((ARRAY_SIZE + 1) * sizeof(exploredNode[0]))) == NULL) { printf("malloc of exploredNode error\n"); return; } memset(exploredNode, 0, (ARRAY_SIZE + 1) * sizeof(exploredNode[0])); // start byt the "last" node for (i = ARRAY_SIZE; i &gt; 0; i--) { if (exploredNode[i] == 0) runThroughGraph1stLoop(i,graph,exploredNode,magicalPath,sizeGraph); } free(exploredNode); } /* * run through from the node to each adjacent node which will run to each adjacent node etc... */ void runThroughGraph1stLoop(int node,int **graph,int *exploredNode,int *magicalPath,int *sizeGraph) { //printf("node = %d\n",node); int i = 0; exploredNode[node] = 1; for (i = 0; i &lt; sizeGraph[node]; i++) { if (exploredNode[graph[node][i]] == 0) { runThroughGraph1stLoop(graph[node][i],graph,exploredNode,magicalPath,sizeGraph); } } magicalPath[0]++; // as index 0 is not used, we use it to remember the size of the array; quite durty i know magicalPath[magicalPath[0]] = node; } </code></pre> <p>The iterative equivalent of the above:</p> <pre><code>struct stack_t { int node; int curChildIndex; }; void getMagicalPathIterative(int *magicalPath,int **graph,int *sizeGraph) { int i,k,m,child,unexploredNodeChild,curStackPos = 0,*exploredNode; bool foundNode; stack_t* myStack; if ((myStack = (stack_t*) malloc((ARRAY_SIZE + 1) * sizeof(myStack[0]))) == NULL) { printf("malloc of myStack error\n"); return; } if ((exploredNode =(int*) malloc((ARRAY_SIZE + 1) * sizeof(exploredNode[0]))) == NULL) { printf("malloc of exploredNode error\n"); return; } memset(exploredNode, 0, (ARRAY_SIZE + 1) * sizeof(exploredNode[0])); for (i = ARRAY_SIZE; i &gt; 0; i--) { if (exploredNode[i] == 0) { curStackPos = 0; myStack[curStackPos].node = i; myStack[curStackPos].curChildIndex = (sizeGraph[myStack[curStackPos].node] &gt; 0) ? 0 : -1; while(curStackPos &gt; -1 &amp;&amp; myStack[curStackPos].node &gt; 0) { exploredNode[myStack[curStackPos].node] = 1; if (myStack[curStackPos].curChildIndex == -1) { magicalPath[0]++; magicalPath[magicalPath[0]] = myStack[curStackPos].node; // as index 0 is not used, we use it to remember the size of the array myStack[curStackPos].node = 0; myStack[curStackPos].curChildIndex = 0; curStackPos--; } else { foundNode = false; for(k = 0;k &lt; sizeGraph[myStack[curStackPos].node] &amp;&amp; !foundNode;k++) { if (exploredNode[graph[myStack[curStackPos].node][k]] == 0) { myStack[curStackPos].curChildIndex = k; foundNode = true; } } if (!foundNode) myStack[curStackPos].curChildIndex = -1; if (myStack[curStackPos].curChildIndex &gt; -1) { foundNode = false; child = graph[myStack[curStackPos].node][myStack[curStackPos].curChildIndex]; unexploredNodeChild = -1; if (sizeGraph[child] &gt; 0) { // get number of adjacent nodes of the current child for(k = 0;k &lt; sizeGraph[child] &amp;&amp; !foundNode;k++) { if (exploredNode[graph[child][k]] == 0) { unexploredNodeChild = k; foundNode = true; } } } // push into the stack the child if not explored myStack[curStackPos + 1].node = graph[myStack[curStackPos].node][myStack[curStackPos].curChildIndex]; myStack[curStackPos + 1].curChildIndex = unexploredNodeChild; curStackPos++; } } } } } } </code></pre>
1
2,543
Python read-only lists using the property decorator
<h2>Short Version</h2> <p>Can I make a read-only list using Python's property system?</p> <h2>Long Version</h2> <p>I've created a Python class that has a list as a member. Internally, I'd like it to do something every time the list is modified. If this were C++, I'd create getters and setters that would allow me to do my bookkeeping whenever the setter was called, and I'd have the getter return a <code>const</code> reference, so that the compiler would yell at me if I tried to do modify the list through the getter. In Python, we have the property system, so that writing vanilla getters and setters for every data member is (thankfully) no longer necessary. However, consider the following script:</p> <pre><code>def main(): foo = Foo() print('foo.myList:', foo.myList) # Here, I'm modifying the list without doing any bookkeeping. foo.myList.append(4) print('foo.myList:', foo.myList) # Here, I'm modifying my "read-only" list. foo.readOnlyList.append(8) print('foo.readOnlyList:', foo.readOnlyList) class Foo: def __init__(self): self._myList = [1, 2, 3] self._readOnlyList = [5, 6, 7] @property def myList(self): return self._myList @myList.setter def myList(self, rhs): print("Insert bookkeeping here") self._myList = rhs @property def readOnlyList(self): return self._readOnlyList if __name__ == '__main__': main() </code></pre> <p>Output:</p> <pre><code>foo.myList: [1, 2, 3] # Note there's no "Insert bookkeeping here" message. foo.myList: [1, 2, 3, 4] foo.readOnlyList: [5, 6, 7, 8] </code></pre> <p>This illustrates that the absence of the concept of <code>const</code> in Python allows me to modify my list using the <code>append()</code> method, despite the fact that I've made it a property. This can bypass my bookkeeping mechanism (<code>_myList</code>), or it can be used to modify lists that one might like to be read-only (<code>_readOnlyList</code>).</p> <p>One workaround would be to return a deep copy of the list in the getter method (i.e. <code>return self._myList[:]</code>). This could mean a lot of extra copying, if the list is large or if the copy is done in an inner loop. (But premature optimization is the root of all evil, anyway.) In addition, while a deep copy would prevent the bookkeeping mechanism from being bypassed, if someone were to call <code>.myList.append()</code> , their changes would be silently discarded, which could generate some painful debugging. It would be nice if an exception were raised, so that they'd know they were working against the class' design.</p> <p>A fix for this last problem would be not to use the property system, and make "normal" getter and setter methods:</p> <pre><code>def myList(self): # No property decorator. return self._myList[:] def setMyList(self, myList): print('Insert bookkeeping here') self._myList = myList </code></pre> <p>If the user tried to call <code>append()</code>, it would look like <code>foo.myList().append(8)</code>, and those extra parentheses would clue them in that they might be getting a copy, rather than a reference to the internal list's data. The negative thing about this is that it is kind of un-Pythonic to write getters and setters like this, and if the class has other list members, I would have to either write getters and setters for those (eww), or make the interface inconsistent. (I think a slightly inconsistent interface might be the least of all evils.)</p> <p>Is there another solution I'm missing? Can one make a read-only list using Pyton's property system?</p> <h2>Edit: Solution</h2> <p>The two main suggestions seem to be either using a tuple as a read-only list, or subclassing list. I like both of those approaches. Returning a tuple from the getter, or using a tuple in the first place, prevents one from using the += operator, which can be a useful operator and also triggers the bookkeeping mechanism by calling the setter. However, returning a tuple is a one-line change, which is nice if you would like to program defensively but judge that adding a whole other class to your script might be unnecessarily complicated. (It can be a good sometimes to be minimalist and assume You Ain't Gonna Need It.)</p> <p>Here is an updated version of the script which illustrates both approaches, for anyone finding this via Google.</p> <pre><code>import collections def main(): foo = Foo() print('foo.myList:', foo.myList) try: foo.myList.append(4) except RuntimeError: print('Appending prevented.') # Note that this triggers the bookkeeping, as we would like. foo.myList += [3.14] print('foo.myList:', foo.myList) try: foo.readOnlySequence.append(8) except AttributeError: print('Appending prevented.') print('foo.readOnlySequence:', foo.readOnlySequence) class UnappendableList(collections.UserList): def __init__(self, *args, **kwargs): data = kwargs.pop('data') super().__init__(self, *args, **kwargs) self.data = data def append(self, item): raise RuntimeError('No appending allowed.') class Foo: def __init__(self): self._myList = [1, 2, 3] self._readOnlySequence = [5, 6, 7] @property def myList(self): return UnappendableList(data=self._myList) @myList.setter def myList(self, rhs): print('Insert bookkeeping here') self._myList = rhs @property def readOnlySequence(self): # or just use a tuple in the first place return tuple(self._readOnlySequence) if __name__ == '__main__': main() </code></pre> <p>Output:</p> <pre><code>foo.myList: [1, 2, 3] Appending prevented. Insert bookkeeping here foo.myList: [1, 2, 3, 3.14] Appending prevented. foo.readOnlySequence: (5, 6, 7) </code></pre> <p>Thanks, everyone.</p>
1
1,975
Get GPS data while App is running background in Android using LocationListener
<p>i have problem with my Android application.I need an application that will get in background GPS location while open another application.application run in background but i want to also get GPS location in background.</p> <p>create start and stop button for get gps location it work properly but when click on home button gps stop to gettting location</p> <p>Here is My code..</p> <pre><code> public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gps); /* get TextView to display the GPS data */ txtLat = (TextView) findViewById(R.id.textview1); /* the location manager is the most vital part it allows access * to location and GPS status services */ locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER ,10000,10, this); // locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000L, 0, this); btnShow = (Button) findViewById(R.id.btnstart); btnStop = (Button) findViewById(R.id.btnstop); btnShow.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Toast.makeText(getBaseContext(), "Trip Start.", Toast.LENGTH_SHORT).show(); txtLat.setVisibility(View.VISIBLE); onResume(); btnShow.setEnabled(false); btnStop.setEnabled(true); } }); Button btnstop = (Button) findViewById(R.id.btnstop); btnstop.setOnClickListener(new OnClickListener() { public void onClick(View v) { onPause(); Toast.makeText(getBaseContext(), "Trip Ended.", Toast.LENGTH_SHORT).show(); btnShow.setEnabled(true); btnStop.setEnabled(false); } }); } public void onLocationChanged(Location location) { if (location == null) { Toast.makeText(getApplicationContext(),"Searching for your location.", Toast.LENGTH_SHORT).show(); locationManager.requestLocationUpdates(provider, 10000, 10,locationListener); onLocationChanged(location); } else { double cell_lat=location.getLatitude(); double cell_long=location.getLongitude(); double altitude=location.getAltitude(); double accuracy=location.getAccuracy(); String status="true"; sb = new StringBuilder(512); noOfFixes++; /* display some of the data in the TextView */ sb.append("Tracking: "); sb.append(noOfFixes); sb.append('\n'); sb.append('\n'); sb.append("Londitude: "); sb.append(location.getLongitude()); sb.append('\n'); sb.append("Latitude: "); sb.append(location.getLatitude()); sb.append('\n'); sb.append("Altitiude: "); sb.append(location.getAltitude()); sb.append('\n'); sb.append("Accuracy: "); sb.append(location.getAccuracy()); sb.append("ft"); sb.append('\n'); txtLat.setText(sb.toString()); } public void onProviderDisabled(String provider) { /* this is called if/when the GPS is disabled in settings */ Log.v(tag, "Disabled"); /* bring up the GPS settings */ Intent intent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } public void onProviderEnabled(String provider) { Log.v(tag, "Enabled"); Toast.makeText(this, "GPS Enabled", Toast.LENGTH_SHORT).show(); } public void onStatusChanged(String provider, int status, Bundle extras) { /* This is called when the GPS status alters */ switch (status) { case LocationProvider.OUT_OF_SERVICE: Log.v(tag, "Status Changed: Out of Service"); Toast`enter code here`.makeText(this, "Status Changed: Out of Service", Toast.LENGTH_SHORT).show(); break; case LocationProvider.TEMPORARILY_UNAVAILABLE: Log.v(tag, "Status Changed: Temporarily Unavailable"); Toast.makeText(this, "Status Changed: Temporarily Unavailable", Toast.LENGTH_SHORT).show(); break; case LocationProvider.AVAILABLE: Log.v(tag, "Status Changed: Available"); Toast.makeText(this, "Status Changed: Available", Toast.LENGTH_SHORT).show(); break; } } @Override protected void onResume() { /* * onResume is is always called after onStart, even if the app hasn't been * paused * * add location listener and request updates every 1000ms or 10m */ locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10f, this); super.onResume(); } @Override protected void onPause() { /* GPS, as it turns out, consumes battery like crazy */ locationManager.removeUp`enter code here`dates(this); super.onPause(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_HOME)) { System.out.println("KEYCODE_HOME"); Toast.makeText(getBaseContext(), "Home Button.", Toast.LENGTH_SHORT).show(); this.moveTaskToBack(true); //showDialog("'HOME'"); return true; } if ((keyCode == KeyEvent.KEYCODE_BACK)) { System.out.println("KEYCODE_BACK"); finish(); showDialog("'BACK'"); return true; } if ((keyCode == KeyEvent.KEYCODE_MENU)) { System.out.println("KEYCODE_MENU"); //showDialog("'MENU'"); return true; } return false; } void showDialog(String the_key){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("You have pressed the " + the_key + " button. Would you like to exit the app?") .setCancelable(true) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); finish(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.setTitle("GPS."); alert.show(); } </code></pre>
1
4,136
Add extra header to email VB ASP 3.0 script
<p>I'm working with a web app in VB ASP 3.0. I have the following code to send an email:</p> <pre><code> Const cdoSendUsingMethod = _ "http://schemas.microsoft.com/cdo/configuration/sendusing" Const cdoSendUsingPort = 2 Const cdoSMTPServer = _ "http://schemas.microsoft.com/cdo/configuration/smtpserver" Const cdoSMTPServerPort = _ "http://schemas.microsoft.com/cdo/configuration/smtpserverport" Const cdoSMTPConnectionTimeout = _ "http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout" Const cdoSMTPAuthenticate = _ "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate" Const cdoBasic = 1 Const cdoSendUserName = _ "http://schemas.microsoft.com/cdo/configuration/sendusername" Const cdoSendPassword = _ "http://schemas.microsoft.com/cdo/configuration/sendpassword" Set objMessage = CreateObject("CDO.Message") objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2 objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1 objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="xxxxxxx" objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="xxxxxxx" objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl")=false objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.socketlabs.com" objMessage.Configuration.Fields.Update fFromEmail = "xxx@xxx.com" fFromAlias = "Display name" fReplyTo = "xxx@xxx.com" if isObject(objMessage) then With objMessage .To = fToEmail .Cc = fCCEmail .Bcc = fBCCEmail .From = fFromAlias &amp; "&lt;" &amp; fFromEmail &amp; "&gt;" .Subject = fSubject .HTMLBody = fEmailBody .Send End With SendEmail = summaryEmailBody Set objMessage = Nothing End If </code></pre> <p>This script works, but now I need to add an extra header. But I can't find how to do so when not in a .net framework.</p> <p>I tried adding the following line:</p> <pre><code> objMessage.Configuration.Fields.Item("urn:schemas:mailheader:X-xsMailingId") = "clientName" </code></pre> <p>but it didn't work. Any help will be greatly appreciated.</p>
1
1,169
TDD for Web API with NUnit, NSubtitute
<p>I'm still confused with some TDD concepts and how to do it correctly. I'm trying to use it implement for a new project using Web API. I have read a lot about it, and some article suggest NUnit as a testing framework and NSubstitute to mock the repository.</p> <p>What I don't understand is with NSubstitute we can define the expected result of what we want, is this valid if we want to validate our code logic?</p> <p>Let's say I have a controller like this with <code>Put</code> and <code>Delete</code> method:</p> <pre><code>[BasicAuthentication] public class ClientsController : BaseController { // Dependency injection inputs new ClientsRepository public ClientsController(IRepository&lt;ContactIndex&gt; clientRepo) : base(clientRepo) { } [HttpPut] public IHttpActionResult PutClient(string accountId, long clientId, [FromBody] ClientContent data, string userId = "", string deviceId = "", string deviceName = "") { var result = repository.UpdateItem(new CommonField() { AccountId = accountId, DeviceId = deviceId, DeviceName = deviceName, UserId = userId }, clientId, data); if (result.Data == null) { return NotFound(); } if (result.Data.Value != clientId) { return InternalServerError(); } IResult&lt;IDatabaseTable&gt; updatedData = repository.GetItem(accountId, clientId); if (updatedData.Error) { return InternalServerError(); } return Ok(updatedData.Data); } [HttpDelete] public IHttpActionResult DeleteClient(string accountId, long clientId, string userId = "", string deviceId = "") { var endResult = repository.DeleteItem(new CommonField() { AccountId = accountId, DeviceId = deviceId, DeviceName = string.Empty, UserId = userId }, clientId); if (endResult.Error) { return InternalServerError(); } if (endResult.Data &lt;= 0) { return NotFound(); } return Ok(); } } </code></pre> <p>and I create some unit tests like this:</p> <pre><code>[TestFixture] public class ClientsControllerTest { private ClientsController _baseController; private IRepository&lt;ContactIndex&gt; clientsRepository; private string accountId = "account_id"; private string userId = "user_id"; private long clientId = 123; private CommonField commonField; [SetUp] public void SetUp() { clientsRepository = Substitute.For&lt;IRepository&lt;ContactIndex&gt;&gt;(); _baseController = new ClientsController(clientsRepository); commonField = new CommonField() { AccountId = accountId, DeviceId = string.Empty, DeviceName = string.Empty, UserId = userId }; } [Test] public void PostClient_ContactNameNotExists_ReturnBadRequest() { // Arrange var data = new ClientContent { shippingName = "TestShippingName 1", shippingAddress1 = "TestShippingAdress 1" }; clientsRepository.CreateItem(commonField, data) .Returns(new Result&lt;long&gt; { Message = "Bad Request" }); // Act var result = _baseController.PostClient(accountId, data, userId); // Asserts Assert.IsInstanceOf&lt;BadRequestErrorMessageResult&gt;(result); } [Test] public void PutClient_ClientNotExists_ReturnNotFound() { // Arrange var data = new ClientContent { contactName = "TestContactName 1", shippingName = "TestShippingName 1", shippingAddress1 = "TestShippingAdress 1" }; clientsRepository.UpdateItem(commonField, clientId, data) .Returns(new Result&lt;long?&gt; { Message = "Data Not Found" }); var result = _baseController.PutClient(accountId, clientId, data, userId); Assert.IsInstanceOf&lt;NotFoundResult&gt;(result); } [Test] public void PutClient_UpdateSucceed_ReturnOk() { // Arrange var postedData = new ClientContent { contactName = "TestContactName 1", shippingName = "TestShippingName 1", shippingAddress1 = "TestShippingAdress 1" }; var expectedResult = new ContactIndex() { id = 123 }; clientsRepository.UpdateItem(commonField, clientId, postedData) .Returns(new Result&lt;long?&gt; (123) { Message = "Data Not Found" }); clientsRepository.GetItem(accountId, clientId) .Returns(new Result&lt;ContactIndex&gt; ( expectedResult )); // Act var result = _baseController.PutClient(accountId, clientId, postedData, userId) .ShouldBeOfType&lt;OkNegotiatedContentResult&lt;ContactIndex&gt;&gt;(); // Assert result.Content.ShouldBe(expectedResult); } [Test] public void DeleteClient_ClientNotExists_ReturnNotFound() { clientsRepository.Delete(accountId, userId, "", "", clientId) .Returns(new Result&lt;int&gt;() { Message = "" }); var result = _baseController.DeleteClient(accountId, clientId, userId); Assert.IsInstanceOf&lt;NotFoundResult&gt;(result); } [Test] public void DeleteClient_DeleteSucceed_ReturnOk() { clientsRepository.Delete(accountId, userId, "", "", clientId) .Returns(new Result&lt;int&gt;(123) { Message = "" }); var result = _baseController.DeleteClient(accountId, clientId, userId); Assert.IsInstanceOf&lt;OkResult&gt;(result); } } </code></pre> <p>Looking at the code above, am I writing my unit tests correctly? I feel like I'm not sure how it will validate the logic in my controller.</p> <p>Please ask for more information, if there is anything that needs clarified.</p>
1
3,109
orm.xml does not override annotations
<p>I ran into an issue where JPA on Derby defaults the BLOB size to 64KB. I can resolve this by setting the <strong>columnDefinition="BLOB(128M)"</strong>. However, this fails during integration testing against another RDBMS like MS SQL. What I'd like to do is set the columnDefinition using the orm.xml. However, my attempts have been futile and am unable to get this to work. It doesn't appear that the values set in <strong>orm.xml</strong> are overriding the annotations as I would expect.</p> <p>I am using JPA 1.0, Toplink Essentials 2.1.60.</p> <p>I have the following entity annotated as such:</p> <pre><code>package foo; @Entity @Table(name = "Attachment") public class Attachment implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Version @Column(name = "VERSION") private Integer version; @Column(name = "FILE_NAME", nullable = false) private String name; @Lob @Basic @Column(name = "ATTACHED_FILE", nullable = false) private byte[] file; } </code></pre> <p>persistence.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"&gt; &lt;persistence-unit name="LAS-OOC" transaction-type="RESOURCE_LOCAL"&gt; &lt;provider&gt;${jpa.provider}&lt;/provider&gt; &lt;!-- this isn't required, i know, but I'm trying everything I can think of --&gt; &lt;mapping-file&gt;META-INF/orm.xml&lt;/mapping-file&gt; &lt;class&gt;foo.Attachment&lt;/class&gt; &lt;properties&gt; ... &lt;/properties&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </code></pre> <p>orm.xml (located in META-INF)</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0"&gt; &lt;persistence-unit-metadata&gt; &lt;persistence-unit-defaults&gt; &lt;schema&gt;TEST&lt;/schema&gt; &lt;/persistence-unit-defaults&gt; &lt;/persistence-unit-metadata&gt; &lt;entity class="foo.Attachment" access="FIELD" &gt; &lt;attributes&gt; &lt;basic name="file"&gt; &lt;!-- I'm using maven profiles to set the 'jpa.blob.definition' property. I even tried changing the column name. --&gt; &lt;column nullable="true" name="ATTACHED_FILE_MODIFIED" column-definition="${jpa.blob.definition}" /&gt; &lt;/basic&gt; &lt;/attributes&gt; &lt;/entity&gt; &lt;/entity-mappings&gt; </code></pre> <p>It IS interesting to note that if I change the entity class or basic name attribute in the orm.xml it complains that it's invalid/not found. So that tells me it is reading it but it's not overriding the annotation specified for <strong>file</strong>. Even the default schema isn't being used.</p> <p>Isn't the orm.xml suppose to override the annotations? Shouldn't this be simple?</p>
1
1,407
Connecting Multiple Mongo DBs in a Node.js Project
<p>I am trying to connect multiple MongoDB databases into a single Node.js project. Here is my current structure and issue at hand.</p> <p>Node Version: <strong>v6.12.1</strong></p> <p>Express.js Version: <strong>4.16.2</strong></p> <p>Mongoose Version: <strong>4.13.6</strong></p> <p>Current Structure:</p> <p><strong>primaryDB.js</strong></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 mongoose = require('mongoose'); var configDB = require('./database.js'); //Connect to MongoDB via Mongoose mongoose.Promise = require('bluebird'); //mongoose.Promise = global.Promise; mongoose.connect(configDB.url, { useMongoClient: true }); //Check for successful DB connection var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log("Primary DB Successfully Connected.."); }); module.exports = mongoose;</code></pre> </div> </div> </p> <p><strong>secondaryDB.js</strong></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 mongoose = require('mongoose'); mongoose.connect('mongodb://mongodb_address_goes_here:27017/db_name', { useMongoClient: true }); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log("Secondary DB Successfully Connected.."); }); module.exports = mongoose;</code></pre> </div> </div> </p> <p>Then each DB connection gets imported respectively into their schema files, from which the schema files have module exports.</p> <p><strong>Issue at hand</strong></p> <p>When I run my application it starts fine and connects to both DB's successfully however I believe that mongoose is either getting overwritten or something because I might be able to do a <code>findOne()</code> command on primary but secondary fails or vice versa.</p> <p><strong>Example:</strong></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 async = require('async'); var primaryModel = require('../../../models/general/primary'); var SecondaryModel = require('../../../models/general/secondary'); function getInfo() { async.waterfall([ getPrimaryName, getSecondaryName ], function (err, info) { }); }; function getPrimaryName(callback){ Primary.findOne({}, function (err, primaryInfo){ if (err) { console.log("Error" + err); } console.log('Primary info is : ' + primaryInfo); callback(null,primaryInfo); }); } function getSecondaryName(primaryInfo, callback) { console.log(primaryInfo); //Make sure its being passed Secondary.findOne({}, function (err, secondaryInfo) { if (err) { console.log("Error" + err); } console.log('Secondary Info is : ' + secondaryInfo); callback(null, secondaryInfo); }); }</code></pre> </div> </div> </p> <p>The problem with above is I might get data back from the call to Primary but not Secondary. Which again I believe is from something being overridden .</p> <p>Any help appreciated. Sorry about the verbosity.</p>
1
1,158
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'spring_batch_tutorial.batch_job_execution_params' doesn't exist - Spring Batch
<p>I am working on Spring MVC+ Spring Batch example, I'm developing an application from link: <a href="https://github.com/krams915/spring-batch-tutorial" rel="nofollow">https://github.com/krams915/spring-batch-tutorial</a> and I was able to successfully deploy the application, but when I click via application I see following error comes. ## Heading ##I've uploaded my code at: <strong><a href="https://github.com/test512/spring-batch-krams-tutorial/tree/master/spring-batch-krams-tutorial" rel="nofollow">https://github.com/test512/spring-batch-krams-tutorial/tree/master/spring-batch-krams-tutorial</a></strong></p> <pre><code>com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'spring_batch_tutorial.batch_job_execution_params' doesn't exist at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:404) at com.mysql.jdbc.Util.getInstance(Util.java:387) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:942) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2549) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1962) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:1392) at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:692) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:684) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:716) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:741) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:751) at org.springframework.batch.core.repository.dao.JdbcJobExecutionDao.getJobParameters(JdbcJobExecutionDao.java:385) at org.springframework.batch.core.repository.dao.JdbcJobExecutionDao$JobExecutionRowMapper.mapRow(JdbcJobExecutionDao.java:415) at org.springframework.batch.core.repository.dao.JdbcJobExecutionDao$JobExecutionRowMapper.mapRow(JdbcJobExecutionDao.java:396) at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:93) at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60) at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:697) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:684) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:716) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:726) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:781) at org.springframework.batch.core.repository.dao.JdbcJobExecutionDao.findJobExecutions(JdbcJobExecutionDao.java:131) at org.springframework.batch.core.repository.support.SimpleJobRepository.getStepExecutionCount(SimpleJobRepository.java:253) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) at com.sun.proxy.$Proxy28.getStepExecutionCount(Unknown Source) at org.springframework.batch.core.job.flow.JobFlowExecutor.isStepRestart(JobFlowExecutor.java:82) at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:63) at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:67) at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:169) at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:144) at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:134) at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306) at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) at java.lang.Thread.run(Unknown Source) 2016-08-23 22:42:34.130 [SimpleAsyncTaskExecutor-1] DEBUG SqlUtils - Attempted to convert SQLException to SQLException. Leaving it alone. [SQLState: 42S02; errorCode: 1146] </code></pre> <p><strong>schema-mysql.sql</strong></p> <pre><code>-- Autogenerated: do not edit this file CREATE TABLE BATCH_JOB_INSTANCE ( JOB_INSTANCE_ID BIGINT NOT NULL PRIMARY KEY , VERSION BIGINT , JOB_NAME VARCHAR(100) NOT NULL, JOB_KEY VARCHAR(32) NOT NULL, constraint JOB_INST_UN unique (JOB_NAME, JOB_KEY) ) ENGINE=InnoDB; CREATE TABLE BATCH_JOB_EXECUTION ( JOB_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY , VERSION BIGINT , JOB_INSTANCE_ID BIGINT NOT NULL, CREATE_TIME DATETIME NOT NULL, START_TIME DATETIME DEFAULT NULL , END_TIME DATETIME DEFAULT NULL , STATUS VARCHAR(10) , EXIT_CODE VARCHAR(100) , EXIT_MESSAGE VARCHAR(2500) , LAST_UPDATED DATETIME, constraint JOB_INST_EXEC_FK foreign key (JOB_INSTANCE_ID) references BATCH_JOB_INSTANCE(JOB_INSTANCE_ID) ) ENGINE=InnoDB; CREATE TABLE BATCH_JOB_PARAMS ( JOB_INSTANCE_ID BIGINT NOT NULL , TYPE_CD VARCHAR(6) NOT NULL , KEY_NAME VARCHAR(100) NOT NULL , STRING_VAL VARCHAR(250) , DATE_VAL DATETIME DEFAULT NULL , LONG_VAL BIGINT , DOUBLE_VAL DOUBLE PRECISION , constraint JOB_INST_PARAMS_FK foreign key (JOB_INSTANCE_ID) references BATCH_JOB_INSTANCE(JOB_INSTANCE_ID) ) ENGINE=InnoDB; CREATE TABLE BATCH_STEP_EXECUTION ( STEP_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY , VERSION BIGINT NOT NULL, STEP_NAME VARCHAR(100) NOT NULL, JOB_EXECUTION_ID BIGINT NOT NULL, START_TIME DATETIME NOT NULL , END_TIME DATETIME DEFAULT NULL , STATUS VARCHAR(10) , COMMIT_COUNT BIGINT , READ_COUNT BIGINT , FILTER_COUNT BIGINT , WRITE_COUNT BIGINT , READ_SKIP_COUNT BIGINT , WRITE_SKIP_COUNT BIGINT , PROCESS_SKIP_COUNT BIGINT , ROLLBACK_COUNT BIGINT , EXIT_CODE VARCHAR(100) , EXIT_MESSAGE VARCHAR(2500) , LAST_UPDATED DATETIME, JOB_CONFIGURATION_LOCATION VARCHAR(100), constraint JOB_EXEC_STEP_FK foreign key (JOB_EXECUTION_ID) references BATCH_JOB_EXECUTION(JOB_EXECUTION_ID) ) ENGINE=InnoDB; CREATE TABLE BATCH_STEP_EXECUTION_CONTEXT ( STEP_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY, SHORT_CONTEXT VARCHAR(2500) NOT NULL, SERIALIZED_CONTEXT TEXT , constraint STEP_EXEC_CTX_FK foreign key (STEP_EXECUTION_ID) references BATCH_STEP_EXECUTION(STEP_EXECUTION_ID) ) ENGINE=InnoDB; CREATE TABLE BATCH_JOB_EXECUTION_CONTEXT ( JOB_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY, SHORT_CONTEXT VARCHAR(2500) NOT NULL, SERIALIZED_CONTEXT TEXT , constraint JOB_EXEC_CTX_FK foreign key (JOB_EXECUTION_ID) references BATCH_JOB_EXECUTION(JOB_EXECUTION_ID) ) ENGINE=InnoDB; CREATE TABLE BATCH_STEP_EXECUTION_SEQ (ID BIGINT NOT NULL) ENGINE=MYISAM; INSERT INTO BATCH_STEP_EXECUTION_SEQ values(0); CREATE TABLE BATCH_JOB_EXECUTION_SEQ (ID BIGINT NOT NULL) ENGINE=MYISAM; INSERT INTO BATCH_JOB_EXECUTION_SEQ values(0); CREATE TABLE BATCH_JOB_SEQ (ID BIGINT NOT NULL) ENGINE=MYISAM; INSERT INTO BATCH_JOB_SEQ values(0); ALTER TABLE `BATCH_JOB_EXECUTION` MODIFY COLUMN `EXIT_CODE` varchar(2500) DEFAULT NULL; ALTER TABLE `BATCH_JOB_EXECUTION` ADD COLUMN `JOB_CONFIGURATION_LOCATION` varchar(2500) DEFAULT NULL; ALTER TABLE `BATCH_JOB_EXECUTION_SEQ` ADD COLUMN `UNIQUE_KEY` char(1) NOT NULL; ALTER TABLE `BATCH_JOB_EXECUTION_SEQ` ADD UNIQUE KEY `UNIQUE_KEY_UN` (`UNIQUE_KEY`); ALTER TABLE `BATCH_JOB_SEQ` ADD COLUMN `UNIQUE_KEY` char(1) NOT NULL; ALTER TABLE `BATCH_JOB_SEQ` ADD UNIQUE KEY `UNIQUE_KEY_UN` (`UNIQUE_KEY`); ALTER TABLE `BATCH_STEP_EXECUTION` MODIFY COLUMN `EXIT_CODE` varchar(2500) DEFAULT NULL; ALTER TABLE `BATCH_STEP_EXECUTION_SEQ` ADD COLUMN `UNIQUE_KEY` char(1) NOT NULL; ALTER TABLE `BATCH_STEP_EXECUTION_SEQ` ADD UNIQUE KEY `UNIQUE_KEY_UN` (`UNIQUE_KEY`); </code></pre> <p><strong>pom.xml</strong></p> <pre><code>&lt;properties&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;springframework.version&gt;4.3.0.RELEASE&lt;/springframework.version&gt; &lt;springbatch.version&gt;3.0.6.RELEASE&lt;/springbatch.version&gt; &lt;hibernate.version&gt;4.3.6.Final&lt;/hibernate.version&gt; &lt;aspectj.version&gt;1.8.9&lt;/aspectj.version&gt; &lt;cglib.version&gt;3.2.4&lt;/cglib.version&gt; &lt;jackson.version&gt;1.9.13&lt;/jackson.version&gt; &lt;spring.data.jpa.version&gt;1.10.2.RELEASE&lt;/spring.data.jpa.version&gt; &lt;hibernate.entitymanager.version&gt;5.1.0.Final&lt;/hibernate.entitymanager.version&gt; &lt;javassist.version&gt;3.18.1-GA&lt;/javassist.version&gt; &lt;mysql.version&gt;5.1.39&lt;/mysql.version&gt; &lt;joda-time.version&gt;2.3&lt;/joda-time.version&gt; &lt;c3p0.version&gt;0.9.5-pre8&lt;/c3p0.version&gt; &lt;querydsl.version&gt;3.7.4&lt;/querydsl.version&gt; &lt;javax.servlet.version&gt;3.1.0&lt;/javax.servlet.version&gt; &lt;mockito.version&gt;1.10.19&lt;/mockito.version&gt; &lt;logback.version&gt;1.1.7&lt;/logback.version&gt; &lt;jcl-over-slf4j.version&gt;1.7.21&lt;/jcl-over-slf4j.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;!-- Spring Web and Web MVC --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-web&lt;/artifactId&gt; &lt;version&gt;${springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt;version&gt;${springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Spring TX --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-tx&lt;/artifactId&gt; &lt;version&gt;${springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Spring OXM --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-oxm&lt;/artifactId&gt; &lt;version&gt;${springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Spring Aspect --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-aspects&lt;/artifactId&gt; &lt;version&gt;${springframework.version}&lt;/version&gt; &lt;type&gt;jar&lt;/type&gt; &lt;scope&gt;compile&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- Spring JDBC --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt; &lt;version&gt;${springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Spring Data JPA --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.data&lt;/groupId&gt; &lt;artifactId&gt;spring-data-jpa&lt;/artifactId&gt; &lt;version&gt;${spring.data.jpa.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Hibernate and JPA --&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate.java-persistence&lt;/groupId&gt; &lt;artifactId&gt;jpa-api&lt;/artifactId&gt; &lt;version&gt;2.0-cr-1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt; &lt;version&gt;${hibernate.entitymanager.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Spring Batch --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.batch&lt;/groupId&gt; &lt;artifactId&gt;spring-batch-core&lt;/artifactId&gt; &lt;version&gt;${springbatch.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- QueryDSL --&gt; &lt;dependency&gt; &lt;groupId&gt;com.mysema.querydsl&lt;/groupId&gt; &lt;artifactId&gt;querydsl-core&lt;/artifactId&gt; &lt;version&gt;${querydsl.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.mysema.querydsl&lt;/groupId&gt; &lt;artifactId&gt;querydsl-jpa&lt;/artifactId&gt; &lt;version&gt;${querydsl.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.mysema.querydsl&lt;/groupId&gt; &lt;artifactId&gt;querydsl-apt&lt;/artifactId&gt; &lt;version&gt;${querydsl.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- MySQL --&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;${mysql.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- ComboPooledDataSource --&gt; &lt;dependency&gt; &lt;groupId&gt;com.mchange&lt;/groupId&gt; &lt;artifactId&gt;c3p0&lt;/artifactId&gt; &lt;version&gt;${c3p0.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- A seamless aspect-oriented extension to the Java programming language --&gt; &lt;dependency&gt; &lt;groupId&gt;org.aspectj&lt;/groupId&gt; &lt;artifactId&gt;aspectjrt&lt;/artifactId&gt; &lt;version&gt;${aspectj.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.aspectj&lt;/groupId&gt; &lt;artifactId&gt;aspectjweaver&lt;/artifactId&gt; &lt;version&gt;${aspectj.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;cglib&lt;/groupId&gt; &lt;artifactId&gt;cglib-nodep&lt;/artifactId&gt; &lt;version&gt;${cglib.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt; &lt;artifactId&gt;jackson-mapper-asl&lt;/artifactId&gt; &lt;version&gt;${jackson.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Jackson is a high-performance JSON processor (parser, generator) --&gt; &lt;dependency&gt; &lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt; &lt;artifactId&gt;jackson-core-asl&lt;/artifactId&gt; &lt;version&gt;${jackson.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt; &lt;version&gt;2.8.1&lt;/version&gt; &lt;/dependency&gt; &lt;!-- logging, slf4j --&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;jcl-over-slf4j&lt;/artifactId&gt; &lt;version&gt;${jcl-over-slf4j.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt; &lt;artifactId&gt;logback-classic&lt;/artifactId&gt; &lt;version&gt;${logback.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Servlet, JSP API, JSTL, Standard --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt; &lt;version&gt;3.1.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet.jsp&lt;/groupId&gt; &lt;artifactId&gt;jsp-api&lt;/artifactId&gt; &lt;version&gt;2.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;jstl&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;taglibs&lt;/groupId&gt; &lt;artifactId&gt;standard&lt;/artifactId&gt; &lt;version&gt;1.1.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Testing Framework mockito all, Junit, Spring Test --&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.12&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.mockito&lt;/groupId&gt; &lt;artifactId&gt;mockito-all&lt;/artifactId&gt; &lt;version&gt;${mockito.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-test&lt;/artifactId&gt; &lt;version&gt;${springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>Other codes file using as it is. Please help.</p> <p><strong>applicationContext.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"&gt; &lt;context:property-placeholder properties-ref="deployProperties" /&gt; &lt;!-- Activates various annotations to be detected in bean classes --&gt; &lt;context:annotation-config /&gt; &lt;!-- Scans the classpath for annotated components that will be auto-registered as Spring beans. For example @Controller and @Service. Make sure to set the correct base-package --&gt; &lt;context:component-scan base-package="org.krams" /&gt; &lt;!-- Configures the annotation-driven Spring MVC Controller programming model. Note that, with Spring 3.0, this tag works in Servlet MVC only! --&gt; &lt;mvc:annotation-driven /&gt; &lt;mvc:resources mapping="/resources/**" location="/resources/" /&gt; &lt;!-- Import extra configuration --&gt; &lt;import resource="trace-context.xml"/&gt; &lt;import resource="spring-data.xml"/&gt; &lt;import resource="spring-batch.xml"/&gt; &lt;import resource="spring-batch-job1.xml"/&gt; &lt;import resource="spring-batch-job2.xml"/&gt; &lt;import resource="spring-batch-job3.xml"/&gt; &lt;bean id="deployProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean" p:location="/WEB-INF/spring.properties" /&gt; &lt;/beans&gt; </code></pre> <p><strong>spring-batch.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:batch="http://www.springframework.org/schema/batch" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd"&gt; &lt;context:property-placeholder properties-ref="deployProperties" /&gt; &lt;bean id="userWriter" class="org.krams.batch.UserItemWriter"/&gt; &lt;bean id="roleWriter" class="org.krams.batch.RoleItemWriter"/&gt; &lt;bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher" p:jobRepository-ref="jobRepository" p:taskExecutor-ref="taskExecutor"/&gt; &lt;!-- 4.3. Configuring a JobLauncher asynchronously --&gt; &lt;bean id="taskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor" /&gt; &lt;!-- http://forum.springsource.org/showthread.php?59779-Spring-Batch-1-1-2-Standard-JPA-does-not-support-custom-isolation-levels-use-a-sp --&gt; &lt;!-- &lt;job-repository id="jobRepository" xmlns="http://www.springframework.org/schema/batch" data-source="jpaDataSource" isolation-level-for-create="SERIALIZABLE" transaction-manager="transactionManager" table-prefix="BATCH_" max-varchar-length="100" /&gt; --&gt; &lt;bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean"&gt; &lt;property name="dataSource" ref="jpaDataSource" /&gt; &lt;property name="transactionManager" ref="transactionManager"/&gt; &lt;property name="databaseType" value="MYSQL" /&gt; &lt;property name="tablePrefix" value="BATCH_"/&gt; &lt;property name="isolationLevelForCreate" value="ISOLATION_DEFAULT"/&gt; &lt;/bean&gt; &lt;!-- &lt;bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="jpaDataSource" /&gt; --&gt; &lt;bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" &gt; &lt;property name="dataSource" ref="jpaDataSource" /&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <p><strong>spring-data.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"&gt; &lt;context:property-placeholder properties-ref="deployProperties" /&gt; &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt; &lt;!-- Activate Spring Data JPA repository support --&gt; &lt;jpa:repositories base-package="org.krams.repository" /&gt; &lt;!-- Declare a datasource that has pooling capabilities--&gt; &lt;bean id="jpaDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" &gt; &lt;property name="driverClass" value="${app.jdbc.driverClassName}" /&gt; &lt;property name="jdbcUrl" value="${app.jdbc.url}" /&gt; &lt;property name="user" value="${app.jdbc.username}" /&gt; &lt;property name="password" value="${app.jdbc.password}" /&gt; &lt;property name="acquireIncrement" value="5" /&gt; &lt;property name="idleConnectionTestPeriod" value="60" /&gt; &lt;property name="maxPoolSize" value="100" /&gt; &lt;property name="maxStatements" value="50" /&gt; &lt;property name="minPoolSize" value="10" /&gt; &lt;/bean&gt; &lt;!-- Declare a JPA entityManagerFactory --&gt; &lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" &gt; &lt;property name="dataSource" ref="jpaDataSource" /&gt; &lt;property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" /&gt; &lt;property name="persistenceUnitName" value="hibernatePersistenceUnit" /&gt; &lt;property name="jpaVendorAdapter" ref="hibernateVendor" /&gt; &lt;!-- &lt;property name="jpaProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.hbm2ddl.auto"&gt;create&lt;/prop&gt; &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; --&gt; &lt;property name="jpaDialect" ref="jpaDialect" /&gt; &lt;/bean&gt; &lt;!-- Specify our ORM vendor --&gt; &lt;bean id="hibernateVendor" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" &gt; &lt;property name="showSql" value="false" /&gt; &lt;!-- &lt;property name="database" value="MYSQL" /&gt; --&gt; &lt;/bean&gt; &lt;bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" /&gt; &lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt; &lt;property name="entityManagerFactory" ref="entityManagerFactory" /&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <p><strong>spring-batch-job1.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:batch="http://www.springframework.org/schema/batch" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd"&gt; &lt;context:property-placeholder properties-ref="deployProperties" /&gt; &lt;job id="batchJob1" xmlns="http://www.springframework.org/schema/batch"&gt; &lt;step id="userload1" next="roleLoad1"&gt; &lt;tasklet&gt; &lt;chunk reader="userFileItemReader1" writer="userWriter" commit-interval="${job.commit.interval}" /&gt; &lt;/tasklet&gt; &lt;/step&gt; &lt;step id="roleLoad1"&gt; &lt;tasklet&gt; &lt;chunk reader="roleFileItemReader1" writer="roleWriter" commit-interval="${job.commit.interval}" /&gt; &lt;/tasklet&gt; &lt;/step&gt; &lt;/job&gt; &lt;bean id="userFileItemReader1" class="org.springframework.batch.item.file.FlatFileItemReader"&gt; &lt;property name="resource" value="classpath:${user1.file.name}" /&gt; &lt;property name="lineMapper"&gt; &lt;bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper"&gt; &lt;property name="lineTokenizer"&gt; &lt;bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer"&gt; &lt;property name="names" value="username,firstName,lastName,password" /&gt; &lt;/bean&gt; &lt;/property&gt; &lt;property name="fieldSetMapper"&gt; &lt;bean class="org.krams.batch.UserFieldSetMapper" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="roleFileItemReader1" class="org.springframework.batch.item.file.FlatFileItemReader"&gt; &lt;property name="resource" value="classpath:${role1.file.name}" /&gt; &lt;property name="lineMapper"&gt; &lt;bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper"&gt; &lt;property name="lineTokenizer"&gt; &lt;bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer"&gt; &lt;property name="names" value="username,role" /&gt; &lt;/bean&gt; &lt;/property&gt; &lt;property name="fieldSetMapper"&gt; &lt;bean class="org.krams.batch.RoleFieldSetMapper" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre>
1
14,952
Sending email with attachment using Maven
<p>Using surefire plugin and postman plugin, I am able to generate a surefire report and send email to a recipient. But the surefire report (html) is not getting attached with the email. Recipient is getting an email without the attachment. If I run the project again, email has been delivered with the attachment. Following is my pom.xml. I don't know what I am missing. Please help.</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/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.testing.example&lt;/groupId&gt; &lt;artifactId&gt;SampleExample&lt;/artifactId&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;name&gt;SampleExample&lt;/name&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.11&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;sourceDirectory&gt;src&lt;/sourceDirectory&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.1&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.8&lt;/source&gt; &lt;target&gt;1.8&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;ch.fortysix&lt;/groupId&gt; &lt;artifactId&gt;maven-postman-plugin&lt;/artifactId&gt; &lt;version&gt;0.1.6&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;send_an_mail&lt;/id&gt; &lt;phase&gt;test&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;send-mail&lt;/goal&gt; &lt;/goals&gt; &lt;inherited&gt;false&lt;/inherited&gt; &lt;configuration&gt; &lt;from&gt;xxxxxxxxxx&lt;/from&gt; &lt;subject&gt;this is a test auto email sent from Eclipse using Maven&lt;/subject&gt; &lt;htmlMessage&gt; &lt;![CDATA[ &lt;p&gt;Hi, Please find attached.&lt;/p&gt; ]]&gt; &lt;/htmlMessage&gt; &lt;failonerror&gt;true&lt;/failonerror&gt; &lt;mailhost&gt;smtp.gmail.com&lt;/mailhost&gt; &lt;mailport&gt;465&lt;/mailport&gt; &lt;mailssl&gt;true&lt;/mailssl&gt; &lt;mailAltConfig&gt;true&lt;/mailAltConfig&gt; &lt;mailuser&gt;xxxxxxx&lt;/mailuser&gt; &lt;mailpassword&gt;xxxxxxx&lt;/mailpassword&gt; &lt;receivers&gt; &lt;receiver&gt;xxxxxxxxx&lt;/receiver&gt; &lt;/receivers&gt; &lt;fileSets&gt; &lt;fileSet&gt; &lt;directory&gt;${basedir}/target/site&lt;/directory&gt; &lt;includes&gt; &lt;include&gt;**/surefire-report.html&lt;/include&gt; &lt;/includes&gt; &lt;/fileSet&gt; &lt;/fileSets&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;reporting&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-report-plugin&lt;/artifactId&gt; &lt;version&gt;2.18.1&lt;/version&gt; &lt;configuration&gt; &lt;testFailureIgnore&gt;true&lt;/testFailureIgnore&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/reporting&gt; &lt;/project&gt; </code></pre>
1
2,918
Node/Express: concurrency issues when using session to store state
<p>So, I've searched quite a bit for this and found several somewhat similar questions, none of them really addressing the problem though so I thought this deserved a question of its own.</p> <p>I have an express application with a bunch of routes that modify the session to keep state. Thing is, if there are multiple parallel requests, from time to time the session will be overwritten due to race conditions between requests.</p> <p>So typically</p> <pre><code>... app.use(express.static('/public')); app.use(session(...)); app.route('methodA').get(function(req, res, next) { doSomethingSlow().then(function() { req.session.a = 'foo'; res.send(...); } }); app.route('methodB').get(function(req, res, next) { doSomethingElseSlow().then(function() { req.session.b = 'bar'; res.send(...); } }); </code></pre> <p>Basically the problem is straightforward and is e.g. described in <a href="https://stackoverflow.com/a/8523574">this</a> answer. Express stores the session in res.end(), but while a methodA request is being handled, a methodB request could have modified the session in the meantime so that when methodA stores the session it will overwrite any changes made by methodB. So even though node is single-threaded and all requests are served by the same thread we can end up with concurrency issues as soon as any method is doing something asynchronous thereby letting other requests be handled simultaneously.</p> <p>However, I am struggling to decide how I should proceed to solve this problem. All answers I have found only list ways of <em>minimizing the probability</em> of this happening, e.g. by making sure static content does not store the session by registering the serve-static MW before the session MW. But this only helps to some extent; if there are in fact API methods that are supposed to be called in parallel some real concurrency approach to session updates is needed (IMO, when it comes to concurrency issues, every "solution" that strives to minimize the probability of problems occuring rather than addressing the actual problem is bound to go wrong).</p> <p>Basically these are the alternatives I am exploring so far:</p> <ol> <li><p><strong>Prevent parallel requests within the same session completely by modifying my client to make sure it calls all API methods serially.</strong></p> <p>This may be possible but will have quite some impact on my architecture and may impact performance. It also avoids the problem rather than solves it and if I make something wrong in my client or the API is used by another client I might still run into this randomly, so it doesn't feel very robust.</p></li> <li><p><strong>Make sure each session write is preceded by a session reload and make the entire reload-modify-write operation atomic.</strong></p> <p>I am not sure how to achieve this. Even if I modify res.end() to reload the session <em>just</em> before modifying and storing it, because reading and writing the session is async I/O it seems possible that this could happen:</p> <ul> <li>request A reloads the session</li> <li>request A modifies session.A = 'foo'</li> <li>request B reloads the session (and will not see session.A)</li> <li>request A stores the session</li> <li>request B modifies session.B = 'bar'</li> <li>request B stores the session, overwriting previous store so that session.A is missing</li> </ul></li> </ol> <p>So in essence I would need to make each reload-modify-store atomic, which basically means blocking the thread? Feels wrong, and I have no idea how to do it.</p> <ol start="3"> <li><p><strong>Stop using the session in this way altogether and pass necessary state as params to each request or by some other means.</strong></p> <p>This also avoids the problem rather than addressing it. It would also have huge impact on my project. But sure, it might be the best way.</p></li> <li><p><strong>???</strong></p></li> </ol> <p>Anyone got any ideas how to address this in a robust way? Thanks!</p>
1
1,095
Google Tag Manager Multiple Enhanced eCommerce Events
<p>I'm new to GTM and I'm having trouble trying to submit 2 enhanced ecommerce events in the dataLayer. Only the last event seems to be getting sent when I check on Google Analytics.</p> <p>I've come across <a href="http://www.simoahava.com/analytics/ecommerce-tips-google-tag-manager/" rel="nofollow">http://www.simoahava.com/analytics/ecommerce-tips-google-tag-manager/</a> which, just before the summary, seems to sum up what I've said regarding it only submitting the last one.</p> <pre><code> dataLayer.push({ 'event': 'addToCart', 'ecommerce': { 'currencyCode': 'GBP', 'add': { 'products': dataLayerProducts } } }); dataLayer.push({ 'event': 'checkout', 'ecommerce': { 'checkout': { 'actionField': {'step': 1}, 'products': dataLayerProducts } } }); </code></pre> <p>Only the checkout will be registered with Analytics. I've tried things like the following:</p> <pre><code> dataLayer = [{ 'event': 'checkout', 'event': 'addToCart', 'ecommerce': { 'add': { 'products': dataLayerProducts }, 'checkout': { 'actionField': {'step': 1}, 'products': dataLayerProducts } } }]; </code></pre> <p>and</p> <pre><code> dataLayer = [{ 'event': 'addToCart', 'ecommerce': { 'add': { 'products': dataLayerProducts }, } }, { 'event': 'checkout', 'ecommerce': { 'checkout': { 'actionField': {'step': 1}, 'products': dataLayerProducts } } }]; </code></pre> <p>But I've had no luck doing it like that either. If it just isn't possible, any helpful workarounds would be much appreciated.</p> <p><strong>UPDATE WITH NEW CODE:</strong> Still only sending the last event (checkout). Code appears immediately after the opening <code>&lt;body&gt;</code> tag.</p> <pre><code>&lt;script&gt; dataLayer = []; dataLayerProducts = []; dataLayerProducts.push({ 'name': 'Product Name', 'id': 'SKU', 'price': '29.95', 'brand': 'Brand', 'category': 'Some/Category', 'quantity': 1 }); dataLayer.push({ 'event': 'addToCart', 'ecommerce': { 'add': { 'products': dataLayerProducts }, } }); dataLayer.push({ 'event': 'checkout', 'ecommerce': { 'checkout': { 'actionField': {'step': 1}, 'products': dataLayerProducts } } }); &lt;/script&gt; &lt;!-- Google Tag Manager --&gt; // Code &lt;!-- End Google Tag Manager --&gt; </code></pre>
1
1,298
How to load files according to Created Date in Windows command shell via SQL Server's xp_cmdshell
<p>In SQL Server, I am using a query below to load all ".jpg" file names from a specific directory (e.g. z:) into a table. </p> <p>I want to know if there's a way to load files according to <strong>Created Date</strong> instead of <strong>Modified Date</strong> in Windows command prompt. The query below only works with <strong>Modified Date</strong> when executing <code>xp_cmdshell</code>.</p> <pre><code>-- Create the table to store file list CREATE TABLE myFilesTable (myFileID INT IDENTITY, myFileName NVARCHAR(256)) -- Insert file list from directory to SQL Server DECLARE @Command varchar(1024) = 'z: &amp; forfiles /m *.jpg /s /d 07/16/2015 /c "cmd /c echo @fdate @ftime @path"' INSERT INTO myFilesTable EXEC MASTER.dbo.xp_cmdshell @Command -- Check the list SELECT * FROM myFilesTable GO </code></pre> <p><code>07/16/2015</code> in the variable <code>@Command</code> is the <strong>Modified Date</strong>. Obviously the command <code>forfiles</code> doesn't have a clue to filter files by <strong>Created Date</strong>.</p> <p>Below is a few results from the query given above in which FileNames are prefixed by <strong>Modified Date</strong>.</p> <pre><code>myFileID | myFileName ---------------------- 1 | NULL 2 | 8/18/2015 11:13:08 AM "Z:\LDB1 App Export\Top Star_Aluminium Frames &amp; Furniture (B)-31267.jpg" 3 | 8/19/2015 5:44:41 PM "Z:\LDB2 App Export\Soe Tint_Hardware Merchants &amp; Ironmongers-31435.jpg" 4 | 8/19/2015 10:37:13 AM "Z:\Cover App Export\Taw Win Tun_Electrical Goods Sales &amp; Repairing (A) -31382.jpg" 5 | 8/24/2015 10:34:33 AM "Z:\CP1 App Export\Thiri May_Fabric Shop (B)-30646.jpg" 6 | 8/17/2015 10:08:39 AM "Z:\CP2 App Export\Ko Tin Aung_Building Materials (B)-31300.jpg" </code></pre> <p>I have also tried using <code>dir</code> command with timefield <code>/t:c</code> (the creation time) something like </p> <pre><code>EXEC MASTER.dbo.xp_cmdshell 'dir z: *.jpg /t:c /s' </code></pre> <p>It gives me the <strong>Created Date</strong> but it shows me the following result which is not as expected. I want the file names with full path/directory names as shown in the previous result.</p> <pre><code>myFileID | myFileName ---------------------- 1 | Volume in drive Z is Publication 2 | Volume Serial Number is 3EF0-5CE4 3 | NULL 4 | Directory of Z:\ 5 | NULL 6 | 07/28/2015 06:41 PM &lt;DIR&gt; . 7 | 07/28/2015 07:06 PM &lt;DIR&gt; .. 8 | 03/05/2015 11:42 AM &lt;DIR&gt; LDB1 App Export 9 | 03/05/2015 05:31 PM &lt;DIR&gt; LDB2 App Export 10 | 0 File(s) 0 bytes 11 | NULL 12 | Directory of Z:\LDB1 App Export 13 | NULL 14 | 03/05/2015 11:42 AM &lt;DIR&gt; . 15 | 07/28/2015 06:41 PM &lt;DIR&gt; .. 16 | 07/28/2015 06:49 PM 2,981,526 Kyaw Phay_Dental Equipment (A)-30998.jpg 17 | 08/31/2015 03:10 PM 3,126,629 Venus_Fashion Shops-31438.jpg 18 | 07/28/2015 06:49 PM 3,544,247 Marvellous_Tourism Services-30986.jpg ... | ... </code></pre> <p>The expected result should be something like below,</p> <pre><code>myFileID | CreatedDate | myFileName ---------------------------------------------- 1 | 8/10/2015 11:24:16 AM | "Z:\LDB1 App Export\Top Star_Aluminium Frames &amp; Furniture (B)-31267.jpg" 2 | 8/10/2015 11:24:27 AM | "Z:\LDB2 App Export\Soe Tint_Hardware Merchants &amp; Ironmongers-31435.jpg" 3 | 8/12/2015 10:05:22 AM | "Z:\Cover App Export\Taw Win Tun_Electrical Goods Sales &amp; Repairing (A) -31382.jpg" 4 | 8/12/2015 10:05:22 AM | "Z:\CP1 App Export\Thiri May_Fabric Shop (B)-30646.jpg" 5 | 8/12/2015 10:05:22 AM | "Z:\CP2 App Export\Ko Tin Aung_Building Materials (B)-31300.jpg" </code></pre> <p>Any help would be very appreciated :)</p>
1
1,657
why JSON.stringify() and JSON.parse does not work?
<p>I have this javascript result:</p> <pre><code>var layer = '{&quot;type&quot;:&quot;polygon&quot;, &quot;coordinates&quot;: &quot;-34.32982832836202 149.88922119140625, -34.80027235055681 149.80682373046875, -34.74161249883173 150.30120849609375, -33.99802726234876 150.77362060546875, -33.97980872872456 150.27923583984375&quot;}'; </code></pre> <p>I checked it against JSONlint.com and was told it is a valid JSON string.</p> <p>why can't <code>JSON.parse()</code> and <code>JSON.stringify()</code> not work.</p> <p>I'm being told by the console that <code>JSON.parse()</code> and <code>JSON.stringify</code> are not recognized functions.</p> <p>Thanks.</p> <h1>UPDATE 1</h1> <p>ok. let me try this again. Sorry, was given bad info.</p> <pre><code>var polygon = new Array(); polygon.push('{&quot;type&quot;:&quot;polygon&quot;, &quot;coordinates&quot;: &quot;-34.32982832836202 149.88922119140625, -34.80027235055681 149.80682373046875, -34.74161249883173 150.30120849609375, -33.99802726234876 150.77362060546875, -33.97980872872456 150.27923583984375&quot;}'); var layer = polygon[0] //should be of value of string just stored console.log(layer); //correctly displays JSON string console.log(JSON.parse(layer)); //line that errors. </code></pre> <p>this is a portion of the full code below:</p> <pre><code>// This example requires the Drawing library. Include the libraries=drawing // parameter when you first load the API. For example: // &lt;script src=&quot;https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&amp;libraries=drawing&quot;&gt; var selectedShape; var drawingManager; var names = []; var polygons = new Array(); function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: { lat: -34.397, lng: 150.644 }, zoom: 8 }); drawingManager = new google.maps.drawing.DrawingManager({ drawingMode: google.maps.drawing.OverlayType.POLYGON, drawingControl: true, drawingControlOptions: { position: google.maps.ControlPosition.TOP_CENTER, drawingModes: ['circle', 'polygon', 'rectangle'] }, polygonOptions: { editable: true, draggable: true }, circleOptions: { editable: true, draggable: true }, rectangleOptions: { editable: true, draggable: true } }); drawingManager.setMap(map); //load preset data function setJSON(Shape) { console.log(Shape.type); if (Shape.type === &quot;circle&quot;) { return '{&quot;type&quot;:&quot;'+Shape.type +'&quot;, &quot;lat&quot;:&quot;'+Shape.getCenter().lat()+'&quot;, &quot;lng&quot;:&quot;'+Shape.getCenter().lng()+'&quot;, &quot;radius&quot;:&quot;'+Shape.getRadius()+'&quot; }'; } if (Shape.type === &quot;rectangle&quot;){ return '{&quot;type&quot;:&quot;' + Shape.type + ', &quot;start&quot;:&quot;'+ Shape.getBounds().getNorthEast() +'&quot;, &quot;end&quot;:&quot;'+ Shape.getBounds().getSouthWest() +'&quot;}'; } if (Shape.type === &quot;polygon&quot;){ //eturn '{&quot;type&quot;:&quot;'+ Shape.type +'&quot;}' + Shape.getPaths(); vertice = Shape.getPath(); console.log(&quot;vertice count: &quot; + vertice.getLength()); JSON = '{&quot;type&quot;:&quot;'+ Shape.type +'&quot;, &quot;coordinates&quot;: &quot;'; vertice.forEach(function(xy, i) { JSON = JSON + xy.lat() + ' ' + xy.lng() + ', '; }); JSON = JSON.slice(0,-2) + '&quot;}'; return JSON; } return 0 } google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) { drawingManager.setMap(null); var newShape = event.overlay; newShape.type = event.type; selectedShape = newShape; console.log(setJSON(selectedShape)); if (newShape.type === &quot;circle&quot; || newShape.type === &quot;rectangle&quot;) { google.maps.event.addListener(selectedShape, 'bounds_changed', function(event){ console.log(setJSON(selectedShape)); }); } if (newShape.type === &quot;polygon&quot;) { google.maps.event.addListener(selectedShape.getPath(), 'set_at', function(event) { // complete functions console.log(setJSON(selectedShape)); }); google.maps.event.addListener(selectedShape.getPath(), 'insert_at', function(event) { // complete functions console.log(setJSON(selectedShape)); }); google.maps.event.addListener(selectedShape, 'rightclick', function(event) { // Check if click was on a vertex control point if (event.vertex === undefined) { return; } deleteMenu.open(map, selectedShape.getPath(), event.vertex); console.log('right-click'); }) } function DeleteMenu() { this.div_ = document.createElement('div'); this.div_.className = 'delete-menu'; this.div_.innerHTML = 'Delete'; var menu = this; google.maps.event.addDomListener(this.div_, 'click', function() { menu.removeVertex(); }); } DeleteMenu.prototype = new google.maps.OverlayView(); DeleteMenu.prototype.onAdd = function() { var deleteMenu = this; var map = this.getMap(); this.getPanes().floatPane.appendChild(this.div_); // mousedown anywhere on the map except on the menu div will close the // menu. this.divListener_ = google.maps.event.addDomListener(map.getDiv(), 'mousedown', function(e) { if (e.target != deleteMenu.div_) { deleteMenu.close(); } }, true); }; DeleteMenu.prototype.onRemove = function() { google.maps.event.removeListener(this.divListener_); this.div_.parentNode.removeChild(this.div_); // clean up this.set('position'); this.set('path'); this.set('vertex'); }; DeleteMenu.prototype.close = function() { this.setMap(null); }; DeleteMenu.prototype.draw = function() { var position = this.get('position'); var projection = this.getProjection(); if (!position || !projection) { return; } var point = projection.fromLatLngToDivPixel(position); this.div_.style.top = point.y + 'px'; this.div_.style.left = point.x + 'px'; }; DeleteMenu.prototype.open = function(map, path, vertex) { this.set('position', path.getAt(vertex)); this.set('path', path); this.set('vertex', vertex); this.setMap(map); this.draw(); }; DeleteMenu.prototype.removeVertex = function() { var path = this.get('path'); var vertex = this.get('vertex'); if (!path || vertex == undefined) { this.close(); return; } path.removeAt(vertex); this.close(); }; var deleteMenu = new DeleteMenu(); }); google.maps.event.addDomListener(document.getElementById('btnClear'), 'click', function(event) { selectedShape.setMap(null); drawingManager.setMap(map); }); google.maps.event.addDomListener(document.getElementById('save'), 'click', function(event) { names.push($('#polyname').val()); polygons.push(setJSON(selectedShape)); length = names.length; console.log(length); console.log(&quot;name: &quot; + names[length-1] + &quot;; polygon: &quot; + polygons[length-1]); }); google.maps.event.addDomListener(document.getElementById('btnrecall'), 'click', function(event) { $('#btnClear').click(); console.log($('#btnLoad').val()); var namefield = $('#btnLoad').val(); if (namefield !== undefined){ var polyid = names.indexOf(namefield); if (polyid &gt; -1) { var layer = polygons[polyid]; console.log(layer); console.log(JSON.parse(JSON.stringify(layer))); }else { alert(&quot;no polygon by that name. Please Try again&quot;); } }else { alert(&quot;please enter a name to continue.&quot;); } }); } </code></pre>
1
4,182
Does C++11 support types recursion in templates?
<p>I want to explain the question in detail. In many languages with strong type systems (like Felix, Ocaml, Haskell) you can define a polymorphic list by composing type constructors. Here's the Felix definition:</p> <pre><code>typedef list[T] = 1 + T * list[T]; typedef list[T] = (1 + T * self) as self; </code></pre> <p>In Ocaml:</p> <pre class="lang-ml prettyprint-override"><code>type 'a list = Empty | Cons ('a, 'a list) </code></pre> <p>In C, this is recursive but neither polymorphic nor compositional:</p> <pre><code>struct int_list { int elt; struct int_list *next; }; </code></pre> <p>In C++ it would be done like this, if C++ supported type recursion:</p> <pre><code>struct unit {}; template&lt;typename T&gt; using list&lt;T&gt; = variant&lt; unit, tuple&lt;T, list&lt;T&gt;&gt; &gt;; </code></pre> <p>given a suitable definition for tuple (aka pair) and variant (but not the broken one used in Boost). Alternatively:</p> <pre><code> using list&lt;T&gt; = variant&lt; unit, tuple&lt;T, &amp;list&lt;T&gt;&gt; &gt;; </code></pre> <p>might be acceptable given a slightly different definition of variant. It was not possible to even write this in C++ &lt; C++11 because without template typedefs, there's no way to get polymorphism, and without a sane syntax for typedefs, there's no way to get the target type in scope. The using syntax above solves both these problems, however this does not imply recursion is permitted.</p> <p>In particular please note that allowing recursion has a major impact on the ABI, i.e. on name mangling (it can't be done unless the name mangling scheme allows for representation of fixpoints).</p> <p>My question: is required to work in C++11? [Assuming the expansion doesn't result in an infinitely large struct]</p> <hr> <p>Edit: just to be clear, the requirement is for general structural typing. Templates provide precisely that, for example</p> <pre><code>pair&lt;int, double&gt; pair&lt;int, pair &lt;long, double&gt; &gt; </code></pre> <p>are anonymously (structurally) typed, and pair is clearly polymorphic. However recursion in C++ &lt; C++11 cannot be stated, not even with a pointer. In C++11 you can state the recursion, albeit with a template typedef (with the new using syntax the expression on the LHS of the = sign is in scope on the RHS).</p> <p>Structural (anonymous) typing with polymorphism and recursion are minimal requirements for a type system. </p> <p>Any modern type system must support polynomial type functors or the type system is too clumbsy to do any kind of high level programming. The combinators required for this are usually stated by type theoreticians like:</p> <pre><code>1 | * | + | fix </code></pre> <p>where 1 is the unit type, * is tuple formation, + is variant formation, and fix is recursion. The idea is simply that:</p> <p>if t is a type and u is a type then t + u and t * u are also types</p> <p>In C++, struct unit{} is 1, tuple is *, variant is + and fixpoints might be obtained with the using = syntax. It's not quite anonymous typing because the fixpoint would require a template typedef.</p> <hr> <p>Edit: Just an example of polymorphic type constructor in C:</p> <pre><code>T* // pointer formation T (*)(U) // one argument function type T[2] // array </code></pre> <p>Unfortunately in C, function values aren't compositional, and pointer formation is subject to lvalue constraint, and the syntactic rules for type composition are not themselves compositional, but here we can say:</p> <pre><code>if T is a type T* is a type if T and U are types, T (*)(U) is a type if T is a type T[2] is a type </code></pre> <p>so these type constuctors (combinators) can be applied recursively to get new types without having to create a new intermediate type. In C++ we can easily fix the syntactic problem:</p> <pre><code>template&lt;typename T&gt; using ptr&lt;T&gt; = T*; template&lt;typename T, typename U&gt; using fun&lt;T,U&gt; = T (*)(U); template&lt;typename T&gt; using arr2&lt;T&gt; = T[2]; </code></pre> <p>so now you can write:</p> <pre><code>arr2&lt;fun&lt;double, ptr&lt;int&gt;&gt;&gt; </code></pre> <p>and the syntax is compositional, as well as the typing.</p>
1
1,363
What does this assertion failure mean in a UITableViewDataSource?
<p>Currently following a checklists tutorial built with io6 in mind. I'm using xcode 5, ios7 sdk. The tutorial hasn't been updated for IOS7 but I didn't want to stop my learning so decided to go ahead and work with the outdated tutorial and hopefully use it as a learning experience. Using reading of official Apple docs and extensive googling as my guide along the way.</p> <p>Very early I've run into an issue already and not sure what is wrong. I noticed that the autocomplete had part of the methods below crossed out (a deprecation maybe?). The issue is definitely coming from the code below because once I remove it the simulator loads the app fine.</p> <p><strong>Code causing crash:</strong></p> <pre><code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChecklistItem"]; return cell; } </code></pre> <p><strong>Here is the stack trace:</strong></p> <pre><code>2013-09-28 20:51:26.208 Checklists[47289:a0b] *** Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:], /SourceCache/UIKit_Sim/UIKit-2903.2/UITableView.m:6235 2013-09-28 20:51:26.218 Checklists[47289:a0b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:' *** First throw call stack: ( 0 CoreFoundation 0x017335e4 __exceptionPreprocess + 180 1 libobjc.A.dylib 0x014b68b6 objc_exception_throw + 44 2 CoreFoundation 0x01733448 +[NSException raise:format:arguments:] + 136 3 Foundation 0x0109723e -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 116 4 UIKit 0x00311ae5 __53-[UITableView _configureCellForDisplay:forIndexPath:]_block_invoke + 426 5 UIKit 0x0028af5f +[UIView(Animation) performWithoutAnimation:] + 82 6 UIKit 0x0028afa8 +[UIView(Animation) _performWithoutAnimation:] + 40 7 UIKit 0x00311936 -[UITableView _configureCellForDisplay:forIndexPath:] + 108 8 UIKit 0x00317d4d -[UITableView _createPreparedCellForGlobalRow:withIndexPath:] + 442 9 UIKit 0x00317e03 -[UITableView _createPreparedCellForGlobalRow:] + 69 10 UIKit 0x002fc124 -[UITableView _updateVisibleCellsNow:] + 2378 11 UIKit 0x0030f5a5 -[UITableView layoutSubviews] + 213 12 UIKit 0x00293dd7 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355 13 libobjc.A.dylib 0x014c881f -[NSObject performSelector:withObject:] + 70 14 QuartzCore 0x03aed72a -[CALayer layoutSublayers] + 148 15 QuartzCore 0x03ae1514 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380 16 QuartzCore 0x03aed675 -[CALayer layoutIfNeeded] + 160 17 UIKit 0x0034eca3 -[UIViewController window:setupWithInterfaceOrientation:] + 304 18 UIKit 0x0026dd27 -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:isRotating:] + 5212 19 UIKit 0x0026c8c6 -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:] + 82 20 UIKit 0x0026c798 -[UIWindow _setRotatableViewOrientation:updateStatusBar:duration:force:] + 117 21 UIKit 0x0026c820 -[UIWindow _setRotatableViewOrientation:duration:force:] + 67 22 UIKit 0x0026b8ba __57-[UIWindow _updateToInterfaceOrientation:duration:force:]_block_invoke + 120 23 UIKit 0x0026b81c -[UIWindow _updateToInterfaceOrientation:duration:force:] + 400 24 UIKit 0x0026c573 -[UIWindow setAutorotates:forceUpdateInterfaceOrientation:] + 870 25 UIKit 0x0026fb66 -[UIWindow setDelegate:] + 449 26 UIKit 0x00340dc7 -[UIViewController _tryBecomeRootViewControllerInWindow:] + 180 27 UIKit 0x002657cc -[UIWindow addRootViewControllerViewIfPossible] + 609 28 UIKit 0x00265947 -[UIWindow _setHidden:forced:] + 312 29 UIKit 0x00265bdd -[UIWindow _orderFrontWithoutMakingKey] + 49 30 UIKit 0x0027044a -[UIWindow makeKeyAndVisible] + 65 31 UIKit 0x002238e0 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1851 32 UIKit 0x00227fb8 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 824 33 UIKit 0x0023c42c -[UIApplication handleEvent:withNewEvent:] + 3447 34 UIKit 0x0023c999 -[UIApplication sendEvent:] + 85 35 UIKit 0x00229c35 _UIApplicationHandleEvent + 736 36 GraphicsServices 0x036862eb _PurpleEventCallback + 776 37 GraphicsServices 0x03685df6 PurpleEventCallback + 46 38 CoreFoundation 0x016aedd5 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 53 39 CoreFoundation 0x016aeb0b __CFRunLoopDoSource1 + 523 40 CoreFoundation 0x016d97ec __CFRunLoopRun + 2156 41 CoreFoundation 0x016d8b33 CFRunLoopRunSpecific + 467 42 CoreFoundation 0x016d894b CFRunLoopRunInMode + 123 43 UIKit 0x002276ed -[UIApplication _run] + 840 44 UIKit 0x0022994b UIApplicationMain + 1225 45 Checklists 0x00001b7d main + 141 46 libdyld.dylib 0x01d6f725 start + 0 ) libc++abi.dylib: terminating with uncaught exception of type NSException </code></pre>
1
3,204
Adding labels programmatically, aligned with labels from Storyboard
<p>Desired View:</p> <p><a href="https://i.stack.imgur.com/dIV7P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dIV7P.png" alt="enter image description here"></a></p> <p>In Storyboard I have two labels with the blue background that I am creating in Autolayout. Their position will never change. Next, I would like to add anywhere from 1 to 10 labels in code in <code>cellForRowAtIndexPath</code> below the blue background labels. </p> <p>I am struggling to align the the labels added in code (brown background) with the ones created in Autolayout (blue background).</p> <p>Below is my failed attempt:</p> <p><a href="https://i.stack.imgur.com/lDfRw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lDfRw.png" alt="enter image description here"></a></p> <p>Two approaches that failed: </p> <ol> <li><p>In <code>cellForRowAtIndexPath</code> get the frame of "B AutoLayout Static Label" and use the X position for Dynamic Labels. Did not work.</p></li> <li><p>Adding constraints also did not work -- perhaps I am not adding the constraints correctly.</p></li> </ol> <p>Here is the code:</p> <pre><code>class TableViewController: UITableViewController { var cellHeight = [Int: CGFloat]() override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 85.0 self.tableView.rowHeight = UITableViewAutomaticDimension } override func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return 4 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell let xLocation = cell.labelBStatic.frame.origin.x var yLocation = cell.labelBStatic.frame.origin.y let height = cell.labelBStatic.frame.size.height var startYLocation = yLocation + height + 20 var i = 0 if indexPath.row % 2 == 0 { i = 5 } else { i = 7 } while i &lt; 10 { let aLabel = UILabel() aLabel.backgroundColor = UIColor.orangeColor() aLabel.text = "Label # \(i)" cell.contentView.addSubview(aLabel) addConstraints(aLabel, verticalSpacing: startYLocation) startYLocation += 20 i++ } print(startYLocation) cellHeight[indexPath.row] = startYLocation return cell } func addConstraints(labelView: UILabel, verticalSpacing: CGFloat) { // set Autoresizing Mask to false labelView.translatesAutoresizingMaskIntoConstraints = false //make dictionary for views let viewsDictionary = ["view1": labelView] //sizing constraints let view1_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:[view1(&gt;=50)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary) labelView.addConstraints(view1_constraint_H) //position constraints let view_constraint_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[view1]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary) let view_constraint_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(verticalSpacing)-[view1]", options: NSLayoutFormatOptions.AlignAllLeading, metrics: nil, views: viewsDictionary) view.addConstraints(view_constraint_H as! [NSLayoutConstraint]) view.addConstraints(view_constraint_V as! [NSLayoutConstraint]) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -&gt; CGFloat { if let height = cellHeight[indexPath.row] { return height } return 0 } </code></pre> <p>Below is the <code>Storyboard</code> setup (Both labels are centered horizontally):</p> <p><a href="https://i.stack.imgur.com/7Eh6k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Eh6k.png" alt="enter image description here"></a></p> <p>Question: How can I get my dynamic labels that I am creating in <code>cellForRowAtIndexPath</code> left align with my static labels that were created in <code>Storyboard</code> to match my desired view on top?</p>
1
1,748
ConstraintLayout ignores margins
<p>I have very simple layout, which can be replaced with one RelativeLayout which always work. However wherever I put margins they are ignored and no, I don't want to use padding and no, chain also doesn't fix the problem. Any idea?</p> <p>For example margins on date or manufacturer are ignored as well as others.</p> <pre><code>&lt;android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/card" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:padding="8dp" app:cardBackgroundColor="?attr/szykColorSecondary" app:cardCornerRadius="8dp" app:cardElevation="4dp"&gt; &lt;android.support.constraint.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp"&gt; &lt;TextView android:id="@+id/date" style="?attr/szyk_textMedium" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginBottom="32dp" android:gravity="left" android:singleLine="true" android:text="16.12.2014" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /&gt; &lt;TextView android:id="@+id/manufacturer" style="?attr/szyk_textBody" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:paddingRight="8dp" android:text="Samsung" android:textAllCaps="true" android:textSize="24sp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toLeftOf="@+id/model" app:layout_constraintTop_toBottomOf="@+id/date" /&gt; &lt;TextView android:id="@+id/model" style="?attr/szyk_textBody" android:layout_width="0dp" android:layout_height="wrap_content" android:gravity="left" android:text="S6 edge" android:textAllCaps="true" android:textSize="24sp" app:layout_constraintBottom_toBottomOf="@+id/manufacturer" app:layout_constraintLeft_toRightOf="@+id/manufacturer" app:layout_constraintRight_toLeftOf="@+id/delete" app:layout_constraintTop_toTopOf="@+id/manufacturer" /&gt; &lt;ImageView android:id="@+id/delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_vector_delete" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /&gt; &lt;TextView android:id="@+id/serial" style="?attr/szyk_textMedium" android:layout_width="0dp" android:layout_height="wrap_content" android:ellipsize="end" android:singleLine="true" android:text="FDSF6D7A8FDAS6F7D89AS" android:textSize="12sp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/manufacturer" /&gt; &lt;TextView android:id="@+id/restore" style="?attr/szyk_textButton" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:text="@string/restore" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/serial" /&gt; &lt;/android.support.constraint.ConstraintLayout&gt; &lt;/android.support.v7.widget.CardView&gt; </code></pre> <p>Version</p> <pre><code>compile 'com.android.support.constraint:constraint-layout:1.0.2' </code></pre> <p>Tools</p> <pre><code>compileSdkVersion 27 buildToolsVersion '27.0.2' </code></pre>
1
2,035
Why is vector faster than unordered_map?
<p>I am solving a problem on LeetCode, but nobody has yet been able to explain my issue.</p> <h2>The problem is as such:</h2> <p>Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.</p> <p>Each letter in the magazine string can only be used once in your ransom note.</p> <p>Note: You may assume that both strings contain only lowercase letters.</p> <pre><code>canConstruct(&quot;a&quot;, &quot;b&quot;) -&gt; false canConstruct(&quot;aa&quot;, &quot;ab&quot;) -&gt; false canConstruct(&quot;aa&quot;, &quot;aab&quot;) -&gt; true </code></pre> <h3>My code (which takes 32ms):</h3> <pre><code>class Solution { public: bool canConstruct(string ransomNote, string magazine) { if(ransomNote.size() &gt; magazine.size()) return false; unordered_map&lt;char, int&gt; m; for(int i = 0; i &lt; magazine.size(); i++) m[magazine[i]]++; for(int i = 0; i &lt; ransomNote.size(); i++) { if(m[ransomNote[i]] &lt;= 0) return false; m[ransomNote[i]]--; } return true; } }; </code></pre> <h3>The code (which I dont know why is faster - takes 19ms):</h3> <pre><code>bool canConstruct(string ransomNote, string magazine) { int lettersLeft = ransomNote.size(); // Remaining # of letters to be found in magazine int arr[26] = {0}; for (int j = 0; j &lt; ransomNote.size(); j++) { arr[ransomNote[j] - 'a']++; // letter - 'a' gives a value of 0 - 25 for each lower case letter a-z } int i = 0; while (i &lt; magazine.size() &amp;&amp; lettersLeft &gt; 0) { if (arr[magazine[i] - 'a'] &gt; 0) { arr[magazine[i] - 'a']--; lettersLeft--; } i++; } if (lettersLeft == 0) { return true; } else { return false; } } </code></pre> <p>Both of these have the same complexity and use the same structure to solve the problem, but I don't understand why one takes almost twice as much time than the other. The time to query a vector is O(1), but its the same for an unordered_map. Same story with adding an entry/key to either of them.</p> <p>Please, could someone explain why the run time varies so much?</p>
1
1,030
Fine-Tuning the Inception model in TensorFlow
<p>I want to use the pre-trained Inception model on my own data-set AND I also want to fine-tune the variables of the Inception model itself.</p> <p>I have downloaded the pre-trained Inception model for TensorFlow from the following link:</p> <p><a href="http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz" rel="nofollow">http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz</a></p> <p>I load the Inception model as follows:</p> <pre><code>graph = tf.Graph() with graph.as_default(): with tf.gfile.FastGFile('classify_image_graph_def.pb', 'rb') as file: graph_def = tf.GraphDef() graph_def.ParseFromString(file.read()) tf.import_graph_def(graph_def, name='') </code></pre> <p>(Side note on the API: It would be nice if I could just write <code>graph = tf.load_graph('inception.pb')</code> instead of these six nested and complicated lines.)</p> <p>Then I get a reference to the tensor for the last layer before the softmax-classifier in the Inception model:</p> <pre><code>last_layer = graph.get_tensor_by_name('pool_3:0') </code></pre> <p>Now I want to append a new softmax-classifier to the graph so I can train the new softmax-classifier AND train some or all of the variables in the Inception model. This is what I understand to be fine-tuning, as opposed to transfer learning where only the new softmax-classifier is trained on my own data-set.</p> <p>I then use PrettyTensor to append the new softmax-classifier (note that <code>y_true</code> is a placeholder variable):</p> <pre><code>with pt.defaults_scope(activation_fn=tf.nn.relu): y_pred, loss = pt.wrap(last_layer).\ flatten().\ softmax_classifier(class_count=10, labels=y_true) </code></pre> <p>But this gives a long error-message where the last part reads:</p> <pre><code>ValueError: Tensor("flatten/reshape/Const:0", shape=(2,), dtype=int32) must be from the same graph as Tensor("pool_3:0", shape=(1, 1, 1, 2048), dtype=float32). </code></pre> <p>So I am apparently not allowed to combine two graphs like this.</p> <p>I have also tried using a <code>reshape()</code> instead of <code>flatten()</code> as follows (note the last layer of the Inception model has 2048 features):</p> <pre><code>with pt.defaults_scope(activation_fn=tf.nn.relu): y_pred, loss = pt.wrap(last_layer).\ reshape([-1, 2048]).\ softmax_classifier(class_count=10, labels=y_true) </code></pre> <p>But this gives almost the same error:</p> <pre><code>ValueError: Tensor("reshape/Const:0", shape=(2,), dtype=int32) must be from the same graph as Tensor("pool_3:0", shape=(1, 1, 1, 2048), dtype=float32). </code></pre> <p>I have also tried wrapping it in a <code>graph.as_default()</code> like so:</p> <pre><code>with graph.as_default(): with pt.defaults_scope(activation_fn=tf.nn.relu): y_pred, loss = pt.wrap(last_layer).\ reshape([-1, 2048]).\ softmax_classifier(class_count=10, labels=y_true) </code></pre> <p>But this gives a similar error:</p> <pre><code>ValueError: Tensor("ArgMax_1:0", shape=(?,), dtype=int64) must be from the same graph as Tensor("cross_entropy/ArgMax:0", shape=(1,), dtype=int64). </code></pre> <p>How would I do fine-tuning of the Inception model? I want to add a new softmax-classifier AND I want to fine-tune some or all of the variables in the Inception model itself.</p> <p>Thanks!</p> <hr> <p>EDIT:</p> <p>I have a partial solution to the problem.</p> <p>The error messages were because I didn't put all the code inside the <code>with graph.as_default():</code> block. Putting all the code inside that block fixes the error-messages and I can now append a new softmax-layer to the Inception model using PrettyTensor, as described above.</p> <p>However, the Inception model is apparently a 'frozen' graph which means that all variables have been converted to constants before it was saved.</p> <p>So my question is now, whether I can somehow 'unfreeze' the graph for the Inception model, so I can continue training some or all of the variables of its graph? How would I do this?</p> <p>Or should I instead use the new MetaGraph functionality?</p> <p><a href="https://www.tensorflow.org/versions/r0.11/how_tos/meta_graph/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.11/how_tos/meta_graph/index.html</a></p> <p>Where can I download a pre-trained MetaGraph for the Inception model?</p>
1
1,574
C# enum to postgres enum
<p>I am currently using postgres enum</p> <pre><code>CREATE TYPE http_action_enum AS ENUM ('GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH'); CREATE TABLE IF NOT EXISTS response ( id UUID PRIMARY KEY, http_action http_action_enum NOT NULL ); </code></pre> <p>But when I using the ef framework to insert to postgres database I keep hit the below error:</p> <pre><code>Exception data: Severity: ERROR SqlState: 42804 MessageText: column &quot;destination&quot; is of type source_dest_enum but expression is of type integer Hint: You will need to rewrite or cast the expression. </code></pre> <p>When I check the response data type it is actually the correct enum and not integer.</p> <p>Repository.cs</p> <pre><code>public async Task&lt;Response&gt; InsertRecord(Response response, CancellationToken cancellationToken) { await dBContext.response.AddAsync(response, cancellationToken).ConfigureAwait(true); await dBContext.SaveChangesAsync(cancellationToken).ConfigureAwait(true); return response; } </code></pre> <p>DBContext.cs</p> <pre><code> protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasDefaultSchema(&quot;public&quot;); modelBuilder.HasPostgresEnum&lt;SourceDestinationEnum&gt;(); modelBuilder.HasPostgresEnum&lt;HttpActionEnum&gt;(); modelBuilder.Entity&lt;Response&gt;().Property(d =&gt; d.RespondedData).HasColumnType(&quot;json&quot;); </code></pre> <p>HttpActionEnum.cs</p> <pre><code>[JsonConverter(typeof(StringEnumConverter))] public enum HttpActionEnum { GET, POST, } </code></pre> <p>Does anyone come across mapping c# enum to postgres enum and could advice?</p> <p>I tried converting to an enum but it's failing with an error that say the column is of type enum but expression is of type text.</p> <p><a href="https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions</a></p> <p>DBContext.cs (updated)</p> <pre><code> protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasDefaultSchema(&quot;public&quot;); modelBuilder.HasPostgresEnum&lt;SourceDestinationEnum&gt;(); modelBuilder.HasPostgresEnum&lt;HttpActionEnum&gt;(); modelBuilder.Entity&lt;Response&gt;(entity =&gt; { entity.Property(e =&gt; e.RespondedData).HasColumnType(&quot;json&quot;); entity.Property(e =&gt; e.Destination).HasConversion( v =&gt; v.ToString(), v =&gt; (SourceDestinationEnum)System.Enum.Parse(typeof(SourceDestinationEnum), v)); }); </code></pre> <p>Error</p> <pre><code>+ InnerException {&quot;42804: column \&quot;destination\&quot; is of type source_dest_enum but expression is of type text&quot;} System.Exception {Npgsql.PostgresException} </code></pre>
1
1,257
How can I customize the progress bar of MPMoviePlayerController's background and behavior?
<p>Since I'm new I can't post image yet... so I'll have to draw the picture:</p> <pre><code>--------------------------------------------------------------------------- |[Done] Loading... (*) | --------------------------------------------------------------------------- | | | | | | | | | | | | | | | |--------------------------| | | | | | | | |&lt;&lt; || &gt;&gt;| | | | | | | | |--------------------------| | | | --------------------------------------------------------------------------- </code></pre> <p>My goal is to create a customized MPMoviePlayerController looks like above. </p> <p>The status bar's background has been changed, and the other thing is it shows the "Done" button even when the player is still loading the movie so that the user can cancel the loading (normal behavior of MPMoviePlayerController is to show the "Done" button after the movie starts to play). Believe it or not, the (*) is the activity indicator. </p> <p>I may be wrong, but I think I read somewhere in Apple's document that one can't modify any of the subviews of MPMoviePlayerController, so I'm wondering if anyone has done anything like this before? </p>
1
1,205
XAML gradient issue in UWP for some devices
<p>I'm using <code>Page</code> as landing screen in my app. XAML looks like this:</p> <pre><code>&lt;Grid x:Name="LayoutRoot"&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="3*"/&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition Height="7*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Rectangle StrokeThickness="0" Fill="#FF79D2F4" Margin="0,0,0,-10" Grid.RowSpan="2"/&gt; &lt;Rectangle StrokeThickness="0" Fill="#FF1F8CC5" Margin="0,-10,0,0" Grid.Row="2" Grid.RowSpan="2"/&gt; &lt;Image Source="ms-appx:///Assets/ViewMedia/Banners/Banner_Light_Big.jpg" Grid.Row="1" Grid.RowSpan="2"/&gt; &lt;Rectangle StrokeThickness="0" Grid.Row="2" Grid.RowSpan="2"&gt; &lt;Rectangle.Fill&gt; &lt;LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"&gt; &lt;GradientStop Offset="0"/&gt; &lt;GradientStop Color="#7F000000" Offset="1"/&gt; &lt;/LinearGradientBrush&gt; &lt;/Rectangle.Fill&gt; &lt;/Rectangle&gt; &lt;/Grid&gt; &lt;StackPanel MaxWidth="300" Margin="20,35" HorizontalAlignment="Stretch" VerticalAlignment="Bottom"&gt; &lt;Button x:Name="LoginButton" x:Uid="LoginButton" Style="{StaticResource BrandButtonStyle}" Margin="0,5" Click="LoginButton_Click"/&gt; &lt;Button x:Name="RegisterButton" x:Uid="RegisterButton" Style="{StaticResource BrandButtonStyle}" Margin="0,5" Click="RegisterButton_Click"/&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; </code></pre> <p>I've got 3 devices on which I'm running the app:</p> <ul> <li>Microsoft Lumia 950 XL [<strong>M</strong>]</li> <li>Custom build PC [<strong>PC</strong>]</li> <li>Lenovo ThinkPad Tablet 2 [<strong>T</strong>]</li> </ul> <p>When running the app this page renders well on <strong>M</strong> and <strong>PC</strong> but on <strong>T</strong> <code>Gradient</code> and two <code>Button</code>s at the bottom are not rendered at all. I don't see them but I can press <code>Button</code>s and their tap event handlers will strike. But if I comment <code>Rectangle</code> with gradient everything is fine on all devices.</p> <p>This is how the app looks on <strong>T</strong> when using gradient. No buttons. And gradient is also not visible. <a href="https://i.stack.imgur.com/RrLtW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RrLtW.png" alt="With gradient"></a></p> <p>This is how the app looks on <strong>T</strong> without gradient. Buttons are in place. <a href="https://i.stack.imgur.com/wo1Oi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wo1Oi.png" alt="Without gradient"></a></p> <p>And this is how it should look running on <strong>PC</strong>. Buttons and gradient are visible. <a href="https://i.stack.imgur.com/symt8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/symt8.png" alt="This is how it should look"></a></p> <p>I don't see any errors in output when running the app. I don't know why this happens only on specific devices. Maybe this is kind of known issue?</p> <p><strong>UPDATE 1</strong></p> <p>From users feedback, I can say that this bug hits only Atom-powered devices. But I'm not sure if this is 100% true for all Atom-powered devices.</p> <p><strong>UPDATE 2</strong></p> <p>I'd updated <strong>T</strong> with W10 from Insider Preview Fast Ring. The bug is in place. So this is not connected to OS builds.</p> <p><strong>UPDATE 3</strong></p> <p>Switching <code>Button</code>s <code>Style</code> back to normal does not solve this. So <code>Style</code> is good, it's not the cause.</p>
1
1,548
NHibernate Specified method is not supported
<p>I'm developed webapp using S#arpLite to build a query get a list from many tables. that using NHibernate version 3.3.1.4000</p> <p>I got a error from app when it's running time such as</p> <pre> `NHibernate System.NotSupportedException Specified method is not supported. {Name = "PolymorphicQuerySourceDetector" FullName = "NHibernate.Hql.Ast.ANTLR.PolymorphicQuerySourceDetector"} at NHibernate.Hql.Ast.ANTLR.PolymorphicQuerySourceDetector.GetClassName(IASTNode querySource) at NHibernate.Hql.Ast.ANTLR.PolymorphicQuerySourceDetector.Process(IASTNode tree) at NHibernate.Hql.Ast.ANTLR.AstPolymorphicProcessor.Process() at NHibernate.Hql.Ast.ANTLR.AstPolymorphicProcessor.Process(IASTNode ast, ISessionFactoryImplementor factory) at NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(IASTNode ast, String queryIdentifier, String collectionRole, Boolean shallow, IDictionary`2 filters, ISessionFactoryImplementor factory) at NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(String queryIdentifier, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 filters, ISessionFactoryImplementor factory) at NHibernate.Engine.Query.HQLExpressionQueryPlan.CreateTranslators(String expressionStr, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) at NHibernate.Engine.Query.HQLExpressionQueryPlan..ctor(String expressionStr, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) at NHibernate.Engine.Query.HQLExpressionQueryPlan..ctor(String expressionStr, IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) at NHibernate.Engine.Query.QueryPlanCache.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters) at NHibernate.Impl.AbstractSessionImpl.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow) at NHibernate.Impl.AbstractSessionImpl.CreateQuery(IQueryExpression queryExpression) at NHibernate.Linq.DefaultQueryProvider.PrepareQuery(Expression expression, IQuery& query, NhLinqExpression& nhQuery) at NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression) at NHibernate.Linq.DefaultQueryProvider.Execute[TResult](Expression expression) at Remotion.Linq.QueryableBase`1.GetEnumerator() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at EzLife.Tasks.EmployeeCudTasks.GetEmployees(List`1 listSkill, List`1 listDepartment, List`1 listAssignment, String searchTerm, String jobtitle, String tier, String competency, Nullable`1 startDate, Nullable`1 endDate, Int32 effort, Nullable`1 active, Int32 currentPage, Int32 pageSize, Int32 sortId, Int32 sortName, Int32 sortTitle, Int32 sortTier, Int32 sortJoinedDate, Int32 sortDepartment) in d:\Projects\EzLife\_source\Ezlife\app\EzLife.Tasks\EmployeeCudTasks.cs:line 206` </pre> <p>Here is my code <pre> `public static IQueryable GetEmployeesQ(this IQueryable employees, IQueryable employeeTitles, int currentPage,int pageSize) { var query = from employee in employees join employeeTitle in employeeTitles on employee.Id equals employeeTitle.Employee.Id select new EmployeeDto() { Id = employee.Id, CustomCode = employee.CustomCode, FirstName = employee.FirstName, LastName = employee.LastName, MiddleName = employee.MiddleName, FullName = string.Empty, JoinedDate = employee.JoinedDate, }; return query; }</p> <p>public static IQueryable GetEmployeeTitlesQ(this IQueryable employeeTitles) { return from et1 in employeeTitles join et2 in ( from et in employeeTitles orderby et.Employee.Id, et.StartDate group et by et.Employee.Id into etmax select new { Id = etmax.Max(et => et.Id) } ) on et1.Id equals et2.Id select et1; }`</p> <p></p> <p>I call GetEmployeeTitlesQ in GetEmployeesQ as : ' public IList GetEmployees(int currentPage = 1, int pageSize = 20) {</p> <code> IList&lt;EmployeeDto&gt; employees = new List&lt;EmployeeDto&gt;(); IQueryable&lt;EmployeeTitle&gt; employeeTitles = employeeTitleRep.GetAll().GetEmployeeTitlesQ(); IQueryable&lt;EmployeeDto&gt; employeeDto = employeeRep.GetAll().GetEmployeesQ( employeeTitles , jobTitles , currentPage , pageSize); try { employees = employeeDto.ToList(); } catch (Exception ex) { var mess = ex.Message.ToString(); } return employees; } </code></pre> <p>' I guess there is a problem from Max() function but I don't why. Is there any way work around to resolve it? </p>
1
2,190
How to load .txt file into an object array using >> overloading? C++
<p>This is my first time posting on this site so please spare me any mistakes/etiquette screw ups!</p> <p>Basically I have a project due on Wednesday (yes, for a class). The code is to be written in C++ and it is a program that takes the following data members (as defined in a student class) from a .txt file listed below:</p> <pre><code>class Student { public: //other functions such as add/edit/delete, etc... go here private: string firstname; string lastname; int grade; //1 for Freshman, 2 for Sophmore, 3 for Junior, 4 for Senior int student_id; double credit_hours; //credit hours taken double GPA; //current GPA }; </code></pre> <p>I have also attached the .txt file below. Basically I have to read in the .txt file into an array of that class type, i.e. an object of the Student class. Our teacher said we could assume that the maximum size of the array was [100] students. I have tried several variations of a readFile() function but none have worked. I know I have to overload the >> operator to work with the Student class but I'm not sure how to do this. She suggested a friend function?</p> <p>Here is the .txt file called "StudentRecords.txt" saved in the same directory as the other .cpp file. </p> <pre><code>Harry Smith 2 11121321 100 3.8 Mary Jones 1 43213843 56 3.1 Nicolas Dodsworth 4 54219473 120 2.3 J.Alfred Prufrock 4 83746321 122 4.0 T.S. Eliot 1 99999999 126 4.0 Charlotte Webb 3 44443333 98 3.8 Don Juan 1 12345678 56 1.2 John Smith 2 54234876 66 2.85 Darth Vader 2 87623450 49 2.55 3 CPO 4 33333333 100 4.0 Emily Dickinson 3 23456120 110 3.6 James Buchanan 1 5640012 30 2.23 Carl Rove 1 12995425 28 1.6 Marie Curie 4 88888888 96 3.5 Micky Mouse 2 8222222 64 1.85 James Madison 3 66633333 88 2.96 Dolly Madison 3 53423445 84 3.24 Pepe LePew 1 73737373 42 2.47 Homer Simpson 4 7223344 105 1.03 Mary Jones 1 09274726 28 2.92 Bloss Sims 4 11111111 100 1.2 </code></pre> <p>Thanks guys! I really appreciate your help. I don't really have a lot of experience with C++ mainly Python, so this would definitely be helping me out. </p> <p>EDIT: </p> <p>Code below. The read function is the last function:</p> <pre><code> #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;fstream&gt; using namespace std; class stdRecord { public: string studentID; string studentName; int courseCode; int creditPoint; }; const int MAXRECORD = 100; int menu(); void searchStudent(stdRecord[],int); void showByCourse(stdRecord[],int); //void showEligible(stdRecord[],int); void showAll(stdRecord[],int); void update(stdRecord[],int ); void add(stdRecord[],int *); void deleteRecord(stdRecord[],int *); void findCourses(stdRecord [],int ); int main() { stdRecord stdRec[MAXRECORD]={"15000000","Joshua Andrew Smith", 3506, 240,"16666666", "Jack Williams", 3506, 180,"17000010", "Lily Jones", 3639, 110}; int counter=3; int choice; do { choice=menu(); switch(choice) { case 0: cout&lt;&lt;"Bye for Now"&lt;&lt;endl; break; case 1: searchStudent(stdRec,counter); break; case 2:showByCourse(stdRec,counter); break; case 3://showEligible(stdRec,counter); break; case 4:showAll(stdRec,counter); break; case 5:update(stdRec,counter); break; case 6:add(stdRec,&amp;counter); break; case 7:deleteRecord(stdRec,&amp;counter); break; } }while(choice!=0); system("pause"); } int menu() { int choice; cout&lt;&lt;"0. Exit"&lt;&lt;endl &lt;&lt;"1. Search for a student"&lt;&lt;endl &lt;&lt;"2. List students enrolled in a course"&lt;&lt;endl &lt;&lt;"3. List students eligible to graduate"&lt;&lt;endl &lt;&lt;"4. List all students"&lt;&lt;endl &lt;&lt;"5. Update a student record"&lt;&lt;endl &lt;&lt;"6. Add a student record"&lt;&lt;endl &lt;&lt;"7. Delete a student record"&lt;&lt;endl &lt;&lt;"Your choice -&gt;"; cin&gt;&gt;choice; return choice; } void searchStudent(stdRecord stdRec[],int counter) { string ID; cout&lt;&lt;"Enter the student ID to search-&gt; "; getline(cin,ID); for(int i=0;i&lt;counter;i++) { if(stdRec[i].studentID.compare(ID)==0) { cout&lt;&lt;"The record with the id is:"&lt;&lt;endl; cout&lt;&lt;"StudentID\tStudentName\tCourseCoce\tCreditPoint"&lt;&lt;endl; cout&lt;&lt;stdRec[i].studentID&lt;&lt;"\t"&lt;&lt;stdRec[i].studentName&lt;&lt;"\t"&lt;&lt;stdRec[i].courseCode&lt;&lt;"\t"&lt;&lt;stdRec[i].creditPoint&lt;&lt;endl; cout&lt;&lt;"Have completed the requested process."&lt;&lt;endl; system("pause"); system("cls"); return; } } char ch; cout&lt;&lt;"Not Found"&lt;&lt;endl; cout&lt;&lt;"Do you want search another record(Y/N)"; cin&gt;&gt;ch; ch=tolower(ch); if(ch=='y') searchStudent(stdRec,counter); else { cout&lt;&lt;"Have completed the requested process."&lt;&lt;endl; system("pause"); system("cls"); } } void findCourses(stdRecord stdRec[],int counter) { int courses[500]; int coursecount=0; cout&lt;&lt;" Enter the course code {"; bool found; for(int i=0;i&lt;counter;i++) { found=false; for(int j=0;j&lt;coursecount;j++) { if(stdRec[i].courseCode==courses[j]) { found=true; break; } } if(!found) courses[coursecount++]=stdRec[i].courseCode; } cout&lt;&lt;" Enter the course code {"; for(int j=0;j&lt;coursecount-1;j++) cout&lt;&lt;courses[j]&lt;&lt;", "; cout&lt;&lt;"or "&lt;&lt;courses[coursecount-1]&lt;&lt;"-&gt;"; } void showByCourse(stdRecord stdRec[],int counter) { int courseCode; findCourses(stdRec,counter); cin&gt;&gt;courseCode; cout&lt;&lt;"The student(s) enrolled in the course is(are):"&lt;&lt;endl; cout&lt;&lt;"StudentID\tStudentName\tCourseCoce\tCreditPoint"&lt;&lt;endl; int studentsCount=0; for(int i=0;i&lt;counter;i++) { if(stdRec[i].courseCode==courseCode) { cout&lt;&lt;stdRec[i].studentID&lt;&lt;"\t"&lt;&lt;stdRec[i].studentName&lt;&lt;"\t"&lt;&lt;stdRec[i].courseCode&lt;&lt;"\t"&lt;&lt;stdRec[i].creditPoint&lt;&lt;endl; studentsCount++; } } cout&lt;&lt;"There is(are) "&lt;&lt;studentsCount&lt;&lt;" student(s) enrolled in the course."&lt;&lt;endl; cout&lt;&lt;"Have completed the requested process."&lt;&lt;endl; system("pause"); system("cls"); } void showEligible(stdRecord stdRec[],int counter) { cout&lt;&lt;"The student(s) eligible to graduate is(are):"&lt;&lt;endl; int studentsCount=0; for(int i=0;i&lt;counter;i++) { if(stdRec[i].creditPoint&gt;=240) { cout&lt;&lt;stdRec[i].studentID&lt;&lt;"\t"&lt;&lt;stdRec[i].studentName&lt;&lt;"\t"&lt;&lt;stdRec[i].courseCode&lt;&lt;"\t"&lt;&lt;stdRec[i].creditPoint&lt;&lt;endl; studentsCount++; } } cout&lt;&lt;"There is(are) "&lt;&lt;studentsCount&lt;&lt;" graduate student(s)."&lt;&lt;endl; cout&lt;&lt;"Have completed the requested process."&lt;&lt;endl; system("pause"); system("cls"); } void showAll(stdRecord stdRec[],int counter) { cout&lt;&lt;"All students are listed below:"&lt;&lt;endl; for(int i=0;i&lt;counter;i++) { cout&lt;&lt;stdRec[i].studentID&lt;&lt;"\t"&lt;&lt;stdRec[i].studentName&lt;&lt;"\t"&lt;&lt;stdRec[i].courseCode&lt;&lt;"\t"&lt;&lt;stdRec[i].creditPoint&lt;&lt;endl; } cout&lt;&lt;"Have completed the requested process."&lt;&lt;endl; system("pause"); system("cls"); } void update(stdRecord stdRec[],int counter) { char keepGoing; string ID; do { cout&lt;&lt;"Enter the student ID to update-&gt; "; getline(cin,ID); bool flag=false; char choice; for(int i=0;i&lt;counter;i++) { if(stdRec[i].studentID.compare(ID)==0) { cout&lt;&lt;"The record with the id is:"&lt;&lt;endl; cout&lt;&lt;"StudentID\tStudentName\tCourseCoce\tCreditPoint"&lt;&lt;endl; cout&lt;&lt;stdRec[i].studentID&lt;&lt;"\t"&lt;&lt;stdRec[i].studentName&lt;&lt;"\t"&lt;&lt;stdRec[i].courseCode&lt;&lt;"\t"&lt;&lt;stdRec[i].creditPoint&lt;&lt;endl; cout&lt;&lt;"Enter y or Y to update the course code, others to keep the original one."&lt;&lt;endl; cin&gt;&gt;choice; if(choice=='y'||choice=='Y') { int courseCode; findCourses(stdRec,counter); cin&gt;&gt;courseCode; stdRec[i].courseCode=courseCode; } cout&lt;&lt;"Enter y or Y to update the credit"; cin&gt;&gt;choice; if(choice=='y'||choice=='Y') { int credits; cout&lt;&lt;"Enter Credit points"; cin&gt;&gt;credits; stdRec[i].creditPoint=credits; } flag=true; break; } } if(!flag) { cout&lt;&lt;"The record with the id "&lt;&lt;ID&lt;&lt;" not Found"&lt;&lt;endl; } cout&lt;&lt;"Do you want update another record(Y/N)"; cin&gt;&gt;keepGoing; keepGoing=tolower(keepGoing); }while(keepGoing=='y'); cout&lt;&lt;"Have completed the requested process."&lt;&lt;endl; system("pause"); system("cls"); } void add(stdRecord stdRec[],int *counter) { string studentID; string studentName; int courseCode; int creditPoint; cout&lt;&lt;"Enter Student ID :"; cin&gt;&gt;studentID; bool flag=true; for(int i=0;i&lt;*counter;i++) { if(stdRec[i].studentID.compare(studentID)==0) { flag=false; break; } } if(flag) { stdRec[*counter].studentID=studentID; cout&lt;&lt;"Enter Student Name \n"; cin &gt;&gt; studentName; stdRec[*counter].studentName=studentName; cout&lt;&lt;"Enter Course Code \n"; cin &gt;&gt; courseCode; stdRec[*counter].courseCode=courseCode; cout &lt;&lt; "Enter Credit Points \n"; cin &gt;&gt; creditPoint; stdRec[*counter].creditPoint=creditPoint; } else { cout&lt;&lt;"Student Id Exists"&lt;&lt;endl; } cout&lt;&lt;"Have completed the requested process."&lt;&lt;endl; system("pause"); system("cls"); } void deleteRecord(stdRecord stdRec[],int *counter){} void readIn(stdRecord stdRec[]) { ifstream file("StudentRecords.txt"); if(file.is_open()) { stdRecord stdRec[MAXRECORD]; for(int i = 0; i &lt; MAXRECORD; i++) { file &gt;&gt; stdRec[i]; } } } </code></pre>
1
5,470
Spark UDF exception when accessing broadcast variable
<p>I'm having difficulty accessing a <code>scala.collection.immutable.Map</code> from inside a spark UDF. </p> <p>I'm broadcasting the map</p> <pre><code>val browserLangMap = sc.broadcast (Source.fromFile(browserLangFilePath).getLines.map(_.split(,)).map(e =&gt; (e(0).toInt,e(1))).toMap) </code></pre> <p>creating UDF that access the map</p> <pre><code>def addBrowserCode = udf((browserLang:Int) =&gt; if(browserLangMap.value.contains(browserLang)) browserLangMap.value(browserLang) else "")` </code></pre> <p>using the UDF to add new column</p> <pre><code>val joinedDF = rawDF.join(broadcast(geoDF).as("GEO"), $"start_ip" === $"GEO.start_ip_num", "left_outer") .withColumn("browser_code", addBrowserCode($"browser_language")) .selectExpr(getSelectQuery:_*) </code></pre> <p>full stack trace --> <a href="https://www.dropbox.com/s/p1d5322fo9cxro6/stack_trace.txt?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/p1d5322fo9cxro6/stack_trace.txt?dl=0</a></p> <pre><code>org.apache.spark.SparkException: Task not serializable at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:304) at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:294) at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:122) at org.apache.spark.SparkContext.clean(SparkContext.scala:2055) at org.apache.spark.SparkContext.runJob(SparkContext.scala:1857) at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala) Caused by: java.io.NotSerializableException: $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$MetaDataSchema$ Serialization stack: - object not serializable (class: $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$MetaDataSchema$, value: $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$MetaDataSchema$@30b4ba52) - field (class: $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC, name: MetaDataSchema$module, type: class $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$MetaDataSchema$) - object (class org.apache.spark.sql.catalyst.expressions.ScalaUDF, UDF(browser_language#235)) - field (class: org.apache.spark.sql.catalyst.expressions.If, name: falseValue, type: class org.apache.spark.sql.catalyst.expressions.Expression) - object (class org.apache.spark.sql.catalyst.expressions.If, if (isnull(browser_language#235)) null else UDF(browser_language#235)) - field (class: org.apache.spark.sql.catalyst.expressions.Alias, name: child, type: class org.apache.spark.sql.catalyst.expressions.Expression) - object (class org.apache.spark.sql.catalyst.expressions.Alias, if (isnull(browser_language#235)) null else UDF(browser_language#235) AS browser_language#507) - object (class org.apache.spark.OneToOneDependency, org.apache.spark.OneToOneDependency@5ae38c4e) - writeObject data (class: scala.collection.immutable.$colon$colon) - object (class scala.collection.immutable.$colon$colon, List(org.apache.spark.OneToOneDependency@5ae38c4e)) - field (class: org.apache.spark.rdd.RDD, name: org$apache$spark$rdd$RDD$$dependencies_, type: interface scala.collection.Seq) at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:301) ... 80 more </code></pre> <p>I know its the access to broadcast Map that is causing this. When I remove reference to that in the UDF there are no exception.</p> <pre><code>def addBrowserCode = udf((browserLang:Int) =&gt; browserLang.toString()) //Test UDF without accessing broadcast Map and it works </code></pre> <p>Spark version 1.6</p>
1
1,668
How to animate an item in the ViewPager after PagerTransform animation?
<p>I am working with viewpager transformer. I am able add a transition effect using transformPage() method. The below given is my pager.</p> <pre><code>final ViewPager pager = (ViewPager) localView .findViewById(R.id.pager); pager.setAdapter(new my_adapter()); pager.setPageTransformer(true, new PageTransformer() { @Override public void transformPage(View view, float position) { int pageWidth = view.getWidth(); if (position &lt; -1) { // [-Infinity,-1) // This page is way off-screen to the left. view.setAlpha(1); } else if (position &lt;= 1) { // [-1,1] View dummyImageView = view.findViewById(R.id.tourImage); dummyImageView.setTranslationX(-position * (pageWidth / 2)); // Half View imageBottom = view .findViewById(R.id.tour_bottom_image); imageBottom.setTranslationX(-position * (pageWidth / 10)); // Half speed } else { // (1,+Infinity] // This page is way off-screen to the right. view.setAlpha(1); } } }); </code></pre> <p>And this is my adapter,</p> <pre><code>private class my_adapter extends PagerAdapter { @Override public int getCount() { return num_pages; } @Override public boolean isViewFromObject(View view, Object o) { return view == o; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public Object instantiateItem(ViewGroup container, int position) { View new_view = null; LayoutInflater inflater = getActivity().getLayoutInflater(); new_view = inflater.inflate(R.layout.tour_page_one, null); TextView tvTourDesc = (TextView) new_view .findViewById(R.id.tourDesc); ImageView imageTour = (ImageView) new_view .findViewById(R.id.tourImage); ImageView imageBottomTour = (ImageView) new_view .findViewById(R.id.tour_bottom_image); container.addView(new_view); return new_view; } } </code></pre> <p>What I am trying to do is animate an item in the adapter, for instance imageTour imageView,once the transition animation is finished. When I add any animation it starts along with the pager transform animation. I want to animate it always after the transition animation. I tried using onPageChangeListener with the pager but it doesn't return any view other than the currentPage number so that i can add animation to imageTour(imageView).</p>
1
1,176
Calling a function and passing parameters stored in a tuple?
<p>I want a class Foo to store a function pointer, which it got on construction, and to call this function at some point. I looked at these two questions for help:</p> <ul> <li><a href="https://stackoverflow.com/questions/4105002/pass-tuples-content-as-variadic-function-arguments">Pass tuple&#39;s content as variadic function arguments</a></li> <li><a href="https://stackoverflow.com/questions/687490/how-do-i-expand-a-tuple-into-variadic-template-functions-arguments">How do I expand a tuple into variadic template function&#39;s arguments?</a></li> </ul> <p>And, based on the answers, came up with this code:</p> <pre><code>#include &lt;functional&gt; template &lt; int N, typename... ARGS &gt; struct apply_func { static void applyTuple( std::function&lt;void(ARGS...)&gt;&amp; f, const std::tuple&lt;ARGS...&gt;&amp; t, ARGS... args ) { apply_func&lt;N-1&gt;::applyTuple( f, t, std::get&lt;N-1&gt;( t ), args... ); } }; template &lt;typename... ARGS&gt; struct apply_func&lt;0,ARGS...&gt; { static void applyTuple( std::function&lt;void(ARGS...)&gt;&amp; f, const std::tuple&lt;ARGS...&gt;&amp; /* t */, ARGS... args ) { f( args... ); } }; template &lt; typename... ARGS &gt; void applyTuple( std::function&lt;void(ARGS...)&gt;&amp; f, std::tuple&lt;ARGS...&gt; const&amp; t ) { apply_func&lt;sizeof...(ARGS), ARGS...&gt;::applyTuple( f, t ); } template&lt;typename... ARGS&gt; class Foo { std::function&lt;void(ARGS...)&gt; m_f; std::tuple&lt;ARGS...&gt; *argument_pack; public: Foo(std::function&lt;void(ARGS...)&gt; f):m_f(f){} void operator()(ARGS... args); void run(); }; template&lt;typename... ARGS&gt; void Foo&lt;ARGS...&gt;::operator()(ARGS... args) { m_f(args...); // this works } template&lt;typename... ARGS&gt; void Foo&lt;ARGS...&gt;::run() { applyTuple&lt;ARGS...&gt;(m_f, *argument_pack); // this doesn't compile } void bar(int i, double d){} int main(void) { Foo&lt;int,double&gt; foo(bar); foo(1,1.0); // this works foo.run(); // this doesn't compile } </code></pre> <p>If you compile with ´g++ -std=c++0x´ the next to last line will give this error:</p> <pre><code> test.cc: In function ‘void applyTuple(std::function&lt;void(ARGS ...)&gt;&amp;, const std::tuple&lt;_Elements ...&gt;&amp;) [with ARGS = {int, double}]’: test.cc:52:9: instantiated from ‘void Foo&lt;ARGS&gt;::run() [with ARGS = {int, double}]’ test.cc:61:17: instantiated from here test.cc:27:8: error: no matching function for call to ‘apply_func&lt;2, int, double&gt;::applyTuple(std::function&lt;void(int, double)&gt;&amp;, const std::tuple&lt;int, double&gt;&amp;)’ test.cc:27:8: note: candidate is: test.cc:6:19: note: static void apply_func&lt;N, ARGS&gt;::applyTuple(std::function&lt;void(ARGS ...)&gt;&amp;, const std::tuple&lt;_Elements ...&gt;&amp;, ARGS ...) [with int N = 2, ARGS = {int, double}] test.cc:6:19: note: candidate expects 4 arguments, 2 provided test.cc: In static member function ‘static void apply_func&lt;N, ARGS&gt;::applyTuple(std::function&lt;void(ARGS ...)&gt;&amp;, const std::tuple&lt;_Elements ...&gt;&amp;, ARGS ...) [with int N = 2, ARGS = {int, double}]’: test.cc:27:8: instantiated from ‘void applyTuple(std::function&lt;void(ARGS ...)&gt;&amp;, const std::tuple&lt;_Elements ...&gt;&amp;) [with ARGS = {int, double}]’ test.cc:52:9: instantiated from ‘void Foo&lt;ARGS&gt;::run() [with ARGS = {int, double}]’ test.cc:61:17: instantiated from here test.cc:9:9: error: no matching function for call to ‘apply_func&lt;1&gt;::applyTuple(std::function&lt;void(int, double)&gt;&amp;, const std::tuple&lt;int, double&gt;&amp;, const double&amp;, int&amp;, double&amp;)’ test.cc:9:9: note: candidate is: test.cc:6:19: note: static void apply_func&lt;N, ARGS&gt;::applyTuple(std::function&lt;void(ARGS ...)&gt;&amp;, const std::tuple&lt;_Elements ...&gt;&amp;, ARGS ...) [with int N = 1, ARGS = {}] test.cc:6:19: note: candidate expects 2 arguments, 5 provided test.cc: In static member function ‘static void apply_func&lt;N, ARGS&gt;::applyTuple(std::function&lt;void(ARGS ...)&gt;&amp;, const std::tuple&lt;_Elements ...&gt;&amp;, ARGS ...) [with int N = 1, ARGS = {}]’: test.cc:9:9: instantiated from ‘static void apply_func&lt;N, ARGS&gt;::applyTuple(std::function&lt;void(ARGS ...)&gt;&amp;, const std::tuple&lt;_Elements ...&gt;&amp;, ARGS ...) [with int N = 2, ARGS = {int, double}]’ test.cc:27:8: instantiated from ‘void applyTuple(std::function&lt;void(ARGS ...)&gt;&amp;, const std::tuple&lt;_Elements ...&gt;&amp;) [with ARGS = {int, double}]’ test.cc:52:9: instantiated from ‘void Foo&lt;ARGS&gt;::run() [with ARGS = {int, double}]’ test.cc:61:17: instantiated from here test.cc:9:9: error: no matching function for call to ‘get(const std::tuple&lt;&gt;&amp;)’ test.cc:9:9: note: candidates are: /usr/include/c++/4.6/utility:133:5: note: template&lt;long unsigned int _Int, class _Tp1, class _Tp2&gt; typename std::tuple_element&lt;_Int, std::pair&lt;_Tp1, _Tp2&gt; &gt;::type&amp; std::get(std::pair&lt;_Tp1, _Tp2&gt;&amp;) /usr/include/c++/4.6/utility:138:5: note: template&lt;long unsigned int _Int, class _Tp1, class _Tp2&gt; const typename std::tuple_element&lt;_Int, std::pair&lt;_Tp1, _Tp2&gt; &gt;::type&amp; std::get(const std::pair&lt;_Tp1, _Tp2&gt;&amp;) /usr/include/c++/4.6/tuple:531:5: note: template&lt;long unsigned int __i, class ... _Elements&gt; typename std::__add_ref&lt;typename std::tuple_element&lt;__i, std::tuple&lt;_Elements ...&gt; &gt;::type&gt;::type std::get(std::tuple&lt;_Elements ...&gt;&amp;) /usr/include/c++/4.6/tuple:538:5: note: template&lt;long unsigned int __i, class ... _Elements&gt; typename std::__add_c_ref&lt;typename std::tuple_element&lt;__i, std::tuple&lt;_Elements ...&gt; &gt;::type&gt;::type std::get(const std::tuple&lt;_Elements ...&gt;&amp;) </code></pre> <p>What am I missing? Thanks!</p>
1
2,615
Django Multi-Table Inheritance VS Specifying Explicit OneToOne Relationship in Models
<p>Hope all this makes sense :) I'll clarify via comments if necessary. Also, I am experimenting using bold text in this question, and will edit it out if I (or you) find it distracting. With that out of the way...</p> <p>Using django.contrib.auth gives us User and Group, among other useful things that I can't do without (like basic messaging).</p> <p>In my app I have several different types of users. A user can be of only one type. That would easily be handled by groups, with a little extra care. <strong>However, these different users are related to each other in hierarchies / relationships.</strong></p> <p>Let's take a look at these users: - </p> <p><strong>Principals - "top level" users</strong></p> <p><strong>Administrators - each administrator reports to a Principal</strong></p> <p><strong>Coordinators - each coordinator reports to an Administrator</strong></p> <p>Apart from these <strong>there are other user types that are not directly related</strong>, but may get related later on. For example, "Company" is another type of user, and can have various "Products", and products may be supervised by a "Coordinator". "Buyer" is another kind of user that may buy products.</p> <p>Now all these <strong>users have various other attributes, some of which are common to all types of users and some of which are distinct only to one user type</strong>. For example, all types of users have to have an address. On the other hand, only the Principal user belongs to a "BranchOffice".</p> <p>Another point, which was stated above, is that <strong>a User can only ever be of one type</strong>.</p> <p>The app also <strong>needs to keep track of who created and/or modified Principals, Administrators, Coordinators, Companies, Products etc</strong>. (So that's two more links to the User model.)</p> <p>In this scenario, is it a good idea to use Django's multi-table inheritance as follows: - </p> <pre><code>from django.contrib.auth.models import User class Principal(User): # # # branchoffice = models.ForeignKey(BranchOffice) landline = models.CharField(blank=True, max_length=20) mobile = models.CharField(blank=True, max_length=20) created_by = models.ForeignKey(User, editable=False, blank=True, related_name="principalcreator") modified_by = models.ForeignKey(User, editable=False, blank=True, related_name="principalmodifier") # # # </code></pre> <p>Or should I go about doing it like this: - </p> <pre><code>class Principal(models.Model): # # # user = models.OneToOneField(User, blank=True) branchoffice = models.ForeignKey(BranchOffice) landline = models.CharField(blank=True, max_length=20) mobile = models.CharField(blank=True, max_length=20) created_by = models.ForeignKey(User, editable=False, blank=True, related_name="principalcreator") modified_by = models.ForeignKey(User, editable=False, blank=True, related_name="principalmodifier") # # # </code></pre> <p>Please keep in mind that there are other user types that are related via foreign keys, for example: -</p> <pre><code>class Administrator(models.Model): # # # principal = models.ForeignKey(Principal, help_text="The supervising principal for this Administrator") user = models.OneToOneField(User, blank=True) province = models.ForeignKey( Province) landline = models.CharField(blank=True, max_length=20) mobile = models.CharField(blank=True, max_length=20) created_by = models.ForeignKey(User, editable=False, blank=True, related_name="administratorcreator") modified_by = models.ForeignKey(User, editable=False, blank=True, related_name="administratormodifier") </code></pre> <p>I am aware that Django does use a one-to-one relationship for multi-table inheritance behind the scenes. I am just not qualified enough to decide which is a more sound approach.</p>
1
1,235
Selenium grid 4 : Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure error
<p>Trying to set up selenium 4 grid with the below docker-compose file but getting the &quot;<em>Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure</em>&quot; error and need some help to fix the same.</p> <p><strong>docker-compose file:</strong></p> <pre><code># To execute this docker-compose yml file use `docker-compose -f docker-compose-v3-full-grid.yml up` # Add the `-d` flag at the end for detached execution # To stop the execution, hit Ctrl+C, and then `docker-compose -f docker-compose-v3-full-grid.yml down` version: &quot;3&quot; services: selenium-event-bus: image: selenium/event-bus:4.0.0-20211013 container_name: selenium-event-bus ports: - &quot;4442:4442&quot; - &quot;4443:4443&quot; - &quot;5557:5557&quot; selenium-sessions: image: selenium/sessions:4.0.0-20211013 container_name: selenium-sessions ports: - &quot;5556:5556&quot; depends_on: - selenium-event-bus environment: - SE_EVENT_BUS_HOST=selenium-event-bus - SE_EVENT_BUS_PUBLISH_PORT=4442 - SE_EVENT_BUS_SUBSCRIBE_PORT=4443 selenium-session-queue: image: selenium/session-queue:4.0.0-20211013 container_name: selenium-session-queue ports: - &quot;5559:5559&quot; depends_on: - selenium-event-bus environment: - SE_EVENT_BUS_HOST=selenium-event-bus - SE_EVENT_BUS_PUBLISH_PORT=4442 - SE_EVENT_BUS_SUBSCRIBE_PORT=4443 selenium-distributor: image: selenium/distributor:4.0.0-20211013 container_name: selenium-distributor ports: - &quot;5553:5553&quot; depends_on: - selenium-event-bus - selenium-sessions - selenium-session-queue environment: - SE_EVENT_BUS_HOST=selenium-event-bus - SE_EVENT_BUS_PUBLISH_PORT=4442 - SE_EVENT_BUS_SUBSCRIBE_PORT=4443 - SE_SESSIONS_MAP_HOST=selenium-sessions - SE_SESSIONS_MAP_PORT=5556 - SE_SESSION_QUEUE_HOST=selenium-session-queue - SE_SESSION_QUEUE_PORT=5559 selenium-router: image: selenium/router:4.0.0-20211013 container_name: selenium-router ports: - &quot;4444:4444&quot; depends_on: - selenium-distributor - selenium-sessions - selenium-session-queue environment: - SE_DISTRIBUTOR_HOST=selenium-distributor - SE_DISTRIBUTOR_PORT=5553 - SE_SESSIONS_MAP_HOST=selenium-sessions - SE_SESSIONS_MAP_PORT=5556 - SE_SESSION_QUEUE_HOST=selenium-session-queue - SE_SESSION_QUEUE_PORT=5559 chrome: image: selenium/node-chrome:4.0.0-20211013 shm_size: 2gb depends_on: - selenium-event-bus environment: - SE_EVENT_BUS_HOST=selenium-event-bus - SE_EVENT_BUS_PUBLISH_PORT=4442 - SE_EVENT_BUS_SUBSCRIBE_PORT=4443 ports: - &quot;6900:5900&quot; </code></pre> <p><strong>Run command:</strong></p> <pre><code>mvn clean install </code></pre> <p>This will trigger the execution of one cucumber test scenario thru the test runner mentioned in the testing.xml file.</p> <p>It looks like the setup is pretty much completed and the logs here:</p> <pre><code> 0.3s dhamo@Dhamo-Mac expressqa_ecom_web % docker-compose -f docker-compose-v3-full-grid.yml up [+] Running 7/7 ⠿ Network expressqa_ecom_web_default Created 0.1s ⠿ Container selenium-event-bus Started 3.5s ⠿ Container expressqa_ecom_web_chrome_1 Started 5.3s ⠿ Container selenium-session-queue Started 4.7s ⠿ Container selenium-sessions Started 5.2s ⠿ Container selenium-distributor Started 5.6s ⠿ Container selenium-router Started 6.4s Attaching to chrome_1, selenium-distributor, selenium-event-bus, selenium-router, selenium-session-queue, selenium-sessions selenium-distributor | 2021-10-18 21:02:16,505 INFO spawned: 'selenium-grid-distributor' with pid 20 selenium-distributor | Starting Selenium Grid Distributor... selenium-distributor | 2021-10-18 21:02:16,682 INFO success: selenium-grid-distributor entered RUNNING state, process has stayed up for &gt; than 0 seconds (startsecs) selenium-router | 2021-10-18 21:02:17,426 INFO Included extra file &quot;/etc/supervisor/conf.d/selenium-grid-router.conf&quot; during parsing selenium-router | 2021-10-18 21:02:17,434 INFO supervisord started with pid 12 chrome_1 | Configuring server... chrome_1 | Setting up SE_NODE_HOST... chrome_1 | Setting up SE_NODE_PORT... chrome_1 | Setting up SE_NODE_GRID_URL... selenium-router | 2021-10-18 21:02:18,447 INFO spawned: 'selenium-grid-router' with pid 18 selenium-router | Starting Selenium Grid Router... selenium-router | 2021-10-18 21:02:18,607 INFO success: selenium-grid-router entered RUNNING state, process has stayed up for &gt; than 0 seconds (startsecs) chrome_1 | Selenium Grid Node configuration: chrome_1 | [events] chrome_1 | publish = &quot;tcp://selenium-event-bus:4442&quot; chrome_1 | subscribe = &quot;tcp://selenium-event-bus:4443&quot; chrome_1 | chrome_1 | [node] chrome_1 | session-timeout = &quot;300&quot; chrome_1 | override-max-sessions = false chrome_1 | detect-drivers = false chrome_1 | max-sessions = 1 chrome_1 | chrome_1 | [[node.driver-configuration]] chrome_1 | display-name = &quot;chrome&quot; chrome_1 | stereotype = '{&quot;browserName&quot;: &quot;chrome&quot;, &quot;browserVersion&quot;: &quot;94.0&quot;, &quot;platformName&quot;: &quot;Linux&quot;}' chrome_1 | max-sessions = 1 chrome_1 | chrome_1 | Starting Selenium Grid Node... selenium-event-bus | 21:02:19.503 INFO [LoggingOptions.configureLogEncoding] - Using the system default encoding selenium-session-queue | 21:02:19.845 INFO [LoggingOptions.configureLogEncoding] - Using the system default encoding selenium-event-bus | 21:02:20.194 INFO [BoundZmqEventBus.&lt;init&gt;] - XPUB binding to [binding to tcp://*:4442, advertising as tcp://172.24.0.2:4442], XSUB binding to [binding to tcp://*:4443, advertising as tcp://172.24.0.2:4443] selenium-sessions | 21:02:20.568 INFO [LoggingOptions.configureLogEncoding] - Using the system default encoding selenium-sessions | 21:02:20.828 INFO [OpenTelemetryTracer.createTracer] - Using OpenTelemetry for tracing selenium-event-bus | 21:02:21.517 INFO [UnboundZmqEventBus.&lt;init&gt;] - Connecting to tcp://172.24.0.2:4442 and tcp://172.24.0.2:4443 selenium-event-bus | 21:02:22.199 INFO [UnboundZmqEventBus.&lt;init&gt;] - Sockets created selenium-sessions | 21:02:22.602 INFO [UnboundZmqEventBus.&lt;init&gt;] - Connecting to tcp://selenium-event-bus:4442 and tcp://selenium-event-bus:4443 selenium-event-bus | 21:02:23.238 INFO [UnboundZmqEventBus.&lt;init&gt;] - Event bus ready selenium-session-queue | 21:02:23.839 INFO [OpenTelemetryTracer.createTracer] - Using OpenTelemetry for tracing selenium-distributor | 21:02:23.759 INFO [LoggingOptions.configureLogEncoding] - Using the system default encoding selenium-sessions | 21:02:23.971 INFO [UnboundZmqEventBus.&lt;init&gt;] - Sockets created selenium-distributor | 21:02:23.987 INFO [OpenTelemetryTracer.createTracer] - Using OpenTelemetry for tracing selenium-sessions | 21:02:25.028 INFO [UnboundZmqEventBus.&lt;init&gt;] - Event bus ready selenium-session-queue | 21:02:25.443 INFO [UnboundZmqEventBus.&lt;init&gt;] - Connecting to tcp://selenium-event-bus:4442 and tcp://selenium-event-bus:4443 selenium-distributor | 21:02:25.711 INFO [UnboundZmqEventBus.&lt;init&gt;] - Connecting to tcp://selenium-event-bus:4442 and tcp://selenium-event-bus:4443 selenium-router | 21:02:25.948 INFO [LoggingOptions.configureLogEncoding] - Using the system default encoding selenium-router | 21:02:26.012 INFO [OpenTelemetryTracer.createTracer] - Using OpenTelemetry for tracing selenium-session-queue | 21:02:26.349 INFO [UnboundZmqEventBus.&lt;init&gt;] - Sockets created selenium-distributor | 21:02:26.883 INFO [UnboundZmqEventBus.&lt;init&gt;] - Sockets created selenium-event-bus | 21:02:27.149 INFO [BaseServerOptions.lambda$getExternalUri$0] - No network connection, guessing name: 13687f81574b selenium-session-queue | 21:02:27.419 INFO [UnboundZmqEventBus.&lt;init&gt;] - Event bus ready selenium-event-bus | 21:02:27.508 WARN [MacAddressUtil.defaultMachineId] - Failed to find a usable hardware address from the network interfaces; using random bytes: c4:5c:a7:6e:6e:8d:0a:e3 selenium-distributor | 21:02:27.932 INFO [UnboundZmqEventBus.&lt;init&gt;] - Event bus ready chrome_1 | 21:02:28.316 INFO [LoggingOptions.configureLogEncoding] - Using the system default encoding chrome_1 | 21:02:28.394 INFO [OpenTelemetryTracer.createTracer] - Using OpenTelemetry for tracing selenium-event-bus | 21:02:28.417 INFO [EventBusCommand.execute] - Started Selenium EventBus 4.0.0 (revision 3a21814679): http://13687f81574b:5557 selenium-session-queue | 21:02:28.435 INFO [BaseServerOptions.lambda$getExternalUri$0] - No network connection, guessing name: 9d9b6ded1846 selenium-sessions | 21:02:28.624 INFO [BaseServerOptions.lambda$getExternalUri$0] - No network connection, guessing name: 7dbac3cddaa7 selenium-session-queue | 21:02:28.872 WARN [MacAddressUtil.defaultMachineId] - Failed to find a usable hardware address from the network interfaces; using random bytes: 28:9e:a1:e5:f8:f2:8f:d6 selenium-sessions | 21:02:28.929 WARN [MacAddressUtil.defaultMachineId] - Failed to find a usable hardware address from the network interfaces; using random bytes: 83:83:18:81:93:d2:80:1b selenium-sessions | 21:02:29.453 INFO [SessionMapServer.execute] - Started Selenium SessionMap 4.0.0 (revision 3a21814679): http://7dbac3cddaa7:5556 selenium-session-queue | 21:02:29.551 INFO [NewSessionQueueServer.execute] - Started Selenium SessionQueue 4.0.0 (revision 3a21814679): http://9d9b6ded1846:5559 chrome_1 | 21:02:29.976 INFO [UnboundZmqEventBus.&lt;init&gt;] - Connecting to tcp://selenium-event-bus:4442 and tcp://selenium-event-bus:4443 chrome_1 | 21:02:30.655 INFO [UnboundZmqEventBus.&lt;init&gt;] - Sockets created chrome_1 | 21:02:31.736 INFO [UnboundZmqEventBus.&lt;init&gt;] - Event bus ready selenium-router | 21:02:32.709 INFO [BaseServerOptions.lambda$getExternalUri$0] - No network connection, guessing name: 8885bd19bf09 chrome_1 | 21:02:32.908 INFO [BaseServerOptions.lambda$getExternalUri$0] - No network connection, guessing name: 8646325b6e37 chrome_1 | 21:02:32.943 INFO [NodeServer.createHandlers] - Reporting self as: http://8646325b6e37:5555 chrome_1 | 21:02:32.989 INFO [BaseServerOptions.lambda$getExternalUri$0] - No network connection, guessing name: 8646325b6e37 chrome_1 | 21:02:33.441 INFO [NodeOptions.getSessionFactories] - Detected 4 available processors selenium-distributor | 21:02:33.943 INFO [BaseServerOptions.lambda$getExternalUri$0] - No network connection, guessing name: d8e53d166441 selenium-distributor | 21:02:35.974 WARN [MacAddressUtil.defaultMachineId] - Failed to find a usable hardware address from the network interfaces; using random bytes: e1:2b:2f:38:b2:02:67:c4 chrome_1 | 21:02:36.783 INFO [NodeOptions.report] - Adding chrome for {&quot;browserVersion&quot;: &quot;94.0&quot;,&quot;browserName&quot;: &quot;chrome&quot;,&quot;platformName&quot;: &quot;Linux&quot;,&quot;se:vncEnabled&quot;: true} 1 times selenium-distributor | 21:02:45.369 INFO [DistributorServer.execute] - Started Selenium Distributor 4.0.0 (revision 3a21814679): http://d8e53d166441:5553 chrome_1 | 21:02:46.857 INFO [Node.&lt;init&gt;] - Binding additional locator mechanisms: id, name, relative selenium-distributor | /opt/bin/start-selenium-grid-distributor.sh: line 66: 24 Killed java ${JAVA_OPTS} -jar /opt/selenium/selenium-server.jar distributor --sessions-host &quot;${SE_SESSIONS_MAP_HOST}&quot; --sessions-port &quot;${SE_SESSIONS_MAP_PORT}&quot; --sessionqueue-host &quot;${SE_SESSION_QUEUE_HOST}&quot; --sessionqueue-port &quot;${SE_SESSION_QUEUE_PORT}&quot; --publish-events tcp://&quot;${SE_EVENT_BUS_HOST}&quot;:&quot;${SE_EVENT_BUS_PUBLISH_PORT}&quot; --subscribe-events tcp://&quot;${SE_EVENT_BUS_HOST}&quot;:&quot;${SE_EVENT_BUS_SUBSCRIBE_PORT}&quot; --bind-bus false ${HOST_CONFIG} ${PORT_CONFIG} ${SE_OPTS} selenium-distributor | 2021-10-18 21:02:50,661 INFO exited: selenium-grid-distributor (exit status 137; not expected) chrome_1 | 21:02:51.371 INFO [BaseServerOptions.lambda$getExternalUri$0] - No network connection, guessing name: 8646325b6e37 chrome_1 | 21:02:51.513 WARN [MacAddressUtil.defaultMachineId] - Failed to find a usable hardware address from the network interfaces; using random bytes: 9f:65:82:c3:22:f7:b7:d4 chrome_1 | 21:02:51.757 INFO [NodeServer$1.start] - Starting registration process for node id adb8ff56-c40d-4d5b-8298-01df3135a951 selenium-router | 21:02:51.758 INFO [BaseServerOptions.lambda$getExternalUri$0] - No network connection, guessing name: 8885bd19bf09 chrome_1 | 21:02:51.769 INFO [NodeServer.execute] - Started Selenium node 4.0.0 (revision 3a21814679): http://8646325b6e37:5555 chrome_1 | 21:02:51.797 INFO [NodeServer$1.lambda$start$1] - Sending registration event... selenium-router | 21:02:52.642 WARN [MacAddressUtil.defaultMachineId] - Failed to find a usable hardware address from the network interfaces; using random bytes: 74:60:3b:79:d9:3b:52:1e selenium-router | 21:02:52.800 INFO [RouterServer.execute] - Started Selenium Router 4.0.0 (revision 3a21814679): http://8885bd19bf09:4444 chrome_1 | 21:03:01.893 INFO [NodeServer$1.lambda$start$1] - Sending registration event... chrome_1 | 21:03:11.927 INFO [NodeServer$1.lambda$start$1] - Sending registration event... </code></pre> <p><strong>Complete error logs while running one test:</strong></p> <pre><code> org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure. Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03' System info: host: 'Dhamo-Mac.local', ip: 'fe80:0:0:0:84c:43e7:38de:c02b%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '11.6', java.version: '11.0.12' Driver info: driver.version: RemoteWebDriver at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:573) at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213) at org.openqa.selenium.remote.RemoteWebDriver.&lt;init&gt;(RemoteWebDriver.java:131) at org.openqa.selenium.remote.RemoteWebDriver.&lt;init&gt;(RemoteWebDriver.java:144) at core.DriverManager.createRemoteDriver(DriverManager.java:82) at core.DriverManager.createDriver(DriverManager.java:44) at core.DriverManager.getDriver(DriverManager.java:34) at core.CoreBase.&lt;init&gt;(CoreBase.java:10) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) at org.picocontainer.injectors.AbstractInjector.newInstance(AbstractInjector.java:145) at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:342) at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270) at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364) at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56) at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64) at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91) at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699) at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647) at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632) at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118) at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136) at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78) at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309) at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335) at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270) at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364) at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56) at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64) at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91) at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699) at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647) at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678) at io.cucumber.picocontainer.PicoFactory.getInstance(PicoFactory.java:49) at io.cucumber.java.AbstractGlueDefinition.invokeMethod(AbstractGlueDefinition.java:47) at io.cucumber.java.JavaHookDefinition.execute(JavaHookDefinition.java:59) at io.cucumber.core.runner.CoreHookDefinition.execute(CoreHookDefinition.java:46) at io.cucumber.core.runner.HookDefinitionMatch.runStep(HookDefinitionMatch.java:21) at io.cucumber.core.runner.ExecutionMode$1.execute(ExecutionMode.java:10) at io.cucumber.core.runner.TestStep.executeStep(TestStep.java:92) at io.cucumber.core.runner.TestStep.run(TestStep.java:64) at io.cucumber.core.runner.TestCase.run(TestCase.java:110) at io.cucumber.core.runner.Runner.runPickle(Runner.java:73) at io.cucumber.testng.TestNGCucumberRunner.lambda$runScenario$0(TestNGCucumberRunner.java:117) at io.cucumber.core.runtime.CucumberExecutionContext.runTestCase(CucumberExecutionContext.java:117) at io.cucumber.testng.TestNGCucumberRunner.runScenario(TestNGCucumberRunner.java:114) at io.cucumber.testng.AbstractTestNGCucumberTests.runScenario(AbstractTestNGCucumberTests.java:31) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133) at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:598) at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173) at org.testng.internal.TestMethodWithDataProviderMethodWorker.call(TestMethodWithDataProviderMethodWorker.java:77) at org.testng.internal.TestMethodWithDataProviderMethodWorker.call(TestMethodWithDataProviderMethodWorker.java:15) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:829) Caused by: java.io.IOException: unexpected end of stream on Connection{localhost:4444, proxy=DIRECT hostAddress=localhost/0:0:0:0:0:0:0:1:4444 cipherSuite=none protocol=http/1.1} at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:208) at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) at org.openqa.selenium.remote.internal.OkHttpClient$Factory$1.lambda$createClient$1(OkHttpClient.java:152) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200) at okhttp3.RealCall.execute(RealCall.java:77) at org.openqa.selenium.remote.internal.OkHttpClient.execute(OkHttpClient.java:103) at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:105) at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:74) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552) ... 63 more Caused by: java.io.EOFException: \n not found: limit=0 content=… at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:237) at okhttp3.internal.http1.Http1Codec.readHeaderLine(Http1Codec.java:215) at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:189) ... 86 more </code></pre> <p>Alternatively, when I try to open the hub url, I get the following: <a href="https://i.stack.imgur.com/4OWDx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4OWDx.png" alt="enter image description here" /></a></p> <p>It's how the remote driver object gets called.</p> <pre><code>case CHROME: ChromeOptions options = getChromeOptions(); try { driver = new RemoteWebDriver(new URL(&quot;http://localhost:4444&quot;), options); } catch (MalformedURLException e) { e.printStackTrace(); } </code></pre> <p>Laptop config: Mac m1 512GB</p> <p>How can I possibly get rid of the issue?</p>
1
10,678
.Net Core 3.1 Using Serilog with Microsoft.Extensions.Logger
<p>In this application I've pulled in and setup Serilog, which works for exceptions, and I wanted to use the Microsoft's Logger with Serilog, but I can't seem to figure out how to DI it into services without this error during <code>dotnet build</code>.</p> <p>I'm not sure what I'm missing to have ILogger be using an instance of Serilog?</p> <p><strong>Error on <code>dotnet build</code>:</strong></p> <pre><code>[13:56:21 FTL] Host terminated unexpectedly System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'App.Services.MyService'.) </code></pre> <p><strong>Dependency Injection into Service:</strong></p> <pre class="lang-cs prettyprint-override"><code>using Microsoft.Extensions.Logging; public class MyService : BaseService { private readonly ILogger _logger; public MyService( ILogger logger) : base(context, httpContext) { _logger = logger; } // ... Removed for brevity } </code></pre> <p>Implementation</p> <pre class="lang-cs prettyprint-override"><code>public static int Main(string[] args) { CreateLogger(); try { Log.Information(&quot;Starting web host&quot;); CreateHostBuilder(args) .Build() .Run(); return 0; } catch (Exception ex) { Log.Fatal(ex, &quot;Host terminated unexpectedly&quot;); return 1; } finally { // Ensure buffered logs are written to their target sink Log.CloseAndFlush(); } } public static IHostBuilder CreateHostBuilder(string[] args) =&gt; Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder =&gt; webBuilder.UseStartup&lt;Startup&gt;()) .UseSerilog(); private static void CreateLogger() { string path = PrimeConstants.LOG_FILE_PATH; try { if (isDevelopment()) { Directory.CreateDirectory(path); } } catch (Exception e) { Console.WriteLine(&quot;Creating the logging directory failed: {0}&quot;, e.ToString()); } var name = Assembly.GetExecutingAssembly().GetName(); var outputTemplate = &quot;[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}&quot;; Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .MinimumLevel.Override(&quot;Microsoft&quot;, LogEventLevel.Warning) .MinimumLevel.Override(&quot;Microsoft.Hosting.Lifetime&quot;, LogEventLevel.Information) .MinimumLevel.Override(&quot;System&quot;, LogEventLevel.Warning) .Enrich.FromLogContext() .Enrich.WithMachineName() .Enrich.WithProperty(&quot;Assembly&quot;, $&quot;{name.Name}&quot;) .Enrich.WithProperty(&quot;Version&quot;, $&quot;{name.Version}&quot;) .WriteTo.Console( outputTemplate: outputTemplate, theme: AnsiConsoleTheme.Code) .WriteTo.Async(a =&gt; a.File( $@&quot;{path}/prime.log&quot;, outputTemplate: outputTemplate, rollingInterval: RollingInterval.Day, shared: true)) .WriteTo.Async(a =&gt; a.File( new JsonFormatter(), $@&quot;{path}/prime.json&quot;, rollingInterval: RollingInterval.Day)) .CreateLogger(); } </code></pre>
1
1,415
ListView Binding array of objects access variables
<p><strong>EDIT</strong><br> Turns out the problem was with getting the enclosure it was throwing an error casting MtObject to Enclosure that wasn't being detected by the debugger.<br> Marked Andy's solution as correct as it is, and it helped me to see the problem was not in the ListView code, thank you andy </p> <p>So i have been searching around and don't seem to be able to find the right answer.<br> Basically i have a ListView which i have bound to an array of Animals and one animal has a property of another object Enclosure, and im trying to bind the enclosure name like this </p> <pre><code>&lt;GridViewColumn Header="Enclosure" DisplayMemberBinding="{Binding Enclosure.Name}" /&gt; </code></pre> <p>this is clearly wrong but i think shows what I'm trying to achieve,<br> The basic layout is object.object. </p> <p>The full ListView below</p> <pre><code>&lt;ListView Margin="20,0,20,0" Grid.Row="1" ItemsSource="{Binding}" x:Name="displayResults" SelectionChanged="displayResults_SelectionChanged_1"&gt; &lt;ListView.ItemContainerStyle&gt; &lt;Style TargetType="ListViewItem"&gt; &lt;Setter Property="Height" Value="45" /&gt; &lt;/Style&gt; &lt;/ListView.ItemContainerStyle&gt; &lt;ListView.View&gt; &lt;GridView x:Name="gridView"&gt; &lt;GridViewColumn Header="Photo" CellTemplate="{StaticResource PhotoTemplate}"/&gt; &lt;GridViewColumn Header="Name" DisplayMemberBinding="{Binding GivenName}" /&gt; &lt;GridViewColumn DisplayMemberBinding="{Binding Path=Enclosure.Id}" Header="Enclosure"/&gt; &lt;GridViewColumn Header="Species" DisplayMemberBinding="{Binding SpeciesName}" /&gt; &lt;GridViewColumn Header="DOB" DisplayMemberBinding="{Binding Dob}" /&gt; &lt;GridViewColumn Header="Average Life Span" DisplayMemberBinding="{Binding AverageLifeSpan}" /&gt; &lt;GridViewColumn Header="Natural Habitat" DisplayMemberBinding="{Binding NaturalHabitat}" /&gt; &lt;/GridView&gt; &lt;/ListView.View&gt; &lt;/ListView&gt; </code></pre> <p>How the enclosure get/set</p> <pre><code>public Enclosure Enclosure { get { return ((Enclosure)(GetSuccessor(GetEnclosureRelationship(Database)))); } set { SetSuccessor(GetEnclosureRelationship(Database), value); } } </code></pre>
1
1,235
Cordova : writing in a file
<p>There is something i've been stuck for quite some time, despite me searching on numerous forums. I'm sorry if my english is not perfect, I hope I'm clear enough for you to be able to understand me and help me get through this.</p> <p>I'm trying to learn some mobile development with Cordova. I want to create an application instagram-like, in which memories will be stored. The application uses two pages : - a page displaying all stored memories ; - a page adding a memory. Memories are stored in a local json file.</p> <p>Here is my code (for now) : <em>note : the code has been translated for better comprehension. I hope I didn"t make any translation error, unrelated to the topic at hand</em></p> <p><strong>addMemory.html (view to add a memory)</strong></p> <pre><code>&lt;form role="form" class="col-xs-12"&gt; &lt;div class="form-group"&gt; &lt;label for="title"&gt;Title :&lt;/label&gt; &lt;input type="text" id="title" class="form-control" ng-model="souvenir.title" placeholder="Add a memory title" /&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="image"&gt;Image :&lt;/label&gt; &lt;button id="image" class="form-control btn btn-default"&gt;Add...&lt;/button&gt; &lt;/div&gt; &lt;button class="btn btn-default" ng-click="createMemory()"&gt;Create&lt;/button&gt; &lt;/form&gt; </code></pre> <p><strong>addMemoryController.js</strong> <em>(add a memory. For now, a memory is a static json stored in a local file. Dynamic control will be added later on)</em></p> <pre><code>app.controller("addMemoryController", function ($scope, $location) { //Array of all stored memories $scope.memoriesList = []; //New memory to add (for now static) $scope.memory = { image: "image/moutain.png", title:"" } //The function pushes the new memory into the list then save the array $scope.createMemory = function () { $scope.memoriesList.push($scope.memory); $scope.saveArray(); } //The function save the array into the local file $scope.saveArray = function () { window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; var requestedBytes = 1024*1024*10; // 10MB navigator.webkitPersistentStorage.requestQuota ( requestedBytes, function (grantedBytes) { window.requestFileSystem(PERSISTENT, grantedBytes, $scope.fileSystemReceived, $scope.errorHandler('requestFileSystem')); }, $scope.errorHandler ); $location.path("/"); } //Function called when the fileSystem is received $scope.fileSystemReceived = function (fileSystem) { fileSystem.root.getFile("memories.json", { create: true, exclusive: false }, $scope.fileEntryReceived, $scope.errorHandler('getFile')); } //Function called when the fileEntry is received $scope.fileEntryReceived = function (fileEntry) { fileEntry.createWriter($scope.fileWriterReceived, $scope.errorHandler('createWriter')); } //Function called when the fileWriter is received $scope.fileWriterReceived = function (fileWriter) { fileWriter.onwrite = function (evt) { console.log("write success"); }; var memoriesListText = angular.toJson($scope.memoriesList); fileWriter.write(memoriesListText); } //Error managment $scope.errorHandler = function (errorMessage) { return function () { console.log(errorMessage); }; } }); </code></pre> <p>When I launch my application, I get an error with the "write" function : <em>TypeMismatchError: The type of an object was incompatible with the expected type of the parameter associated to the object.</em></p> <p>I tried to write a simple text content without any difference :</p> <pre><code>fileWriter.write("some text"); </code></pre> <p>I even tried to create a ".txt" file, logically without any difference. </p> <p>What am I supposed to give as parameter if not a text ? I can't file a doc describing this function type signature.</p>
1
1,350
Memory corrupt in adding string to vector<string> loop
<p>This is on Visual Studio 2008 on a dual-core, 32 bit Vista machine. In the debug code this runs fine, but in Release mode this bombs:</p> <pre><code>void getFromDB(vector&lt;string&gt;&amp; dates) { ... sql::Resultset res = stmt-&gt;executeQuery("SELECT FROM ..."); while (res-&gt;next()) { string date = res-&gt;getString("date"); dates.push_back(date); } // &lt;&lt;&lt; crashing here (line 56) delete res; } </code></pre> <p>The MySQL C++ connector has this method in it's ResultSet:</p> <pre><code>virtual std::string getString(const std::string&amp; columnLabel) const = 0; </code></pre> <p>For some reason in the release compiled (against a MySQL C++ connector DLL) this crashes at the end of the loop with a heap corruption:</p> <blockquote> <p>HEAP[sa-ms-release.exe]: Invalid address specified to RtlFreeHeap( 024E0000, 001C4280 ) Windows has triggered a breakpoint in sa-ms-release.exe.</p> </blockquote> <pre><code> ntdll.dll!_RtlpBreakPointHeap@4() + 0x28 bytes ntdll.dll!_RtlpValidateHeapEntry@12() + 0x713e8 bytes ntdll.dll!_RtlDebugFreeHeap@12() + 0x9a bytes ntdll.dll!@RtlpFreeHeap@16() + 0x145cf bytes ntdll.dll!_RtlFreeHeap@12() + 0xed5 bytes kernel32.dll!_HeapFree@12() + 0x14 bytes &gt; sa-ms-release.exe!free(void * pBlock=0x001c4280) Line 110 C sa-ms-release.exe!std::allocator&lt;char&gt;::deallocate(char * _Ptr=0x001c4280, unsigned int __formal=32) Line 140 + 0x9 bytes C++ sa-ms-release.exe!std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt;::_Tidy(bool _Built=true, unsigned int _Newsize=0) Line 2158 C++ sa-ms-release.exe!std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt;::~basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt;() Line 907 C++ sa-ms-release.exe!StyleData:: getFromDB( std::vector&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt;,std::allocator&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; &gt; &gt; &amp; dates) Line 56 + 0x69 bytes C++ </code></pre> <p>I think I may be violating some basic C++ rule that causes the destructor to be called on a string I want to preserve inside the vector.</p> <p>If I replace</p> <pre><code>string date = res-&gt;getString("date") </code></pre> <p>with </p> <pre><code>string date = string ("2008-11-23"); </code></pre> <p>everything works fine. It seems to have to do with the string returned from the MySQL C++ Connector getString() method. The returned string is destroyed and that causes the problem, I guess. But more likely something else is wrong. I am using the release (opt) MySQL connector.</p>
1
1,108
Android: Unable to instantiate activity ComponentInfo
<p>I'm getting the following error and I don't no what to do. I cleared my projects 100 times, removed all JARs from the buildpath, deleted bin and gen.....but nothing worked for me.<br> Please find below the error code:</p> <pre><code>09-03 19:43:17.326: E/Trace(800): error opening trace file: No such file or directory (2) 09-03 19:43:17.546: D/AndroidRuntime(800): Shutting down VM 09-03 19:43:17.597: W/dalvikvm(800): threadid=1: thread exiting with uncaught exception (group=0x40a71930) 09-03 19:43:17.629: E/AndroidRuntime(800): FATAL EXCEPTION: main 09-03 19:43:17.629: E/AndroidRuntime(800): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.firsttravel/com.example.firsttravel.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.firsttravel.MainActivity" on path: /data/app/com.example.firsttravel-2.apk 09-03 19:43:17.629: E/AndroidRuntime(800): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106) 09-03 19:43:17.629: E/AndroidRuntime(800): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 09-03 19:43:17.629: E/AndroidRuntime(800): at android.app.ActivityThread.access$600(ActivityThread.java:141) 09-03 19:43:17.629: E/AndroidRuntime(800): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 09-03 19:43:17.629: E/AndroidRuntime(800): at android.os.Handler.dispatchMessage(Handler.java:99) 09-03 19:43:17.629: E/AndroidRuntime(800): at android.os.Looper.loop(Looper.java:137) 09-03 19:43:17.629: E/AndroidRuntime(800): at android.app.ActivityThread.main(ActivityThread.java:5041) 09-03 19:43:17.629: E/AndroidRuntime(800): at java.lang.reflect.Method.invokeNative(Native Method) 09-03 19:43:17.629: E/AndroidRuntime(800): at java.lang.reflect.Method.invoke(Method.java:511) 09-03 19:43:17.629: E/AndroidRuntime(800): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 09-03 19:43:17.629: E/AndroidRuntime(800): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 09-03 19:43:17.629: E/AndroidRuntime(800): at dalvik.system.NativeStart.main(Native Method) 09-03 19:43:17.629: E/AndroidRuntime(800): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.firsttravel.MainActivity" on path: /data/app/com.example.firsttravel-2.apk 09-03 19:43:17.629: E/AndroidRuntime(800): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65) 09-03 19:43:17.629: E/AndroidRuntime(800): at java.lang.ClassLoader.loadClass(ClassLoader.java:501) 09-03 19:43:17.629: E/AndroidRuntime(800): at java.lang.ClassLoader.loadClass(ClassLoader.java:461) 09-03 19:43:17.629: E/AndroidRuntime(800): at android.app.Instrumentation.newActivity(Instrumentation.java:1054) 09-03 19:43:17.629: E/AndroidRuntime(800): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097) 09-03 19:43:17.629: E/AndroidRuntime(800): ... 11 more 09-03 19:43:54.849: I/Process(800): Sending signal. PID: 800 SIG: 9` </code></pre> <p>Do you guys have any idea what is wrong?</p> <p>Thank you very much.</p>
1
1,125
How to switch between DatabaseGeneratedOption.Identity, Computed and None at runtime without having to generate empty DbMigrations
<p>I am migrating a legacy database to a new database which we need to access and "manage" (as oxymoronic as it might sound) primarily through Entity Framework Code-First.</p> <p>We are using MS SQL Server 2014.</p> <ol> <li><p>The legacy database contained some tables with <strong>computed</strong> columns. <strong>Typical GUID and DateTime stuff.</strong></p></li> <li><p>Technically speaking, these columns did not have a computed column specification, but rather where given a default value with <code>NEWID()</code> and <code>GETDATE()</code></p></li> </ol> <p>We all know that it is very easy to configure the <code>DbContext</code> to deal with those properties as follows:</p> <pre><code>modelBuilder.Entity&lt;Foo&gt;() .Property(t =&gt; t.Guid) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed); modelBuilder.Entity&lt;Bar&gt;() .Property(t =&gt; t.DTS) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed); </code></pre> <p>The above would instruct the Entity Framework to ignore submitting any supplied values for such properties during <code>INSERTs</code> and <code>UPDATEs</code>.</p> <ol> <li><p>But now <strong>we need to allow for import of legacy records and maintain the OLD values</strong>, including the <strong>PRIMARY KEY</strong>, which is marked as <code>IDENTITY</code> </p> <ol> <li><p>This means we would have to set the <code>Id</code>, <code>Guid</code> and <code>DTS</code> properties to <code>DatabaseGeneratedOption.None</code> while inserting those records.</p></li> <li><p>For the case of <code>Id</code>, we would have to somehow execute <code>SET IDENTITY_INSERT ... ON/OFF</code> within the connection session.</p></li> <li><p><strong>And we want to do this importing process via Code-First as well.</strong></p></li> </ol></li> <li><p>If I modify the model and "temporarily" and set those properties to <code>DatabaseGeneratedOption.None</code> after the database has been created, we would get the typical:</p> <p><em>The model backing the context has changed since the database was created. Consider using Code First Migrations to update the database</em>.</p></li> <li><p>I understand that we could generate an empty coded-migration with <code>-IgnoreChanges</code> so as to "establish" this latest version of the context, but this wouldn't be an acceptable strategy as we would have to be run empty migrations back-and-forth solely for this purpose.</p></li> </ol> <hr> <h3>Half an answer:</h3> <p>We have considered giving these properties nullable types, i.e.</p> <pre><code>public class Foo { ... public Guid? Guid { get; set; } } public class Bar { ... public DateTime? DTS { get; set; } } </code></pre> <p>While caring about the default values in an initial <code>DbMigration</code>:</p> <pre><code>CreateTable( "dbo.Foos", c =&gt; new { Id = c.Int(nullable: false, identity: true), Guid = c.Guid(nullable: false, defaultValueSql: "NEWID()"), }) .PrimaryKey(t =&gt; t.Id); CreateTable( "dbo.Bars", c =&gt; new { Id = c.Int(nullable: false, identity: true), DTS = c.Guid(nullable: false, defaultValueSql: "GETDATE()"), }) .PrimaryKey(t =&gt; t.Id); </code></pre> <hr> <h2>The Question:</h2> <p>But the question remains: Is there a way to switch between <code>DatabaseGeneratedOption.Identity</code>, <code>DatabaseGeneratedOption.Computed</code> and <code>DatabaseGeneratedOption.None</code> at runtime?</p> <p>At the very least, how could we turn <code>DatabaseGeneratedOption.Identity</code> on/off at runtime?</p>
1
1,298
It is not working on data-parsley-mincheck="2" with Parsley.js-2.0.0-rc4
<p>When I check my form, it show 'Y' in console. But I did not select any checkbox.<br/> In official document, it say:</p> <blockquote> <p>checkbox need to have either a name or an id attribute to be correctly binded and validated by Parsley. Otherwise, they would be ignored and a warning will be put in the console.</p> </blockquote> <p>I had set 'name' attribute in input tag and parsley also did not show:</p> <blockquote> <p>To be binded by Parsley, a radio, a checkbox and a multiple select input must have either a name, and id or a multiple option.</p> </blockquote> <p>But it still not work on data-parsley-mincheck="2". <br/><br/> In other situation, the same code is work on parsley-mincheck="2" with parsly version 1.2.3.<br/><br/> So, if I have any mistake with the official document (parsly 2.0.0-rc4).</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Test&lt;/title&gt; &lt;script src="jquery-1.11.0.min.js"&gt;&lt;/script&gt; &lt;script src="parsley.min.js"&gt;&lt;/script&gt; &lt;script&gt; function checkMyForm(myform) { if($(myform).parsley().validate()) { console.info('Y'); } else { console.error('N'); } } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form name="myform" action="" method="post" novalidate onsubmit="return false;"&gt; &lt;div&gt; &lt;input name="mybox" type="checkbox" value="1" data-parsley-multiple="mytest" data-parsley-mincheck="2" /&gt;&amp;nbsp;Value-1&amp;nbsp;&amp;nbsp; &lt;input name="mybox" type="checkbox" value="2" data-parsley-multiple="mytest"/&gt;&amp;nbsp;Value-2&amp;nbsp;&amp;nbsp; &lt;input name="mybox" type="checkbox" value="3" data-parsley-multiple="mytest"/&gt;&amp;nbsp;Value-3&amp;nbsp;&amp;nbsp; &lt;input name="mybox" type="checkbox" value="4" data-parsley-multiple="mytest"/&gt;&amp;nbsp;Value-4&amp;nbsp;&amp;nbsp; &lt;input name="mybox" type="checkbox" value="5" data-parsley-multiple="mytest"/&gt;&amp;nbsp;Value-5&amp;nbsp;&amp;nbsp; &lt;/div&gt; &lt;!-- &lt;div style="padding: 10px 0px;"&gt; &lt;input name="mytext" type="text" data-parsley-required="true"/&gt; &lt;/div&gt; --&gt; &lt;a href="javascript: checkMyForm(document.myform);"&gt;Test Checkbox&lt;/a&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I find some similar question about it:<br/> <a href="https://stackoverflow.com/questions/22085202/how-can-i-get-parsley-js-to-oupt-1-error-for-a-group-of-radio-buttons-or-checkbo">How can I get Parsley.js to oupt 1 error for a group of radio buttons or checkboxes?</a></p> <p>I try to change my data-parsley-mincheck="2" to the last checkbox and add required attribute.<br/> When I check my form again, it also return 'Y' (But I did not select any checkbox).<br/> Thus, it is not the key point on the problem.</p>
1
1,487
C# abstract base class for common columns in LINQ
<p>This is what I have so far</p> <pre><code>using System; using System.Collections.Generic; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Linq; using System.Text; namespace Firelight.Business { public interface IBaseEntity&lt;K&gt; { K Id { get; } } /// &lt;summary&gt; /// Base business database connection object, primary key is int /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Table name&lt;/typeparam&gt; public abstract class BaseEntity&lt;T&gt; : BaseEntity&lt;T, Guid&gt; where T : class, IBaseEntity&lt;Guid&gt; { } /// &lt;summary&gt; /// Base business database connection object /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Table name&lt;/typeparam&gt; /// &lt;typeparam name="K"&gt;Primary key type&lt;/typeparam&gt; public abstract class BaseEntity&lt;T,K&gt; : IBaseEntity&lt;K&gt; where T : class, IBaseEntity&lt;K&gt; { // Avoids having to declare IBaseConnection at partial class level [Column(Name = "Id", CanBeNull = false, IsPrimaryKey = true, IsDbGenerated = true)] public K Id { get; set; } // { return default(K); } public static Table&lt;T&gt; Table { get { return LinqUtil.Context.GetTable&lt;T&gt;(); } } public static T SearchById(K id) { return Table.Single&lt;T&gt;(t =&gt; t.Id.Equals(id)); } public static void DeleteById(K id) { Table.DeleteOnSubmit(SearchById(id)); LinqUtil.Context.SubmitChanges(); } } } </code></pre> <p>My problem is that mapping doesn't work:</p> <blockquote> <p>Data member 'System.Guid [or System.Int32] Id' of type 'X' is not part of the mapping for type 'X'. Is the member above the root of an inheritance hierarchy?</p> </blockquote> <p>Before trying to map the attributes, I got this instead:</p> <blockquote> <p>Could not find key member 'Id' of key 'Id' on type 'X'. The key may be wrong or the field or property on 'X' has changed names.</p> </blockquote> <p>I tried changing K to Guid and it works, but why? I don't see how generic-typing is an issue here</p> <p>I'm not entirely sure that I actually needed the Interface either, I don't really remember why I added it.</p> <p>So, the question would be: How can I make a class like this work? I want it so I can access a commonly named PK (Id), which always has the type K [which is Guid or Int32], and refactor basic functions like select and delete by Id</p> <p>Thanks!</p> <p>EDIT:</p> <p>this works</p> <pre><code>using System; using System.Collections.Generic; using System.Data.Linq; using System.Linq; namespace Firelight.Business { public interface IBaseEntity&lt;K&gt; { K Id { get; set; } } /// &lt;summary&gt; /// Base business database connection object /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Table name&lt;/typeparam&gt; public abstract class BaseEntity&lt;T&gt; : IBaseEntity&lt;Guid&gt; where T : class, IBaseEntity&lt;Guid&gt; { // Avoids having to declare IBaseConnection at partial class level public Guid Id { get; set; } public static Table&lt;T&gt; Table { get { return LinqUtil.Context.GetTable&lt;T&gt;(); } } public static T SearchById(Guid id) { return Table.Single&lt;T&gt;(t =&gt; t.Id.Equals(id)); } public static void DeleteById(Guid id) { Table.DeleteOnSubmit(SearchById(id)); LinqUtil.Context.SubmitChanges(); } } } </code></pre> <p>What I want would be basically the same, replacing Guid with K and making the class BaseEntity (so I can use the same class for Int32 and Guid PKs</p>
1
1,553
AvroTypeException: Not an enum: MOBILE on DataFileWriter
<p>I am getting the following error message when I tried to write avro records using build-in <code>AvroKeyValueSinkWriter</code> in Flink 1.3.2 and avro 1.8.2:</p> <p>My schema looks like this:</p> <pre><code>{"namespace": "com.base.avro", "type": "record", "name": "Customer", "doc": "v6", "fields": [ {"name": "CustomerID", "type": "string"}, {"name": "platformAgent", "type": { "type": "enum", "name": "PlatformAgent", "symbols": ["WEB", "MOBILE", "UNKNOWN"] }, "default":"UNKNOWN"} ] } </code></pre> <p>And I am calling the following Flink code to write data:</p> <pre><code> var properties = new util.HashMap[String, String]() val stringSchema = Schema.create(Type.STRING) val myTypeSchema = Customer.getClassSchema val keySchema = stringSchema.toString val valueSchema = myTypeSchema.toString val compress = true properties.put(AvroKeyValueSinkWriter.CONF_OUTPUT_KEY_SCHEMA, keySchema) properties.put(AvroKeyValueSinkWriter.CONF_OUTPUT_VALUE_SCHEMA, valueSchema) properties.put(AvroKeyValueSinkWriter.CONF_COMPRESS, compress.toString) properties.put(AvroKeyValueSinkWriter.CONF_COMPRESS_CODEC, DataFileConstants.SNAPPY_CODEC) val sink = new BucketingSink[org.apache.flink.api.java.tuple.Tuple2[String, Customer]]("s3://test/flink") sink.setBucketer(new DateTimeBucketer("yyyy-MM-dd/HH/mm/")) sink.setInactiveBucketThreshold(120000) // this is 2 minutes sink.setBatchSize(1024 * 1024 * 64) // this is 64 MB, sink.setPendingSuffix(".avro") val writer = new AvroKeyValueSinkWriter[String, Customer](properties) sink.setWriter(writer.duplicate()) </code></pre> <p>However, it throws the following errors:</p> <pre><code>Caused by: org.apache.avro.AvroTypeException: Not an enum: MOBILE at org.apache.avro.generic.GenericDatumWriter.writeEnum(GenericDatumWriter.java:177) at org.apache.avro.generic.GenericDatumWriter.writeWithoutConversion(GenericDatumWriter.java:119) at org.apache.avro.generic.GenericDatumWriter.write(GenericDatumWriter.java:75) at org.apache.avro.generic.GenericDatumWriter.writeField(GenericDatumWriter.java:166) at org.apache.avro.generic.GenericDatumWriter.writeRecord(GenericDatumWriter.java:156) at org.apache.avro.generic.GenericDatumWriter.writeWithoutConversion(GenericDatumWriter.java:118) at org.apache.avro.generic.GenericDatumWriter.write(GenericDatumWriter.java:75) at org.apache.avro.generic.GenericDatumWriter.writeField(GenericDatumWriter.java:166) at org.apache.avro.generic.GenericDatumWriter.writeRecord(GenericDatumWriter.java:156) at org.apache.avro.generic.GenericDatumWriter.writeWithoutConversion(GenericDatumWriter.java:118) at org.apache.avro.generic.GenericDatumWriter.write(GenericDatumWriter.java:75) at org.apache.avro.generic.GenericDatumWriter.write(GenericDatumWriter.java:62) at org.apache.avro.file.DataFileWriter.append(DataFileWriter.java:302) ... 10 more </code></pre> <p>Please suggest!</p> <p><strong>UPDATE 1:</strong> I found this is kind of bug in avro 1.8+ based on this ticket: <a href="https://issues-test.apache.org/jira/browse/AVRO-1810" rel="nofollow noreferrer">https://issues-test.apache.org/jira/browse/AVRO-1810</a></p>
1
1,240
Apache Camel - response after sending a message to a route
<p><br> I'm using <code>Apache Camel</code> and <code>Spring Boot</code> for my project. I have the following code where I receive a <code>json object</code> via <code>http</code> on the <code>rtos</code> endpoint; then I map it into a <code>POJO</code>, modify it and send it again to another endpoint.</p> <pre><code>restConfiguration().component("servlet").host("localhost").port("8080").bindingMode(RestBindingMode.auto); rest("/request").post("/rtos").type(User.class).to("direct:rtos") from("direct:rtos").process(new Processor() { public void process(Exchange exchange) throws Exception { User body = exchange.getIn().getBody(User.class); System.out.println("Input object: " + body.getName() + ", " + body.getAge()); body.setAge("35"); System.out.println("Output object: " + body.getName() + ", " + body.getAge()); } }).marshal().json(JsonLibrary.Jackson) .to("http4://localhost:8080/receive?bridgeEndpoint=true"); from("servlet:/receive").unmarshal().json(JsonLibrary.Jackson, User.class).process(new Processor() { @Override public void process(Exchange exchange) throws Exception { User body = exchange.getIn().getBody(User.class); body.setAge("100"); System.out.println("Received object: " + body.getName() + ", " + body.getAge()); } }); </code></pre> <p>This works okay, meaning that the object is correctly manipulated and passed through the endpoints. What happens is that after sending the http request I get <code>500 Internal Server Error</code> and the following error: <br></p> <pre><code>com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.apache.camel.converter.stream.CachedOutputStream$WrappedInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) </code></pre> <p>I noticed that the error disappears if I manage to return something to the first route, for example <br></p> <pre><code>[...] .to("http4://localhost:8080/receive?bridgeEndpoint=true").transform().constant("End of route"); </code></pre> <p>I wonder why is that, and what it has to do with jackson serialization. And what if I don't want to send a reply to the first request? I red <a href="http://camel.apache.org/request-reply.html" rel="nofollow">this</a> and <a href="http://camel.apache.org/event-message.html" rel="nofollow">this</a>, and I tried to modify my code as follows: <br></p> <pre><code>from("direct:rtos").setExchangePattern(ExchangePattern.InOnly).process(new Processor() { public void process(Exchange exchange) throws Exception { User body = exchange.getIn().getBody(User.class); System.out.println("Input object: " + body.getName() + ", " + body.getAge()); body.setAge("35"); System.out.println("Output object: " + body.getName() + ", " + body.getAge()); } }).marshal().json(JsonLibrary.Jackson) .inOnly("http4://localhost:8080/receive?bridgeEndpoint=true"); </code></pre> <p>but I get the same error.<br> Can anyone suggest me where I'm wrong? I'm trying to understand properly how the Camel flow works, so it's possible that I've made some mistakes somewhere.<br> Thanks,<br> Sara</p> <p><em>EDIT</em> this is my User class:</p> <pre><code>package it.cam.resources; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.StringSerializer; import java.io.Serializable; public class User implements Serializable{ @JsonProperty("id") private String id; @JsonProperty("name") private String name; @JsonProperty("age") private String age; @JsonSerialize(using=StringSerializer.class) public String getName() { return name; } public void setName(String name) { this.name = name; } @JsonSerialize(using=StringSerializer.class) public String getAge() { return age; } public void setAge(String age) { this.age = age; } } </code></pre>
1
1,482
Socket.io and Express with nginx
<p>I'm struggling to configure nginx correctly to ensure that it can handle the proxy for both Express (port 8081) and Socket.io (port 3000). Here is my config that is currently yielding a 502 error for the whole request, not just Socket.io:</p> <pre><code>server { root /var/www/example.com/public/; index index.html index.htm index.nginx-debian.html; server_name example.com; location /socket.io/ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://127.0.0.1:3000/; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location / { #try_files $uri $uri/ =404; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://127.0.0.1:8081/; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header X-Forwarded-Proto $scheme; } listen [::]:443 ssl; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80; server_name example.com; return 404; # managed by Certbot } </code></pre> <p>As far as I understand it, I need to ensure the Websocket used by Socket.io is upgraded to HTTP but this is where I'm struggling to grasp what I need to be doing. Presumably both Socket.io and Express need to be running on different ports and then need to proxy to nginx as per my configuration above.</p> <p>If I disable the Express proxy and just use nginx to serve up files then my assets are served but obviously I need this to work with both Express and Socket.io.</p> <p>Edit: I'm running nginx 1.14 but looking at a nginx blog post suggests I need at least 1.3...yet it looks a fair few years old already so not sure why the Ubuntu package manager is so outdated. I'm getting no configuration errors in but connection refused in error logs due to upstream.</p> <p>Any help much appreciated!</p>
1
1,248
Processing video library does not work on Linux (Ubuntu 13.04)
<p>I have a problem.</p> <p>I'm trying to run the <code>Mirror</code> sample from the Processing <code>video</code> library, with the latest version of Processing (2.0.3). However, I get this error;</p> <pre><code>Fontconfig warning: "/etc/fonts/conf.d/50-user.conf", line 14: reading configurations from ~/.fonts.conf is deprecated. libEGL warning: failed to create a pipe screen for i965 java.lang.RuntimeException: java.lang.UnsatisfiedLinkError: Unable to load library 'gstreamer-0.10': libgstreamer-0.10.so: cannot open shared object file: No such file or directory at com.jogamp.common.util.awt.AWTEDTExecutor.invoke(AWTEDTExecutor.java:58) at jogamp.opengl.awt.AWTThreadingPlugin.invokeOnOpenGLThread(AWTThreadingPlugin.java:100) at jogamp.opengl.ThreadingImpl.invokeOnOpenGLThread(ThreadingImpl.java:205) at javax.media.opengl.Threading.invokeOnOpenGLThread(Threading.java:172) at javax.media.opengl.Threading.invoke(Threading.java:191) at javax.media.opengl.awt.GLCanvas.display(GLCanvas.java:483) at processing.opengl.PGL.requestDraw(PGL.java:1149) at processing.opengl.PGraphicsOpenGL.requestDraw(PGraphicsOpenGL.java:1604) at processing.core.PApplet.run(PApplet.java:2176) at java.lang.Thread.run(Thread.java:662) Caused by: java.lang.UnsatisfiedLinkError: Unable to load library 'gstreamer-0.10': libgstreamer-0.10.so: cannot open shared object file: No such file or directory at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:163) at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:236) at com.sun.jna.Library$Handler.&lt;init&gt;(Library.java:140) at com.sun.jna.Native.loadLibrary(Native.java:379) at org.gstreamer.lowlevel.GNative.loadNativeLibrary(Unknown Source) at org.gstreamer.lowlevel.GNative.loadLibrary(Unknown Source) at org.gstreamer.lowlevel.GstNative.load(GstNative.java:42) at org.gstreamer.lowlevel.GstNative.load(GstNative.java:39) at org.gstreamer.Gst.&lt;clinit&gt;(Gst.java:59) at processing.video.Video.initImpl(Unknown Source) at processing.video.Video.init(Unknown Source) at processing.video.Capture.initGStreamer(Unknown Source) at processing.video.Capture.&lt;init&gt;(Unknown Source) at testvideo.setup(testvideo.java:46) at processing.core.PApplet.handleDraw(PApplet.java:2280) at processing.opengl.PGL$PGLListener.display(PGL.java:2601) at jogamp.opengl.GLDrawableHelper.displayImpl(GLDrawableHelper.java:588) at jogamp.opengl.GLDrawableHelper.display(GLDrawableHelper.java:572) at javax.media.opengl.awt.GLCanvas$7.run(GLCanvas.java:1054) at jogamp.opengl.GLDrawableHelper.invokeGLImpl(GLDrawableHelper.java:1034) at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:909) at javax.media.opengl.awt.GLCanvas$8.run(GLCanvas.java:1065) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:199) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:666) at java.awt.EventQueue.access$400(EventQueue.java:81) at java.awt.EventQueue$2.run(EventQueue.java:627) at java.awt.EventQueue$2.run(EventQueue.java:625) at java.security.AccessController.doPrivileged(Native Method) at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87) at java.awt.EventQueue.dispatchEvent(EventQueue.java:636) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) </code></pre> <p>This means I can't use video, of course. <strong>Any tips on fixing this?</strong></p>
1
1,689
XSLT Munchen method and child element of prior XML tag
<p>I've been attempting to group data to reduce the output, however when I use Munchen I get close to what I want, but with an expected "bug" in the output. I've tried to come up with a solution, but I have run out of ideas!</p> <p>Please recognize that the data set here is a <strong>very</strong> simplified look at the actual data in order to be able to post this question. There are about 40 more tags at various levels in the real data so perhaps I'm losing the forest for the trees.</p> <p>The data contains a set of names and start/end times. Currently if "Jeff" is working from 6-9a his name appears for each half hour of time (6 lines of data). The request is to list "Jeff" as appearing from 6-9a on a single line. I'm using "Jeff" as a test before applying it to the rest of the sheet so I can see what other issues might arise; therefore the test on his name will eventually be removed.</p> <pre><code>&lt;schedules&gt; &lt;ES_schedules name="Jeff"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="6" minutes="00" seconds="00" durationinseconds="21600"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="6" minutes="30" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Jeff"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="6" minutes="30" seconds="00" durationinseconds="23400"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="7" minutes="00" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Jeff"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="7" minutes="00" seconds="00" durationinseconds="25200"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="7" minutes="30" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Jeff"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="7" minutes="30" seconds="00" durationinseconds="27000"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="8" minutes="00" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Jeff"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="8" minutes="00" seconds="00" durationinseconds="28800"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="8" minutes="30" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Jeff"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="8" minutes="30" seconds="00" durationinseconds="30600"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="9" minutes="00" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Rich"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="9" minutes="00" seconds="00" durationinseconds="32400"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="12" minutes="00" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Jeff"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="12" minutes="00" seconds="00" durationinseconds="43200"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="12" minutes="30" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Jeff"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="12" minutes="30" seconds="00" durationinseconds="45000"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="13" minutes="00" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Dan"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="13" minutes="00" seconds="00" durationinseconds="46800"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="16" minutes="00" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Shane"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="16" minutes="00" seconds="00" durationinseconds="57600"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="16" minutes="30" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Sean"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="16" minutes="30" seconds="00" durationinseconds="59400"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="17" minutes="00" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Joe"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="17" minutes="00" seconds="00" durationinseconds="61200"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="17" minutes="30" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Mark"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="17" minutes="30" seconds="00" durationinseconds="63000"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="18" minutes="00" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Kendra"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="18" minutes="00" seconds="00" durationinseconds="64800"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="20" minutes="00" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Mark"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="20" minutes="00" seconds="00" durationinseconds="72000"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="20" minutes="30" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Crystal"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="20" minutes="30" seconds="00" durationinseconds="73800"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="22" minutes="30" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Matthew"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="22" minutes="30" seconds="00" durationinseconds="81000"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="23" minutes="00" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Georgia"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="23" minutes="00" seconds="00" durationinseconds="82800"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="1" minutes="00" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Ben"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="1" minutes="00" seconds="00" durationinseconds="90000"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="3" minutes="00" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="Ben"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="3" minutes="00" seconds="00" durationinseconds="97200"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="5" minutes="00" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; &lt;ES_schedules name="McGregor"&gt; &lt;tx_starttime&gt; &lt;ESP_TIMEDURATION hours="5" minutes="00" seconds="00" durationinseconds="104400"/&gt; &lt;/tx_starttime&gt; &lt;tx_endtime&gt; &lt;ESP_TIMEDURATION hours="6" minutes="00" seconds="00"/&gt; &lt;/tx_endtime&gt; &lt;tx_txdate&gt; &lt;ESP_DATE year="2016" dateindays="42063"/&gt; &lt;/tx_txdate&gt; &lt;/ES_schedules&gt; </code></pre> <p></p> <p>When I run this via the Munchean method below my output groups "Jeff" incorrectly. Since he works 6-9a and then 12-1p my output shows Jeff working from 6a-1p.</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output method="text"/&gt; &lt;xsl:key name="groups" match="schedules/ES_schedules" use="concat(tx_date//@dateindays, '_',@name)"/&gt; &lt;xsl:template match="/"&gt; &lt;xsl:for-each select="schedules/ES_schedules[generate-id() = generate-id(key('groups',concat(tx_date//@dateindays, '_',@name))[1])]"&gt; &lt;xsl:sort select="tx_txdate/ESP_DATE/@dateindays" data-type="number" order="ascending"/&gt; &lt;xsl:sort select="tx_starttime/ESP_TIMEDURATION/@durationinseconds" data-type="number" order="ascending"/&gt; &lt;xsl:variable name="thisDay" select="tx_txdate/ESP_DATE/@dateindays"/&gt; &lt;xsl:variable name="thisGroup" select="@name"/&gt; &lt;xsl:value-of select="@name"/&gt; &lt;xsl:text&gt; &lt;/xsl:text&gt; &lt;xsl:choose&gt; &lt;xsl:when test="@name = 'Jeff'"&gt; &lt;xsl:for-each select="/schedules/ES_schedules[tx_txdate/ESP_DATE/@dateindays = $thisDay and @name = 'Jeff']"&gt; &lt;xsl:sort data-type="number" select="tx_starttime/ESP_TIMEDURATION/@durationinseconds" order="ascending"/&gt; &lt;xsl:if test="position() = 1"&gt; &lt;xsl:apply-templates select="tx_starttime/ESP_TIMEDURATION"/&gt; &lt;/xsl:if&gt; &lt;/xsl:for-each&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;xsl:apply-templates select="tx_starttime/ESP_TIMEDURATION"/&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;xsl:text&gt; - &lt;/xsl:text&gt; &lt;xsl:choose&gt; &lt;xsl:when test="@name = 'Jeff'"&gt; &lt;xsl:for-each select="/schedules/ES_schedules[tx_txdate/ESP_DATE/@dateindays = $thisDay and @name = $thisGroup]"&gt; &lt;xsl:sort data-type="number" select="tx_starttime/ESP_TIMEDURATION/@durationinseconds" order="descending"/&gt; &lt;xsl:if test="position() = 1"&gt; &lt;xsl:apply-templates select="tx_endtime/ESP_TIMEDURATION"/&gt; &lt;/xsl:if&gt; &lt;/xsl:for-each&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;xsl:apply-templates select="tx_endtime/ESP_TIMEDURATION"/&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;xsl:text&gt;&amp;#xD;&lt;/xsl:text&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; &lt;xsl:template match="ESP_TIMEDURATION"&gt; &lt;!--2011-09-01T00:00:00.000--&gt; &lt;xsl:value-of select="format-number(@hours,'00')"/&gt; &lt;xsl:text&gt;:&lt;/xsl:text&gt; &lt;xsl:value-of select="format-number(@minutes,'00')"/&gt; &lt;xsl:text&gt;:&lt;/xsl:text&gt; &lt;xsl:value-of select="format-number(@seconds,'00')"/&gt; &lt;/xsl:template&gt; </code></pre> <p></p> <blockquote> <p>Jeff 06:00:00 - 13:00:00 Rich 09:00:00 - 12:00:00 Dan 13:00:00 - 16:00:00 Shane 16:00:00 - 16:30:00 Sean 16:30:00 - 17:00:00 Joe 17:00:00 - 17:30:00 Mark 17:30:00 - 18:00:00 Kendra 18:00:00 - 20:00:00 Crystal 20:30:00 - 22:30:00 Matthew 22:30:00 - 23:00:00 Georgia 23:00:00 - 01:00:00 Ben 01:00:00 - 03:00:00 McGregor 05:00:00 - 06:00:00</p> </blockquote> <p>I know that my problem is that the key is based on the date and name, but I'm not sure how to get XSLT to recognize that I want to group only if the prior time period has the same name.</p>
1
7,152
keyboardWillShow not respond
<p>here is problem, when i debug my program, i found keyboardWillShow function not responds every time. just first time, it will be called by program. here is my code, i dont know whats wrong in my code, but, when the keyboard first appeared, the function run well.</p> <pre><code>- (void)keyboardWillShow:(NSNotification *)notification { /* Reduce the size of the text view so that it's not obscured by the keyboard. Animate the resize so that it's in sync with the appearance of the keyboard. */ NSDictionary *userInfo = [notification userInfo]; // Get the origin of the keyboard when it's displayed. NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]; // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position. CGRect keyboardRect = [aValue CGRectValue]; keyboardRect = [self.view convertRect:keyboardRect fromView:nil]; CGFloat keyboardTop = keyboardRect.origin.y; CGRect newTextViewFrame = self.textview.frame; newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y; // Get the duration of the animation. NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]; NSTimeInterval animationDuration; [animationDurationValue getValue:&amp;animationDuration]; // Animate the resize of the text view's frame in sync with the keyboard's appearance. [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:animationDuration]; textview.frame = newTextViewFrame; [UIView commitAnimations]; } - (void)keyboardWillHide:(NSNotification *)notification { NSDictionary* userInfo = [notification userInfo]; /* Restore the size of the text view (fill self's view). Animate the resize so that it's in sync with the disappearance of the keyboard. */ NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]; NSTimeInterval animationDuration; [animationDurationValue getValue:&amp;animationDuration]; [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:animationDuration]; // textview.frame = self.view.bounds; [self save]; [UIView commitAnimations]; } </code></pre> <p>and i regist notification</p> <pre><code>- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; } </code></pre> <p>and remove it in here</p> <pre><code>- (void)viewDidUnload { [super viewDidUnload]; [self save]; self.textview = nil; self.title = nil; self.tags = nil; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; } </code></pre> <p>i resign firstresponder, here is my code</p> <pre><code>- (IBAction)save:(id)sender { self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNote)] autorelease]; [textview resignFirstResponder]; } - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{ self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(save:)] autorelease]; [self setUpUndoManager]; return YES; } - (BOOL)textFieldShouldEndEditing:(UITextField *)textField{ [self save]; return YES; } </code></pre>
1
1,318
how to send a mail to group of person by using Javamail
<p>Can anybody tell me how to send a mail to group of person by using JavaMail?</p> <p>I have tried but I am getting error at <code>SendEmailToGroupDemo()</code> and at <code>start()</code> method.</p> <pre><code>public class MailJava { public static void main(String[] args) { // Create a SendEmail object and call start // method to send a mail in Java. SendEmailToGroupDemo sendEmailToGroup = new SendEmailToGroupDemo(); sendEmailToGroup.start(); } private void start() { // For establishment of email client with // Google's gmail use below properties. // For TLS Connection use below properties // Create a Properties object Properties props = new Properties(); // these properties are required // providing smtp auth property to true props.put("mail.smtp.auth", "true"); // providing tls enability props.put("mail.smtp.starttls.enable", "true"); // providing the smtp host i.e gmail.com props.put("mail.smtp.host", "smtp.gmail.com"); // providing smtp port as 587 props.put("mail.smtp.port", "587"); // For SSL Connection use below properties /*props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465");*/ // Create Scanner object to take necessary // values from the user. Scanner scanner = new Scanner(System.in); System.out.println("Please provide your Username for Authentication ..."); final String Username = scanner.next(); System.out.println("Please provide your Password for Authentication ..."); final String Password = scanner.next(); System.out.println("Please provide Email Address from which you want to send Email ..."); final String fromEmailAddress = scanner.next(); System.out.println("Please provide Email Addresses to which you want to send Email ..."); System.out.println("If you are done type : Done or done"); // ArrayLists to store email addresses entered by user ArrayList&lt; String&gt; emails = (ArrayList&lt; String &gt;) getEmails(); System.out.println("Please provide Subject for your Email ... "); final String subject = scanner.next(); System.out.println("Please provide Text Message for your Email ... "); final String textMessage = scanner.next(); // Create a Session object based on the properties and // Authenticator object Session session = Session.getDefaultInstance(props, new LoginAuthenticator(Username,Password)); try { // Create a Message object using the session created above Message message = new MimeMessage(session); // setting email address to Message from where message is being sent message.setFrom(new InternetAddress(fromEmailAddress)); // setting the email addressess to which user wants to send message message.setRecipients(Message.RecipientType.BCC, getEmailsList(emails)); // setting the subject for the email message.setSubject(subject); // setting the text message which user wants to send to recipients message.setText(textMessage); // Using the Transport class send() method to send message Transport.send(message); System.out.println("\nYour Message delivered successfully ...."); } catch (MessagingException e) { throw new RuntimeException(e); } } // This method takes a list of email addresses and // returns back an array of Address by looping the // list one by one and storing it into Address[] private Address[] getEmailsList(ArrayList&lt; String &gt; emails) { Address[] emaiAddresses = new Address[emails.size()]; for (int i =0;i &lt; emails.size();i++) { try { emaiAddresses[i] = new InternetAddress(emails.get(i)); } catch (AddressException e) { e.printStackTrace(); } } return emaiAddresses; } // This method prompts user for email group to which he // wants to send message public List&lt; String &gt; getEmails() { ArrayList&lt; String &gt; emails = new ArrayList&lt; String &gt;(); int counter = 1; String address = ""; Scanner scanner = new Scanner(System.in); // looping inifinitely times as long as user enters // emails one by one // the while loop breaks when user types done and // press enter. while(true) { System.out.println("Enter E-Mail : " + counter); address = scanner.next(); if(address.equalsIgnoreCase("Done")){ break; } else { emails.add(address); counter++; } } return emails; } } // Creating a class for Username and Password authentication // provided by the user. class LoginAuthenticator extends Authenticator { PasswordAuthentication authentication = null; public LoginAuthenticator(String username, String password) { authentication = new PasswordAuthentication(username,password); } @Override protected PasswordAuthentication getPasswordAuthentication() { return authentication; } } </code></pre>
1
1,924
Are there any guarantees about C struct order?
<p>I've used structs extensively and I've seen some interesting things, especially <code>*value</code> instead of <code>value-&gt;first_value</code> where value is a pointer to struct, <code>first_value</code> is the very first member, is <code>*value</code> safe?</p> <p>Also note that sizes aren't guaranteed because of alignment, whats the alginment value based on, the architecture/register size?</p> <p>We align data/code for faster execution can we tell compiler not to do this? so maybe we can guarantee certain things about structs, like their size?</p> <p>When doing pointer arithmetic on struct members in order to locate member offset, I take it you do <code>-</code> if little endian <code>+</code> for big endian, or does it just depend on the compiler?</p> <p><i>what does malloc(0) really allocate?</i></p> <p><b>The following code is for educational/discovery purposes, its not meant to be of production quality.</b> </p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; int main() { printf("sizeof(struct {}) == %lu;\n", sizeof(struct {})); printf("sizeof(struct {int a}) == %lu;\n", sizeof(struct {int a;})); printf("sizeof(struct {int a; double b;}) == %lu;\n", sizeof(struct {int a; double b;})); printf("sizeof(struct {char c; double a; double b;}) == %lu;\n", sizeof(struct {char c; double a; double b;})); printf("malloc(0)) returns %p\n", malloc(0)); printf("malloc(sizeof(struct {})) returns %p\n", malloc(sizeof(struct {}))); struct {int a; double b;} *test = malloc(sizeof(struct {int a; double b;})); test-&gt;a = 10; test-&gt;b = 12.2; printf("test-&gt;a == %i, *test == %i \n", test-&gt;a, *(int *)test); printf("test-&gt;b == %f, offset of b is %i, *(test - offset_of_b) == %f\n", test-&gt;b, (int)((void *)test - (void *)&amp;test-&gt;b), *(double *)((void *)test - ((void *)test - (void *)&amp;test-&gt;b))); // find the offset of b, add it to the base,$ free(test); return 0; } </code></pre> <p>calling <code>gcc test.c</code> followed by <code>./a.out</code> I get this:</p> <pre><code>sizeof(struct {}) == 0; sizeof(struct {int a}) == 4; sizeof(struct {int a; double b;}) == 16; sizeof(struct {char c; double a; double b;}) == 24; malloc(0)) returns 0x100100080 malloc(sizeof(struct {})) returns 0x100100090 test-&gt;a == 10, *test == 10 test-&gt;b == 12.200000, offset of b is -8, *(test - offset_of_b) == 12.200000 </code></pre> <p><b>Update</b> this is my machine: </p> <p><code>gcc --version</code></p> <pre><code>i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5666) (dot 3) Copyright (C) 2007 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. </code></pre> <p><code>uname -a</code></p> <pre><code>Darwin MacBookPro 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun 7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386 </code></pre>
1
1,144
How to open main window after successful login
<p>I am gettin' stared wiith python. I got a udemy course and also read this post: <a href="https://stackoverflow.com/questions/45508996/how-to-let-your-main-window-appear-after-succesful-login-in-tkinterpython-3-6">How To Let Your Main Window Appear after succesful login in Tkinter(PYTHON 3.6</a></p> <p>Still, I am unable to implement the recired event. I want to open a new (main) window of the desctop app after login. For some reason the script also opens a third window all of a sudden. I am getting really frusted working since 2 das on that stuff...</p> <p>Thanks for help :)</p> <pre><code>from tkinter import Tk, Label, Button, messagebox from tkinter import * class AirsoftGunRack: ##### Main Window ##### ##### Login Page ##### def __init__(self,master): """ :type master: object """ ##### Login Page ##### self.master = master master.title("Login - Airsoft GunRack 3.0") master.geometry("450x230+450+170") # Creating describtions self.username = Label(master, text="Username:") self.username.place(relx=0.285, rely=0.298, height=20, width=55) self.password = Label(master, text="Password:") self.password.place(relx=0.285, rely=0.468, height=20, width=55) # Creating Buttons self.login_button = Button(master, text="Login") self.login_button.place(relx=0.440, rely=0.638, height=30, width=60) self.login_button.configure(command=self.login_user) self.exit_button = Button(master, text="Exit") # , command=master.quit) self.exit_button.place(relx=0.614, rely=0.638, height=30, width=60) self.exit_button.configure(command=self.exit_login) # Creating entry boxes self.username_box = Entry(master) self.username_box.place(relx=0.440, rely=0.298, height=20, relwidth=0.35) self.password_box = Entry(master) self.password_box.place(relx=0.440, rely=0.468, height=20, relwidth=0.35) self.password_box.configure(show="*") self.password_box.configure(background="white") # Creating checkbox self.var = IntVar() self.show_password = Checkbutton(master) self.show_password.place(relx=0.285, rely=0.650, relheight=0.100, relwidth=0.125) self.show_password.configure(justify='left') self.show_password.configure(text='''Show''') self.show_password.configure(variable=self.var, command=self.cb) def cb(self, ): if self.var.get() == True: self.password_box.configure(show="") else: self.password_box.configure(show="*") # Giving function to login process def login_user(self): name = self.username_box.get() password = self.password_box.get() if name == "user" and password == "1234": self.main_win.deiconify() #Unhides the root window self.master.destroy() #Removes the toplevel window #messagebox.showinfo("Login page", "Login successful!") else: messagebox.showwarning("Login failed", "Username or password incorrect!") def exit_login(self): msg = messagebox.askyesno("Exit login page", "Do you really want to exit?") if (msg): exit() main_win = Toplevel() main_win.title("Main Window") main_win.title("Main Window") main_win.geometry("800x800+450+170") root = Tk() gunrack = AirsoftGunRack(root) root.mainloop() #main_win.withdraw() main_win.mainloop() </code></pre>
1
1,267
OpenCV videocapture read camera rtsp error
<p>I’m using opencv-python (version 4.4.0.46) python version 3.8.5 to capture my IP Camera stream, however, I cannot read the video frame. Here is my code:</p> <pre class="lang-py prettyprint-override"><code>import cv2 # cap = cv2.VideoCapture(&quot;rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov&quot;) cap = cv2.VideoCapture(&quot;rtsp://admin:xxx@xxx/Streaming/Channels/1&quot;) print(cap.isOpened()) ret,frame = cap.read() print(ret) while ret: ret,frame = cap.read() print(ret) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cap.release() </code></pre> <p>In my code, when I use my IPC stream, I got &quot;print(cap.isOpened())&quot; as True, while &quot;cap.read()&quot; returns False. However, when it changes to &quot;BigBuckBunny_115k&quot; stream, everything is OK, and I can get the frame picture.</p> <p>Somebody might say that your IPC should be damaged. But I've tried using ffmpeg to capture video, which can easily get the frame picture. My code:</p> <pre><code>ffmpeg -i &quot;rtsp://admin:xxx@xxx/Streaming/Channels/1&quot; -y -f image2 -r 1/1 img%03d.jpg </code></pre> <p>Using python to capture video, I got &quot;False&quot; like above, but there is not ant error log printed, making me difficult to solve the problem. So I changed to use java, and using opencv-4.4.0.so as the library, my code:</p> <pre class="lang-java prettyprint-override"><code>VideoCapture videoCapture = new VideoCapture(); // set the exception mode true so that it can print stack trace when error videoCapture.setExceptionMode(true); boolean openStatus = videoCapture.open(&quot;rtsp://admin:xxx@xxx/Streaming/Channels/1&quot;); log.info(&quot;open rtsp status: {}&quot;, openStatus); int i = 0; status = true; while (openStatus &amp;&amp; status) { Mat mat = new Mat(); videoCapture.read(mat); Imgcodecs.imwrite(&quot;../&quot; + i + &quot;.png&quot;, mat); i++; } </code></pre> <p>by running this code, I got exception: org.opencv.core.CvException: cv::Exception: OpenCV(4.4.0) /xxx/opencv-4.4.0/modules/videoio/src/cap.cpp:177: error: (-2:Unspecified error) could not open 'rtsp://admin:xxx@xxx/Streaming/Channels/1' in function 'open'. The exception log above does not help to solve the problem, what does &quot;-2:Unspecified error&quot; means?</p> <p>Forgot to mention that my runtime is CentOS 7.5 (kernel version 3.10.0-862.el7.x86_64) . Then I changed to another server with the same opencv-python version and CentOS version. It is strange that on this new server, using the same opencv code, I can get the video frame now.</p> <p>The first question is, is there any relevant information that I can refer to? The second question is, how can I troubleshoot this problem. The third question is, why does it behave differently on different server, is there any system configuration on my first server error, like network configuration?</p> <hr /> <hr /> <p>Update on 2021.01.07</p> <p>Thanks antoine for giving me information about OpenCV backend. I've tried to print the python-opencv build information using the code below.</p> <pre><code>import cv2 print(cv2.getBuildInformation()) </code></pre> <p>And on the 2 servers I have (one of them can read the video stream and one of them not), I got console print totally the same. Here is the print:</p> <pre><code>General configuration for OpenCV 4.4.0 ===================================== Version control: 4.4.0-dirty Platform: Timestamp: 2020-11-03T00:52:03Z Host: Linux 4.15.0-1077-gcp x86_64 CMake: 3.18.2 CMake generator: Unix Makefiles CMake build tool: /bin/gmake Configuration: Release CPU/HW features: Baseline: SSE SSE2 SSE3 requested: SSE3 Dispatched code generation: SSE4_1 SSE4_2 FP16 AVX AVX2 AVX512_SKX requested: SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX SSE4_1 (15 files): + SSSE3 SSE4_1 SSE4_2 (1 files): + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 (0 files): + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 AVX AVX (4 files): + SSSE3 SSE4_1 POPCNT SSE4_2 AVX AVX2 (29 files): + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX512_SKX (4 files): + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX_512F AVX512_COMMON AVX512_SKX C/C++: Built as dynamic libs?: NO C++ standard: 11 C++ Compiler: /usr/lib/ccache/compilers/c++ (ver 9.3.1) C++ flags (Release): -Wl,-strip-all -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections -msse -msse2 -msse3 -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG C++ flags (Debug): -Wl,-strip-all -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections -msse -msse2 -msse3 -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG C Compiler: /usr/lib/ccache/compilers/cc C flags (Release): -Wl,-strip-all -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Winit-self -Wno-comment -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections -msse -msse2 -msse3 -fvisibility=hidden -O3 -DNDEBUG -DNDEBUG C flags (Debug): -Wl,-strip-all -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Winit-self -Wno-comment -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections -msse -msse2 -msse3 -fvisibility=hidden -g -O0 -DDEBUG -D_DEBUG Linker flags (Release): -Wl,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a -L/root/ffmpeg_build/lib -Wl,--gc-sections -Wl,--as-needed Linker flags (Debug): -Wl,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a -L/root/ffmpeg_build/lib -Wl,--gc-sections -Wl,--as-needed ccache: YES Precompiled headers: NO Extra dependencies: ade Qt5::Core Qt5::Gui Qt5::Widgets Qt5::Test Qt5::Concurrent /lib64/libpng.so /lib64/libz.so dl m pthread rt 3rdparty dependencies: ittnotify libprotobuf libjpeg-turbo libwebp libtiff libjasper IlmImf quirc ippiw ippicv OpenCV modules: To be built: calib3d core dnn features2d flann gapi highgui imgcodecs imgproc ml objdetect photo python3 stitching video videoio Disabled: world Disabled by dependency: - Unavailable: java js python2 ts Applications: - Documentation: NO Non-free algorithms: NO GUI: QT: YES (ver 5.15.0) QT OpenGL support: NO GTK+: NO VTK support: NO Media I/O: ZLib: /lib64/libz.so (ver 1.2.7) JPEG: libjpeg-turbo (ver 2.0.5-62) WEBP: build (ver encoder: 0x020f) PNG: /lib64/libpng.so (ver 1.5.13) TIFF: build (ver 42 - 4.0.10) JPEG 2000: build Jasper (ver 1.900.1) OpenEXR: build (ver 2.3.0) HDR: YES SUNRASTER: YES PXM: YES PFM: YES Video I/O: DC1394: NO FFMPEG: YES avcodec: YES (58.109.100) avformat: YES (58.61.100) avutil: YES (56.60.100) swscale: YES (5.8.100) avresample: NO GStreamer: NO v4l/v4l2: YES (linux/videodev2.h) Parallel framework: pthreads Trace: YES (with Intel ITT) Other third-party libraries: Intel IPP: 2020.0.0 Gold [2020.0.0] at: /tmp/pip-req-build-99ib2vsi/_skbuild/linux-x86_64-3.8/cmake-build/3rdparty/ippicv/ippicv_lnx/icv Intel IPP IW: sources (2020.0.0) at: /tmp/pip-req-build-99ib2vsi/_skbuild/linux-x86_64-3.8/cmake-build/3rdparty/ippicv/ippicv_lnx/iw Lapack: NO Eigen: NO Custom HAL: NO Protobuf: build (3.5.1) OpenCL: YES (no extra features) Include path: /tmp/pip-req-build-99ib2vsi/opencv/3rdparty/include/opencl/1.2 Link libraries: Dynamic load Python 3: Interpreter: /opt/python/cp38-cp38/bin/python (ver 3.8.6) Libraries: libpython3.8.a (ver 3.8.6) numpy: /tmp/pip-build-env-qru8fff1/overlay/lib/python3.8/site-packages/numpy/core/include (ver 1.17.3) install path: python Python (for build): /bin/python2.7 Java: ant: NO JNI: NO Java wrappers: NO Java tests: NO Install to: /tmp/pip-req-build-99ib2vsi/_skbuild/linux-x86_64-3.8/cmake-install ----------------------------------------------------------------- </code></pre> <p>In the print, I found the information:</p> <pre><code> Video I/O: DC1394: NO FFMPEG: YES avcodec: YES (58.109.100) avformat: YES (58.61.100) avutil: YES (56.60.100) swscale: YES (5.8.100) avresample: NO GStreamer: NO v4l/v4l2: YES (linux/videodev2.h) </code></pre> <p>Seems my two servers both have FFMPEG and don't have GStreamer. So, is there any other reason may cause the difference?</p> <p>By the way, I've tried passing API preference to the constructor like below:</p> <pre><code>cap = cv2.VideoCapture(&quot;rtsp://admin:xxx@xxx/Streaming/Channels/1&quot;, cv2.CAP_FFMPEG) </code></pre> <p>However, passing the parameter didn't solve the problem, I cannot read video frame either.</p>
1
5,574
drf_yasg documentation parameters not showing
<p>I am using drf_yasg to self document my API which is built using the django-framework, but none of the parameters are displaying at all for any of the endpoints. The way I've done it is to pass the parameters within the http request body in JSON format. I then read the parameters from request.data. Below is an example of one of the views where it takes 'id' as a parameter in the body of the request.</p> <pre><code>@api_view(['POST']) @permission_classes([IsAuthenticated]) def get_availability_by_schoolid(request): if request.user.is_donor: try: #Get the existing slots and remove them to replace with new slots slots = SchoolSlot.objects.filter(school__id=request.data[&quot;id&quot;]).values('day','am','pm') availability = process_availability(slots) availabilityslotserializer = SchoolSlotSerializer(availability) return Response(availabilityslotserializer.data, status=status.HTTP_200_OK) except Exception as e: print(e) return Response(ResponseSerializer(GeneralResponse(False,&quot;Unable to locate school&quot;)).data, status=status.HTTP_400_BAD_REQUEST) else: return Response(ResponseSerializer(GeneralResponse(False,&quot;Not registered as a donor&quot;)).data, status=status.HTTP_400_BAD_REQUEST) </code></pre> <p>This will display in the swagger documentation as below:</p> <p><a href="https://i.stack.imgur.com/1lRyq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1lRyq.png" alt="swagger output" /></a></p> <p>I have been looking at the documentation and it suggests that i might need to add a decorator with manual parameters, but I can't figure out how I would do that as the examples I can find are for get query parameters or path parameters. I have added the decorator below which enables the response to document.</p> <pre><code>@swagger_auto_schema(method='post', responses={200: SchoolSlotSerializer,400: 'Bad Request'}) </code></pre> <p>An example of the request body for this is:</p> <pre><code> { &quot;id&quot;: 43 } </code></pre> <p>UPDATE:</p> <p>I seem to get something with the following decorator:</p> <pre><code>@swagger_auto_schema(method='post', request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'id': openapi.Schema(type=openapi.TYPE_INTEGER, description='Donor ID') }), responses={200: SchoolSlotSerializer,400: 'Bad Request'}) </code></pre> <p>This documents the parameters. Now what I have for another endpoint is it takes the following JSON for input, how would I go about adding this?</p> <pre><code> { &quot;availability&quot;: { &quot;mon&quot;: { &quot;AM&quot;: true, &quot;PM&quot;: false }, &quot;tue&quot;: { &quot;AM&quot;: false, &quot;PM&quot;: false }, &quot;wed&quot;: { &quot;AM&quot;: false, &quot;PM&quot;: false }, &quot;thu&quot;: { &quot;AM&quot;: true, &quot;PM&quot;: true }, &quot;fri&quot;: { &quot;AM&quot;: false, &quot;PM&quot;: false }, &quot;sat&quot;: { &quot;AM&quot;: false, &quot;PM&quot;: false }, &quot;sun&quot;: { &quot;AM&quot;: true, &quot;PM&quot;: false } } } </code></pre>
1
1,567
Suddenly getting "Error: TrustFailure (The authentication or decryption has failed.)" on my Xamarin Android app
<p>Just out of the blue, my app started getting this error when making calls to a REST API via https. I was working on a mod that added an Intent to handle opening files of a certain file extension but I doubt that that was the cause. </p> <p>Instead, the problem is similar to this one: <a href="https://stackoverflow.com/questions/43815536/invalid-certificate-received-from-server">Invalid certificate received from server</a></p> <p>My cert is also by Comodo and has been installed since April of this year. The solution of disabling the COMODO RSA Certification Authority did not work.</p> <p>The server is a VPS that the host underwent a hardware upgrade during the time that this error started to appear but I'm also not sure that that would be the reason since the browser shows SSL as fine and the iOS version of the app is also working fine.</p> <p>The code in the app that makes the call to the server is in a utility class and I did not change that code at all. The minor change that I did was to add an intent which I then removed and the error is still there.</p> <p>Here are the error messages including the inner exceptions and the stack trace:</p> <pre><code>System.Net.WebExceptionStatus.TrustFailure ex.InnerException.Message - The authentication or decryption has failed. ex.InnerException.InnerException.InnerException.Message - Invalid certificate received from server. Error code: 0xffffffff800b010b ex.InnerException.InnerException.StackTrace at Mono.Security.Protocol.Tls.RecordProtocol.EndReceiveRecord (System.IAsyncResult asyncResult) [0x0003a] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs:430 at Mono.Security.Protocol.Tls.SslClientStream.SafeEndReceiveRecord (System.IAsyncResult ar, System.Boolean ignoreEmpty) [0x00000] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs:256 at Mono.Security.Protocol.Tls.SslClientStream.NegotiateAsyncWorker (System.IAsyncResult result) [0x00071] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs:418 ex.InnerException.StackTrace at Mono.Security.Protocol.Tls.SslStreamBase.EndRead (System.IAsyncResult asyncResult) [0x00051] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslStreamBase.cs:883 at Mono.Net.Security.Private.LegacySslStream.EndAuthenticateAsClient (System.IAsyncResult asyncResult) [0x00011] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/System/Mono.Net.Security/LegacySslStream.cs:475 at Mono.Net.Security.Private.LegacySslStream.AuthenticateAsClient (System.String targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, System.Boolean checkCertificateRevocation) [0x00000] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/System/Mono.Net.Security/LegacySslStream.cs:445 at Mono.Net.Security.MonoTlsStream.CreateStream (System.Byte[] buffer) [0x0004e] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/System/Mono.Net.Security/MonoTlsStream.cs:106 </code></pre> <p>I'm using the standard port 443. I checked the bindings and there are no issues, it says that the cert is 'ok' when I view the certification path status.</p> <p>I am getting the error when using an actual device, not an emulator.</p> <p>Any help is appreciated.</p> <p>***** update </p> <p>I called Comodo's support and found out the issue is with Android's certificate store not being up to date and using the old legacy SHA. So the certification path 2 was coming back to the client with a 'Extra Download' status. There supposedly is a cert named 'COMODO RSA Certification Authority' in my server expiring in 2036 that interferes with 'COMODO RSA Certification Authority' intermediate certificate expiring in 2020. Here are the details of that cert:</p> <p>[Root] Comodo RSA Certification Authority (SHA-2) Serial Number: 4c:aa:f9:ca:db:63:6f:e0:1f:f7:4e:d8:5b:03:86:9d Issuer: C=GB, ST=Greater Manchester, L=Salford, O=COMODO CA Limited, CN=COMODO RSA Certification Authority<br> Validity (Expires) : Jan 18 23:59:59 2038 GMT</p> <p>However, I couldn't find out in both local computer and current user. Since this is a VPS/virtual machine, the problem may be that the host machine may be adding this in the virtual network communication/response back to the client. The problem now is that the hosting company doesn't want to disable the cert in the host machine.</p>
1
1,471
Sqlite giving NullPointerException error in android
<p>I am trying to use sqlite DB to store images along with other information in my android app but i am getting this error</p> <pre><code>06-20 12:00:51.411 4132-4132/braindottech.com.fishid E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: braindottech.com.fishid, PID: 4132 java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223) at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163) at braindottech.com.fishid.PhotoDBMS.&lt;init&gt;(PhotoDBMS.java:65) at braindottech.com.fishid.CameraScan$6.onClick(UseSqliteDB.java:23) at android.view.View.performClick(View.java:5204) at android.view.View$PerformClick.run(View.java:21153) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) </code></pre> <p>Here is my "UseSqliteDB.java" code: </p> <pre><code>public class UseSqliteDB extends Fragment { private Button saveResult; public UseSqliteDB(){} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_camera, container, false); context = this.getActivity(); saveResult = (Button) v.findViewById(R.id.button_save_CameraPreview); saveResult.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { try { PhotoDBMS photoDBMS = new PhotoDBMS(getActivity()); String nameImage = "IMAGE"; Calendar calendar = Calendar.getInstance(); nameImage += calendar.get(Calendar.DATE) + calendar.get(Calendar.HOUR) + calendar.get(Calendar.MINUTE) + calendar.get(Calendar.SECOND) + calendar.get(Calendar.MILLISECOND); Boolean response = photoDBMS.insertData(nameImage, resultTV.getText().toString(), finalBitmap); if (!response) { Toast.makeText(context, "Database entry failed!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(context, "Database entry successful!", Toast.LENGTH_LONG).show(); } }catch(Exception e){ Log.d("HIP","E = "+e); } } }); return v; } } </code></pre> <p>PhotoDBMS.java</p> <pre><code>public class PhotoDBMS { private Context context; public PhotoDBMS(Context c){ context = c; } public static abstract class DBMS_Constants implements BaseColumns { public static final String TABLE_NAME = "MY_COLLECTION"; public static final String COLUMN_NAME_NAME = "Name"; public static final String COLUMN_NAME_INFO = "Info"; public static final String COLUMN_NAME_IMAGE = "Image"; } private static final String TEXT_TYPE = " TEXT"; private static final String COMMA_SEP = ","; private static final String BLOB = "BLOB"; private static final String SQL_CREATE_TABLE = "CREATE TABLE " + DBMS_Constants.TABLE_NAME + " (" + DBMS_Constants._ID + " INTEGER PRIMARY KEY," + DBMS_Constants.COLUMN_NAME_NAME + TEXT_TYPE + COMMA_SEP + DBMS_Constants.COLUMN_NAME_INFO + TEXT_TYPE + COMMA_SEP + DBMS_Constants.COLUMN_NAME_IMAGE + BLOB + " )"; private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + DBMS_Constants.TABLE_NAME; public class DbHelper extends SQLiteOpenHelper { // If you change the database schema, you must increment the database version. public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "FeedReader.db"; public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_TABLE); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // This database is only a cache for online data, so its upgrade policy is // to simply to discard the data and start over db.execSQL(SQL_DELETE_ENTRIES); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } } DbHelper dbHelper = new DbHelper(context); SQLiteDatabase collectionDB = dbHelper.getWritableDatabase(); public boolean insertData(String name, String info, Bitmap bm){ bitmapUtility utility = new bitmapUtility(); byte[] image = utility.getBytes(bm); ContentValues cv = new ContentValues(); cv.put(DBMS_Constants.COLUMN_NAME_NAME, name); cv.put(DBMS_Constants.COLUMN_NAME_INFO, info); cv.put(DBMS_Constants.COLUMN_NAME_IMAGE, image); return collectionDB.insert( DBMS_Constants.TABLE_NAME, null, cv ) &gt; 0; } public boolean deleteData(String name){ return collectionDB.delete(DBMS_Constants.TABLE_NAME, DBMS_Constants.COLUMN_NAME_NAME + " = " + name, null) &gt; 0; } } </code></pre> <p>I am getting this error on try-catch section inside UseSqliteDB.java. Please help me to solve this error. Thankx in advance! </p>
1
2,355
HABTM Double-Nested fields_for
<p>Interesting segment of code that I can't get to work. I have the following models/relationships (unnecessary code excluded)</p> <pre><code>class Service &lt; ActiveRecord::Base belongs_to :service_category, :foreign_key =&gt; "cats_uid_fk" belongs_to :service_type, :foreign_key =&gt; "types_uid_fk" has_and_belongs_to_many :service_subtypes, :join_table =&gt; "services_to_service_subs" belongs_to :service_request, :foreign_key =&gt; "audits_uid_fk" accepts_nested_attributes_for :service_subtypes end class ServiceSubtype &lt; ActiveRecord::Base belongs_to :service_types, :foreign_key =&gt; "types_uid_fk" has_and_belongs_to_many :services, :join_table =&gt; "services_to_service_subs" end </code></pre> <p>The form displaying all this info:</p> <pre><code>&lt;% form_for(@request, :url =&gt; { :action =&gt; :create }) do |form| %&gt; &lt;table&gt; ...other data... &lt;% form.fields_for :services do |fields| %&gt; &lt;%= fields.hidden_field :cats_uid_fk %&gt; &lt;%= fields.hidden_field :types_uid_fk %&gt; &lt;% fields.fields_for :service_subtypes do |subtype| %&gt; &lt;%= subtype.hidden_field :id %&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;p&gt; &lt;%= form.submit "Create", :class=&gt;"hargray" %&gt; &lt;/p&gt; &lt;% end %&gt; </code></pre> <p>And the controller to handle the submit:</p> <pre><code>def create logger.debug params[:service_request].inspect @request = ServiceRequest.new(params[:service_request]) if session[:cus_id] @request.customer = Customer.find session[:cus_id] end begin @request.save! flash[:notice] = "Information submitted successfully. You will be contacted by a customer service representative regarding the services you selected." redirect_to :controller =&gt; "customer", :action =&gt; "index" rescue Exception =&gt; exc flash[:notice] = "#{ format_validations(@request) } - #{exc.message}" render :action =&gt; "new" end end </code></pre> <p>The html looks clean:</p> <pre><code>&lt;input id="service_request_services_attributes_0_cats_uid_fk" name="service_request[services_attributes][0][cats_uid_fk]" type="hidden" value="1" /&gt; &lt;input id="service_request_services_attributes_0_types_uid_fk" name="service_request[services_attributes][0][types_uid_fk]" type="hidden" value="1" /&gt; &lt;input id="service_request_services_attributes_0_service_subtypes_attributes_0_id" name="service_request[services_attributes][0][service_subtypes_attributes][0][id]" type="hidden" value="2" /&gt; &lt;input id="service_request_services_attributes_0_service_subtypes_attributes_0_id" name="service_request[services_attributes][0][service_subtypes_attributes][0][id]" type="hidden" value="2" /&gt; &lt;input id="service_request_services_attributes_0_service_subtypes_attributes_1_id" name="service_request[services_attributes][0][service_subtypes_attributes][1][id]" type="hidden" value="4" /&gt; &lt;input id="service_request_services_attributes_0_service_subtypes_attributes_1_id" name="service_request[services_attributes][0][service_subtypes_attributes][1][id]" type="hidden" value="4" /&gt; </code></pre> <p>The submitted parameters look like this:</p> <pre><code>{ ...other data... "services_attributes"=&gt; { "0"=&gt; { "types_uid_fk"=&gt;"1", "service_subtypes_attributes"=&gt; { "0"=&gt;{"id"=&gt;"1"}, "1"=&gt;{"id"=&gt;"2"}, "2"=&gt;{"id"=&gt;"3"} }, "cats_uid_fk"=&gt;"1" } } } </code></pre> <p>I get back "undefined method 'service_subtype' for #" error and the only table not updated is the join table between the HABTM models. Any idea how to solve this or what is happening behind the scenes? I'm not sure I understand the "magic" happening behind this procedure to see it working. It seems like most say that HABTM doesnt work with nested attributes. Seems to be the case. Work arounds?</p>
1
1,455
Can't display files from a vsftpd server on centos 6
<p>It's a Centos 6 running apache server and vsftpd server. Problem is not about connection, it's about displaying folder from local_root directory.</p> <p>Here is /etc/vsftpd/vsftpd.conf :</p> <pre><code># Example config file /etc/vsftpd/vsftpd.conf # # The default compiled in settings are fairly paranoid. This sample file # loosens things up a bit, to make the ftp daemon more usable. # Please see vsftpd.conf.5 for all compiled in defaults. # # READ THIS: This example file is NOT an exhaustive list of vsftpd options. # Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's # capabilities. # # Allow anonymous FTP? (Beware - allowed by default if you comment this ou$ anonymous_enable=NO # # Uncomment this to allow local users to log in. local_enable=YES # # Uncomment this to enable any form of FTP write command. write_enable=YES # # Default umask for local users is 077. You may wish to change this to 022, # if your users expect that (022 is used by most other ftpd's) local_umask=022 # # Uncomment this to allow the anonymous FTP user to upload files. This only # has an effect if the above global write enable is activated. Also, you w$ # obviously need to create a directory writable by the FTP user. #anon_upload_enable=YES # # Uncomment this if you want the anonymous FTP user to be able to create # new directories. #anon_mkdir_write_enable=YES # # Activate directory messages - messages given to remote users when they # go into a certain directory. dirmessage_enable=YES # # The target log file can be vsftpd_log_file or xferlog_file. # This depends on setting xferlog_std_format parameter xferlog_enable=YES # # Make sure PORT transfer connections originate from port 20 (ftp-data). connect_from_port_20=YES # # If you want, you can arrange for uploaded anonymous files to be owned by # a different user. Note! Using "root" for uploaded files is not # recommended! #chown_uploads=YES #chown_username=whoever # # The name of log file when xferlog_enable=YES and xferlog_std_format=YES # WARNING - changing this filename affects /etc/logrotate.d/vsftpd.log #xferlog_file=/var/log/xferlog # # Switches between logging into vsftpd_log_file and xferlog_file files. # NO writes to vsftpd_log_file, YES to xferlog_file xferlog_std_format=YES # # You may change the default value for timing out an idle session. #idle_session_timeout=600 # # You may change the default value for timing out a data connection. #data_connection_timeout=120 # # It is recommended that you define on your system a unique user which the # ftp server can use as a totally isolated and unprivileged user. #nopriv_user=ftpsecure # # Enable this and the server will recognise asynchronous ABOR requests. Not # recommended for security (the code is non-trivial). Not enabling it, # however, may confuse older FTP clients. #async_abor_enable=YES # # By default the server will pretend to allow ASCII mode but in fact ignore # the request. Turn on the below options to have the server actually do AS$ # mangling on files when in ASCII mode. # Beware that on some FTP servers, ASCII support allows a denial of service # attack (DoS) via the command "SIZE /big/file" in ASCII mode. vsftpd # predicted this attack and has always been safe, reporting the size of the # raw file. # ASCII mangling is a horrible feature of the protocol. ascii_upload_enable=YES ascii_download_enable=YES # # You may fully customise the login banner string: #ftpd_banner=Welcome to blah FTP service. # # You may specify a file of disallowed anonymous e-mail addresses. Apparently # useful for combatting certain DoS attacks. #deny_email_enable=YES # (default follows) #banned_email_file=/etc/vsftpd/banned_emails # # You may specify an explicit list of local users to chroot() to their home # directory. If chroot_local_user is YES, then this list becomes a list of # users to NOT chroot(). #chroot_local_user=YES chroot_list_enable=YES # (default follows) chroot_list_file=/etc/vsftpd/chroot_list # # You may activate the "-R" option to the builtin ls. This is disabled by # default to avoid remote users being able to cause excessive I/O on large # sites. However, some broken FTP clients such as "ncftp" and "mirror" assume # the presence of the "-R" option, so there is a strong case for enabling it. ls_recurse_enable=YES # # When "listen" directive is enabled, vsftpd runs in standalone mode and # listens on IPv4 sockets. This directive cannot be used in conjunction # with the listen_ipv6 directive. listen=YES # # This directive enables listening on IPv6 sockets. To listen on IPv4 and IPv6 # sockets, you must run two copies of vsftpd with two configuration files. # Make sure, that one of the listen options is commented !! #listen_ipv6=YES ## Heading ## pam_service_name=vsftpd userlist_enable=YES tcp_wrappers=YES chroot_local_user=YES local_root=/var/www user_sub_token=$USER </code></pre> <p>Here is ls -l output in / folder :</p> <pre><code>[root@daniel /]# ls -l total 98 dr-xr-xr-x. 2 root root 4096 2015-05-14 04:43 bin dr-xr-xr-x. 5 root root 1024 2015-05-12 15:33 boot drwxr-xr-x. 20 root root 3820 2015-06-05 02:30 dev drwxr-xr-x. 103 root root 12288 2015-06-05 03:03 etc drwxr-xr-x. 5 root root 4096 2015-05-08 06:54 home dr-xr-xr-x. 11 root root 4096 2015-05-08 05:13 lib dr-xr-xr-x. 9 root root 12288 2015-06-04 03:25 lib64 drwx------. 2 root root 16384 2015-05-08 04:13 lost+found drwxr-xr-x. 2 root root 4096 2011-09-23 14:50 media drwxr-xr-x. 2 root root 0 2015-06-05 02:29 misc drwxr-xr-x. 2 root root 4096 2011-09-23 14:50 mnt drwxr-xr-x. 2 root root 0 2015-06-05 02:29 net drwxr-xr-x. 3 root root 4096 2015-05-08 05:13 opt dr-xr-xr-x. 167 root root 0 2015-06-05 02:29 proc dr-xr-x---. 10 root root 4096 2015-06-04 03:02 root dr-xr-xr-x. 2 root root 12288 2015-05-24 03:34 sbin drwxr-xr-x. 7 root root 0 2015-06-05 02:29 selinux drwxr-xr-x. 2 root root 4096 2011-09-23 14:50 srv drwxr-xr-x. 13 root root 0 2015-06-05 02:29 sys drwxrwxrwt. 3 root root 4096 2015-06-05 03:28 tmp drwxr-xr-x. 13 root root 4096 2015-05-08 05:04 usr drwxr-xr-x. 22 root root 4096 2015-06-04 02:57 var </code></pre> <p>This folder is displayed in browser or ftp connection(ftp 192.168.1.10) but /var/www is not :(.</p> <p>Also ls -l /var/www : </p> <pre><code>[root@daniel /]# ls -al /var/www total 84 drwxrwxr-x+ 11 root root 4096 2015-06-04 05:32 . drwxr-xr-x. 22 root root 4096 2015-06-04 02:57 .. drwxrwxr-x+ 3 root root 4096 2015-05-22 06:09 site1.com drwxrwxr-x+ 3 root root 4096 2015-05-22 05:30 site2.com drwxrwxr-x+ 2 root root 4096 2015-06-02 05:59 cgi-bin drwxrwxr-x+ 3 root root 4096 2015-05-20 05:55 error drwxrwxr-x+ 2 root root 4096 2015-06-04 05:32 ftp drwxrwxr-x+ 2 root root 4096 2015-05-22 03:55 html drwxrwxr-x+ 3 root root 4096 2015-05-20 05:58 icons drwxrwxr-x+ 3 root root 4096 2015-05-22 05:30 site3.com drwxrwxr-x+ 2 root root 4096 2015-05-19 07:26 usage </code></pre> <p>And also selinux bools for ftp :</p> <pre><code>[root@daniel /]# getsebool -a | grep ftp allow_ftpd_anon_write --&gt; off allow_ftpd_full_access --&gt; off allow_ftpd_use_cifs --&gt; off allow_ftpd_use_nfs --&gt; off ftp_home_dir --&gt; on ftpd_connect_db --&gt; off ftpd_use_fusefs --&gt; off ftpd_use_passive_mode --&gt; off httpd_enable_ftp_server --&gt; off tftp_anon_write --&gt; off tftp_use_cifs --&gt; off tftp_use_nfs --&gt; off </code></pre> <p>Sorry for this too long question, but I tried to expose all details you need to solve this problem.</p> <p>Thanks in advance for your help!</p>
1
2,686
How to create an Access report from a query using vb.net
<p>Let me explain what trying to do. I have a vb.net form linked with an access database. The form let you make a query and search the database. Now I want to put the option to print a report from the same query.</p> <p>This it what my form look like: </p> <p><img src="https://i.stack.imgur.com/GQhbI.png" alt="enter image description here"></p> <ol> <li>I want to let the user chose what he want to see in the report</li> <li>Create a report from the query </li> <li>Be able to preview the report</li> <li><p>Print it</p> <p>I could not found anywhere how to create report using a specific query.</p></li> </ol> <p><strong>What I was able to do</strong>:</p> <ol> <li>I was able to print a report that has already been created in access using this <a href="http://support.microsoft.com/en-us/kb/317113/en-us?p=1" rel="nofollow noreferrer">link</a>.</li> <li>I was able to print show the results of the query in an excel sheet.</li> </ol> <hr> <p>This is the part of my code where I connect to the database and show the results in excel</p> <pre><code> ' Connect to the database and send the query Dim con As New OleDb.OleDbConnection Dim ds As New DataSet Dim da As OleDb.OleDbDataAdapter Dim MaxRows As Integer Try con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\docs-management.mdb" con.Open() da = New OleDb.OleDbDataAdapter(sql, con) da.Fill(ds, "DocList") ' Discover if there's a successful search MaxRows = ds.Tables("DocList").Rows.Count If MaxRows = 0 Then MsgBox("No documents were found using this filter.") con.Close() Exit Sub End If Dim YesOrNoAnswerToMessageBox As String Dim QuestionToMessageBox As String QuestionToMessageBox = MaxRows &amp; " Document(s) have been found and will be put into an excel spreadsheet." &amp; _ vbCrLf &amp; "Would you like to continue?" YesOrNoAnswerToMessageBox = MsgBox(QuestionToMessageBox, vbYesNo, "Narrowing your search") If YesOrNoAnswerToMessageBox = vbNo Then Exit Sub Else End If Dim oExcel As Object Dim oBook As Object Dim oSheet As Object oExcel = CreateObject("Excel.Application") oExcel.Visible = True oBook = oExcel.Workbooks.Add oSheet = oBook.Worksheets(1) 'Transfer the data to Excel For columns = 0 To ds.Tables("DocList").Columns.Count - 1 oSheet.Cells(1, columns + 1) = ds.Tables("DocList").Columns(columns).ColumnName Next oSheet.Rows("1:1").Font.Bold = True For col = 0 To ds.Tables("DocList").Columns.Count - 1 For row = 0 To ds.Tables("DocList").Rows.Count - 1 oSheet.Cells(row + 2, col + 1) = ds.Tables("DocList").Rows(row).ItemArray(col) ' This is where we make hyperlinks out of the file locations If ds.Tables("DocList").Columns(col).ToString = "File_Location" Then oSheet.Hyperlinks.Add(Anchor:=oSheet.Cells(row + 2, col + 1), Address:=ds.Tables("DocList").Rows(row).ItemArray(col), TextToDisplay:=ds.Tables("DocList").Rows(row).ItemArray(col)) End If Next Next con.Close() Catch MsgBox("An error has been generated while contacting or transfering data from the database.") End Try </code></pre>
1
1,444
Java 7: SEND TLSv1.2 ALERT: fatal, description = handshake_failure mule
<p>I'm using <strong>java 7</strong>, <strong>mule 3.7.0</strong>, I've installed <strong>Java Cryptography Extension</strong></p> <p>I'm trying to send a request to a server, but I'm getting:</p> <pre><code>java.io.EOFException: SSL peer shut down incorrectly at sun.security.ssl.InputRecord.read(InputRecord.java:482) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:944) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1342) Cipher Suites: [TLS_DHE_DSS_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA] Compression Methods: { 0 } Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1} Extension ec_point_formats, formats: [uncompressed] Extension extended_master_secret Extension server_name, server_name: [host_name: merchant.payb.lv] *** entry.worker.04, WRITE: TLSv1 Handshake, length = 136 entry.worker.04, received EOFException: error entry.worker.04, handling exception: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake entry.worker.04, SEND TLSv1.2 ALERT: fatal, description = handshake_failure entry.worker.04, WRITE: TLSv1.2 Alert, length = 2 entry.worker.04, Exception sending alert: java.net.SocketException: Broken pipe (Write failed) entry.worker.04, called closeSocket() entry.worker.04, called close() entry.worker.04, called closeInternal(true) entry.worker.04, called close() entry.worker.04, called closeInternal(true) entry.worker.04, called close() entry.worker.04, called closeInternal(true) </code></pre> <p>As I understood the problem is that there's no support for <strong>TLSv1.2</strong>, but there should be after I installed <strong>Java Cryptography Extension</strong>, can anyone help, please?</p> <p>I've tried:</p> <pre><code>System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2") System.setProperty("jdk.tls.client.protocols", "TLSv1,TLSv1.1,TLSv1.2") System.setProperty("https.cipherSuites", "TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA") </code></pre> <p>Also tried:</p> <pre><code>String[] ciphers = new String[2] ciphers[0] = "TLS_RSA_WITH_AES_256_CBC_SHA256" ciphers[1] = "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA" SSLSocket.setEnabledCipherSuites(ciphers) String[] protocols = new String[1] protocols[0] = "TLSv1.2"; SSLSocket.setEnabledProtocols(protocols) </code></pre>
1
1,312
AWS ECS using docker and ngnix, how to get my nginx config into the container?
<p>I'm trying to setup a ECS cluster in AWS using Nginx, unicorn and Django.</p> <p>I have converted my docker-compose.yml into a ECS task, but am wondering how I get my nginx config into the container?</p> <p>this is my task in json</p> <p>I have created some mount points for files but am unsure how to get the config there. when I run docker from my local servers the nginx config file is local to the compose file, obviously in aws it is not?</p> <p>how do I get the nginx config into the contain through ecs?</p> <pre><code>{ "containerDefinitions": [ { "volumesFrom": null, "memory": 300, "extraHosts": null, "dnsServers": null, "disableNetworking": null, "dnsSearchDomains": null, "portMappings": [ { "containerPort": 8000, "protocol": "tcp" } ], "hostname": null, "essential": true, "entryPoint": null, "mountPoints": [ { "containerPath": "/static", "sourceVolume": "_Static", "readOnly": null } ], "name": "it-app", "ulimits": null, "dockerSecurityOptions": null, "environment": null, "links": null, "workingDirectory": "/itapp", "readonlyRootFilesystem": null, "image": "*****.amazonaws.com/itapp", "command": [ "bash", "-c", "", "python manage.py collectstatic --noinput &amp;&amp; python manage.py makemigrations &amp;&amp; python manage.py migrate &amp;&amp; gunicorn itapp.wsgi -b 0.0.0.0:8000" ], "user": null, "dockerLabels": null, "logConfiguration": null, "cpu": 0, "privileged": null }, { "volumesFrom": null, "memory": 300, "extraHosts": null, "dnsServers": null, "disableNetworking": null, "dnsSearchDomains": null, "portMappings": [ { "hostPort": 80, "containerPort": 8000, "protocol": "tcp" } ], "hostname": null, "essential": true, "entryPoint": null, "mountPoints": [ { "containerPath": "/etc/nginx/conf.d", "sourceVolume": "_ConfigNginx", "readOnly": null }, { "containerPath": "/static", "sourceVolume": "_Static", "readOnly": null } ], "name": "nginx", "ulimits": null, "dockerSecurityOptions": null, "environment": null, "links": [ "it-app" ], "workingDirectory": null, "readonlyRootFilesystem": null, "image": "nginx:latest", "command": null, "user": null, "dockerLabels": null, "logConfiguration": null, "cpu": 0, "privileged": null } ], "placementConstraints": [], "volumes": [ { "host": { "sourcePath": "./config/nginx" }, "name": "_ConfigNginx" }, { "host": { "sourcePath": "./static" }, "name": "_Static" } ], "family": "it-app-task", "networkMode": "bridge" } </code></pre> <p>ngnix config</p> <pre><code>upstream web { ip_hash; server web:8000; } server { location /static/ { autoindex on; alias /static/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_pass http://web/; } listen 8000; server_name localhost; } </code></pre>
1
2,379
NHibernate cascading save
<p>This is trying to insert null into Comment.BlogArticleID.</p> <p>The following GenericADOException appeared: "could not insert: [NHibernate__OneToMany.BO.Comment][SQL: INSERT INTO Comment (Name) VALUES (?); select SCOPE_IDENTITY()]"</p> <p>The following Inner-Exception appeared: "Cannot insert the value NULL into column 'BlogArticleID', table 'Relationships_Test_OneToMany.dbo.Comment'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."</p> <p><strong>I need a unidirectional mapping.</strong> The answer provided yet is talking about bi-directional mapping.</p> <p>Does NHibernate cascade save works with native ID generator?</p> <h2>DB tables:</h2> <p>BlogArticle{ID, Name}, where in case of ID, Identitity=true.</p> <p>Comment{ID, Name, BlogArticleID}, where in case of ID, Identitity=true.</p> <h2>Comment.hbm.xml</h2> <pre><code>&lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernate__OneToMany.BO" namespace="NHibernate__OneToMany.BO" default-access="property"&gt; &lt;class name="Comment" table="Comment"&gt; &lt;id name="ID"&gt; &lt;generator class="native" /&gt; &lt;/id&gt; &lt;property name="Name" /&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; public class Comment { private int _id; public virtual int ID { get { return _id; } set { _id = value; } } public Comment() { } public Comment(string name) { this._name = name; } private string _name; public virtual string Name { get { return _name; } set { _name = value; } } } </code></pre> <h2>BlogArticle.hbm.xml</h2> <pre><code>&lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="NHibernate__OneToMany.BO" assembly="NHibernate__OneToMany.BO" default-access="property"&gt; &lt;class name="BlogArticle" table="BlogArticle"&gt; &lt;id name="ID"&gt; &lt;generator class="native" /&gt; &lt;/id&gt; &lt;property name="Name" column="Name" /&gt; &lt;bag name="Comments" cascade="all" &gt; &lt;key column="BlogArticleID" /&gt; &lt;one-to-many class="Comment" /&gt; &lt;/bag&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; public class BlogArticle { private int _id; public virtual int ID { get { return _id; } set { _id = value; } } private string _name; public virtual string Name { get { return _name; } set { _name = value; } } private IList _depts; public virtual IList Comments { get { return _depts; } set { _depts = value; } } } </code></pre> <h2>Main</h2> <pre><code>class Program { static void Main(string[] args) { BlogArticle ba = new BlogArticle(); ba.Name = "Humanity"; ba.Comments = new List&lt;Comment&gt;(); ba.Comments.Add(new Comment("Comm1")); ba.Comments.Add(new Comment("Comm2")); ba.Comments.Add(new Comment("Comm3")); Repository&lt;BlogArticle&gt; rep = new Repository&lt;BlogArticle&gt;(); rep.Save(ba); } } </code></pre> <h2>Repository</h2> <pre><code>public class Repository&lt;T&gt; : IRepository&lt;T&gt; { ISession _session; public Repository() { _session = SessionFactoryManager.SessionFactory.OpenSession(); } private void Commit() { if (_session.Transaction.IsActive) { _session.Transaction.Commit(); } } private void Rollback() { if (_session.Transaction.IsActive) { _session.Transaction.Rollback(); //_session.Clear(); } } private void BeginTransaction() { _session.BeginTransaction(); } public void Save(T obj) { try { this.BeginTransaction(); _session.Save(obj); this.Commit(); } catch (Exception ex) { this.Rollback(); throw ex; } } void IRepository&lt;T&gt;.Save(IList&lt;T&gt; objs) { try { this.BeginTransaction(); for (Int32 I = 0; I &lt; objs.Count; ++I) { _session.Save(objs[I]); } this.Commit(); } catch (Exception ex) { this.Rollback(); throw ex; } } void IRepository&lt;T&gt;.Update(T obj) { try { this.BeginTransaction(); _session.Update(obj); this.Commit(); } catch (Exception ex) { this.Rollback(); throw ex; } } void IRepository&lt;T&gt;.Update(IList&lt;T&gt; objs) { try { this.BeginTransaction(); for (Int32 I = 0; I &lt; objs.Count; ++I) { _session.Update(objs[I]); } this.Commit(); } catch (Exception ex) { this.Rollback(); throw ex; } } void IRepository&lt;T&gt;.Delete(T obj) { try { this.BeginTransaction(); _session.Delete(obj); this.Commit(); } catch (Exception ex) { this.Rollback(); throw ex; } } void IRepository&lt;T&gt;.Delete(IList&lt;T&gt; objs) { try { this.BeginTransaction(); for (Int32 I = 0; I &lt; objs.Count; ++I) { _session.Delete(objs[I]); } this.Commit(); } catch (Exception ex) { this.Rollback(); throw ex; } } T IRepository&lt;T&gt;.Load&lt;T&gt;(object id) { return _session.Load&lt;T&gt;(id); } public IList&lt;T&gt; Get&lt;T&gt;(int pageIndex, int pageSize) { ICriteria criteria = _session.CreateCriteria(typeof(T)); criteria.SetFirstResult(pageIndex * pageSize); if (pageSize &gt; 0) { criteria.SetMaxResults(pageSize); } return criteria.List&lt;T&gt;(); } public T Get&lt;T&gt;(object id) { return _session.Get&lt;T&gt;(id); } public IList&lt;T&gt; Get&lt;T&gt;() { return Get&lt;T&gt;(0, 0); } public IList&lt;T&gt; Get&lt;T&gt;(string propertyName, bool Ascending) { Order cr1 = new Order(propertyName, Ascending); IList&lt;T&gt; objsResult = _session.CreateCriteria(typeof(T)).AddOrder(cr1).List&lt;T&gt;(); return objsResult; } public IList&lt;T&gt; Find&lt;T&gt;(IList&lt;string&gt; strs) { System.Collections.Generic.IList&lt;NHibernate.Criterion.ICriterion&gt; objs = new System.Collections.Generic.List&lt;ICriterion&gt;(); foreach (string s in strs) { NHibernate.Criterion.ICriterion cr1 = NHibernate.Criterion.Expression.Sql(s); objs.Add(cr1); } ICriteria criteria = _session.CreateCriteria(typeof(T)); foreach (ICriterion rest in objs) _session.CreateCriteria(typeof(T)).Add(rest); criteria.SetFirstResult(0); return criteria.List&lt;T&gt;(); } public void Detach(T item) { _session.Evict(item); } } </code></pre>
1
4,557
Swing/JFrame vs AWT/Frame for rendering outside the EDT
<p>What are the principle differences between using an AWT Frame and a Swing JFrame when implementing your own rendering and not using standard Java GUI components?</p> <p>This is a follow on from a previous question:</p> <p><a href="https://stackoverflow.com/questions/6824756/awt-custom-rendering-capture-smooth-resizes-and-eliminate-resize-flicker/6893310#comment-8211192">AWT custom rendering - capture smooth resizes and eliminate resize flicker</a></p> <p>The typical talking points on Swing vs AWT don't seem to apply because we're only using frames. Heavyweight vs Lightweight goes out the window (and JFrame extends Frame), for example.</p> <p>So which is best, JFrame or Frame for <strong>this situation</strong>? Does it make any meaningful difference?</p> <p>Note: this scenario is one where <strong>rendering in the EDT is not desirable</strong>. There is an application workflow which is not linked to the EDT and rendering is done on an as-needs basis outside of the EDT. To synchronize rendering with the EDT would add latency to the rendering. We are not rendering any Swing or AWT components other than the Frame or JFrame (or an enclosed JPanel/Component/etc if it is best).</p> <pre><code>import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.Toolkit; import java.awt.image.BufferStrategy; import java.awt.Frame; public class SmoothResize extends Frame { public static void main(String[] args) { Toolkit.getDefaultToolkit().setDynamicLayout(true); System.setProperty("sun.awt.noerasebackground", "true"); SmoothResize srtest = new SmoothResize(); //srtest.setIgnoreRepaint(true); srtest.setSize(100, 100); srtest.setVisible(true); } public SmoothResize() { render(); } private Dimension old_size = new Dimension(0, 0); private Dimension new_size = new Dimension(0, 0); public void validate() { super.validate(); new_size.width = getWidth(); new_size.height = getHeight(); if (old_size.equals(new_size)) { return; } else { render(); } } public void paint(Graphics g) { validate(); } public void update(Graphics g) { paint(g); } public void addNotify() { super.addNotify(); createBufferStrategy(2); } protected synchronized void render() { BufferStrategy strategy = getBufferStrategy(); if (strategy == null) { return; } // Render single frame do { // The following loop ensures that the contents of the drawing buffer // are consistent in case the underlying surface was recreated do { Graphics draw = strategy.getDrawGraphics(); Insets i = getInsets(); int w = (int)(((double)(getWidth() - i.left - i.right))/2+0.5); int h = (int)(((double)(getHeight() - i.top - i.bottom))/2+0.5); draw.setColor(Color.YELLOW); draw.fillRect(i.left, i.top + h, w,h); draw.fillRect(i.left + w, i.top, w,h); draw.setColor(Color.BLACK); draw.fillRect(i.left, i.top, w, h); draw.fillRect(i.left + w, i.top + h, w,h); draw.dispose(); // Repeat the rendering if the drawing buffer contents // were restored } while (strategy.contentsRestored()); // Display the buffer strategy.show(); // Repeat the rendering if the drawing buffer was lost } while (strategy.contentsLost()); } } </code></pre>
1
1,287
Access Application, Hidden Application Window With Form Taskbar Icon
<p>I have an access application with one main form. When you open the application, an AutoExec macro hides the application via the Windows API apiShowWindow. Then, the AutoExec opens up the main form which is set to Popup. This all works beautifully; my database guts are hidden and the form opens up and just floats along.</p> <p>However, when the access database gets hidden, you loose the taskbar icon. I have a custom icon set in the Options\Current Database\Application Icon setting. If I don't hide the database, this icon displays just fine in the task bar.</p> <p>I found an API workaround that will show an icon in the taskbar for just the form. It goes a little something like this:</p> <pre><code>Public Declare Function GetWindowLong Lib "user32" _ Alias "GetWindowLongA" _ (ByVal hWnd As Long, _ ByVal nIndex As Long) As Long Public Declare Function SetWindowLong Lib "user32" _ Alias "SetWindowLongA" _ (ByVal hWnd As Long, _ ByVal nIndex As Long, _ ByVal dwNewLong As Long) As Long Public Declare Function SetWindowPos Lib "user32" _ (ByVal hWnd As Long, _ ByVal hWndInsertAfter As Long, _ ByVal X As Long, _ ByVal Y As Long, _ ByVal cx As Long, _ ByVal cy As Long, _ ByVal wFlags As Long) As Long Public Sub AppTasklist(frmHwnd) Dim WStyle As Long Dim Result As Long WStyle = GetWindowLong(frmHwnd, GWL_EXSTYLE) WStyle = WStyle Or WS_EX_APPWINDOW Result = SetWindowPos(frmHwnd, HWND_TOP, 0, 0, 0, 0, _ SWP_NOMOVE Or _ SWP_NOSIZE Or _ SWP_NOACTIVATE Or _ SWP_HIDEWINDOW) Result = SetWindowLong(frmHwnd, GWL_EXSTYLE, WStyle) Debug.Print Result Result = SetWindowPos(frmHwnd, HWND_TOP, 0, 0, 0, 0, _ SWP_NOMOVE Or _ SWP_NOSIZE Or _ SWP_NOACTIVATE Or _ SWP_SHOWWINDOW) End Sub </code></pre> <p>This approach does work; I get an icon in the taskbar dedicated to just the form. However, the icon in the taskbar is the standard Access icon.</p> <p>In response to this problem, I added another API call using the SendMessageA:</p> <blockquote> <p>Public Declare Function SendMessage32 Lib "user32" Alias _ "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, _ ByVal wParam As Long, ByVal lParam As Long) As Long</p> </blockquote> <p>Executed thus:</p> <pre><code>Private Const WM_SETICON = &amp;H80 Private Const ICON_SMALL = 0&amp; Private Const ICON_BIG = 1&amp; Dim icoPth As String: icoPth = CurrentProject.Path &amp; "\MyAppIcon.ico" Dim NewIco As Long: NewIco = ExtractIcon32(0, icoPth, 0) Dim frmHwnd As Long: frmHwnd = Me.hwnd 'the form's handle SendMessage32 frmHwnd, WM_SETICON, ICON_SMALL, NewIco SendMessage32 frmHwnd, WM_SETICON, ICON_BIG, NewIco SendMessage32 hWndAccessApp, WM_SETICON, ICON_SMALL, NewIco SendMessage32 hWndAccessApp, WM_SETICON, ICON_BIG, NewIco </code></pre> <p>Keep in mind that I have tried the above four lines of 'SendMessages' in various orders inside of and outside of, top of and bottom of the AppTasklist Sub to no avail.</p> <p>It does appear to work at the application level, but it never seems to work at the form level.</p> <p>For those of you familiar with this particular predicament, let me list some of the other options outside of VBA that I have tried.</p> <p>1.) Taskbar\Properties\Taskbar buttons. I've changed this menu option to 'Never Combine' and 'Combine When Taskbar Is Full'. So, basically, this does work; I now get my icon for just the folder and the little label. BUT(!), it only works if the users have these settings checked on their end. In my experience, almost no one uses any of the options except 'Always combine, hide labels'.</p> <p>2.) Changing the Registry settings. You can change the following registry key to change the default icon an application uses: "HKEY_CLASSES_ROOT\Access.Application.14\DefaultIcon(Default)." However, most users (myself included) don't have access to the HKEY_CLASSES_ROOT part of the registry. Furthermore, I would have to write some code to find the proper key and then change it (which I could do) but, it's unclear if this change would be immediate--not to mention I'd have to change it back when exiting the application.</p> <p>3.) Right-clicking the pinned application, then right clicking the application in the menu does give you a properties menu with a button called 'Change Icon...' in the 'Shortcut' tab. However, for a program like Access, this button is greyed out.</p> <p>I am using Windows 7 and Access 2010.</p> <p>Is it possible to force the Taskbar Icon in the above scenario to something other than the standard Access Icon?</p> <p>I feel like there's ether a little something I'm missing, or an API function that could be used, or a better SendMessage constant, or that, maybe, it just can't be done.</p> <p>Any help would be greatly appreciated.</p> <p>Also, as a disclaimer (I guess): obviously the above code was pulled from other posts from this forum and others. Most of it was unattributed from whence I got it. I've made some minor tweeks to make it work in Access as opposed to that other piece of Microsoft Software that keeps getting in my search results so I will not name it here.</p> <p>Thanks!</p>
1
1,777
CSV with embedded commas using C# .Net 4.0 LINQ
<p>I'm attempting to find an elegant way to read a cvs string via 4.0 linq and have been somewhat unsuccessful due to embedded commas between quotes. Here is an example of 3 columns and 3 rows:</p> <blockquote> <p>Date,Years,MemoText "2011-01-01","0.5","Memo Text<br> Memo Text continuing<br> And still continuing, and then comma, yet the memo is in quotes"<br> "2010-01-01","0.5","Memo Text, Memo without line breaks"<br> "2009-01-01","1.0","Plain memo text"<br></p> </blockquote> <p>So far I've come up with the following faulty code as the pulling together other stack exchange bits. This doesn't work since carriage line feeds in memo text since carriage return line feeds break up memo text into multiple fields.</p> <pre><code>using (var reader = new StreamReader(getReader)) { var records = reader.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); var enumRecords = records.Skip(1).Take(1); using (var dc = new DataContext()) { foreach (var record in enumRecords .Select(x =&gt; x.Trim() .Split(new char[] { ',' })) .Select(fields =&gt; new Entity { Date = (!string.IsNullOrEmpty(record.ElementAt(0))) ? Convert.ToDateTime(record.ElementAt(0)) : default(DateTime), DecimalYears = record.ElementAt(1), MemoText = record.ElementAt(2) })) { //Commit DataContext } } } </code></pre> <p>No dice when splitting on commas alone since commas exist between quoted text:</p> <pre><code>using (var reader = new StreamReader(getReader)) { var sdata = reader.ReadToEnd(); using (var dc = new DataContext()) { var query = sdata .Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Replace(Environment.NewLine, string.Empty) .Replace("\"\"", "\",\"") .Select((i, n) =&gt; new { i, n }) .GroupBy(a =&gt; a.n / 3) .Skip(1).Take(1); foreach (var fields in query) { var newEntity = new Entity(); newEntity.Date = (!string.IsNullOrEmpty(fields.ElementAt(0).i)) ? Convert.ToDateTime(fields.ElementAt(0).i) : default(DateTime); newEntity.DecimalYears = fields.ElementAt(1).i; newEntity.MemoText = fields.ElementAt(2).i; } } } </code></pre> <p>So far what seems like a simple objective is bordering on verbose ugly code, possibly someone out there has a clean and functional way to approach this using LINQ? </p>
1
1,065
ERROR/AndroidRuntime(328): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10
<p>**How to solve this ERROR/AndroidRuntime(328): Caused by: </p> <p>java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10 this problem ...**</p> <pre><code>**Log cat:** 06-15 05:11:39.499: ERROR/AndroidRuntime(328): FATAL EXCEPTION: AsyncTask #2 06-15 05:11:39.499: ERROR/AndroidRuntime(328): java.lang.RuntimeException: An error occured while executing doInBackground() 06-15 05:11:39.499: ERROR/AndroidRuntime(328): at android.os.AsyncTask$3.done(AsyncTask.java:200) 06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.lang.Thread.run(Thread.java:1096) **06-15 05:11:39.499: ERROR/AndroidRuntime(328): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10** 06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257) 06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.ArrayList.get(ArrayList.java:311) 06-15 05:11:39.499: ERROR/AndroidRuntime(328): at $MyGroupByCategorySync.doInBackground(GroupByCategoryProductSearchMainActivity.java:691) 06-15 05:11:39.499: ERROR/AndroidRuntime(328): at android.os.AsyncTask$2.call(AsyncTask.java:185) 06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 06-15 05:11:39.499: ERROR/AndroidRuntime(328): ... 4 more </code></pre> <p><strong>Code :</strong></p> <pre><code> private void createSingleRow(String bycategory_info[],Drawable product_image) { Log.e("------------", "........................................................................................."); Log.v("--&gt;","GroupByCategoryProductSearchMainActivity STARTING createSingleRow()"); String productname = bycategory_info[1]; String city = bycategory_info[4]; String state = bycategory_info[4]; final String strOfferid=bycategory_info[3]; // for(int row_id=0;row_id&lt;no_of_rows;row_id++) // { TableRow table_row = new TableRow(this); TextView tv_blank = new TextView(this); TextView tv_photo = new TextView(this); TextView txt_pname = new TextView(this); TextView txt_city = new TextView(this); TextView txt_state = new TextView(this); TextView img_line = new TextView(this); LinearLayout line_layout = new LinearLayout(this); LinearLayout row_layout = new LinearLayout(this); table_row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT ,LayoutParams.FILL_PARENT)); table_row.setPadding(0, 5, 0, 5); tv_blank.setWidth(11); tv_photo.setBackgroundDrawable(product_image); Log.i("--: VALUE :--", "PRODUCT IMAGE SET TO ROW = "+single_row_id+" "+product_image); tv_photo.setLayoutParams(new TableRow.LayoutParams(45 ,45)); tv_photo.setGravity(Gravity.CENTER_VERTICAL); txt_pname.setBackgroundResource(R.drawable.empty); txt_pname.setText(productname); Log.i("--: VALUE :--", "PRODUCT NAME SET TO ROW = "+single_row_id+" "+productname); txt_pname.setTextColor(color_black); txt_pname.setTextSize(14); txt_pname.setWidth(110); txt_pname.setHeight(60); txt_pname.setPadding(10,0,0,0); txt_pname.setGravity(Gravity.LEFT); txt_pname.setGravity(Gravity.CENTER_VERTICAL); txt_city.setBackgroundResource(R.drawable.empty); txt_city.setText(city); Log.i("--: VALUE :--", "location NAME SET TO ROW = "+single_row_id+" "+city); txt_city.setTextColor(color_black); txt_city.setTextSize(13); txt_city.setWidth(65); txt_city.setHeight(60); txt_city.setPadding(15,0,0,0); txt_city.setGravity(Gravity.LEFT); txt_city.setGravity(Gravity.CENTER_VERTICAL); txt_state.setBackgroundResource(R.drawable.empty); txt_state.setText(state); Log.i("--: VALUE :--", "PRODUCT NAME SET TO ROW = "+single_row_id+" "+state); txt_state.setTextColor(color_black); txt_state.setTextSize(13); txt_state.setWidth(65); txt_state.setHeight(60); txt_state.setPadding(15,0,0,0); txt_state.setGravity(Gravity.LEFT); txt_state.setGravity(Gravity.CENTER_VERTICAL); img_line.setBackgroundResource(R.drawable.separater_line); img_line.setLayoutParams(new TableRow.LayoutParams(LayoutParams.FILL_PARENT ,2)); line_layout.setGravity(Gravity.CENTER_HORIZONTAL); //table_row.setBackgroundColor(color_white); /* table_row.setGravity(Gravity.CENTER_VERTICAL); table_row.addView(tv_blank); table_row.addView(tv_photo); table_row.addView(btn_name);*/ row_layout.setGravity(Gravity.CENTER_VERTICAL); row_layout.addView(tv_blank); row_layout.addView(tv_photo); row_layout.addView(txt_pname); row_layout.addView(txt_city); row_layout.addView(txt_state); table_row.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { XMLDataParser.parseXML(XMLDataParser.GROUP_PRODUCT_ITEM_DETAIL_PARSER_CODE,strOfferid); Intent intent_show_detail = new Intent(GroupByCategoryProductSearchMainActivity.this,GroupByCategoryItemDetail.class); Toast.makeText(GroupByCategoryProductSearchMainActivity.this, "Row pressed", 1000); startActivity(intent_show_detail); finish(); } }); table_row.addView(row_layout); line_layout.addView(img_line); tl_group_product_list_by_category.addView(table_row); tl_group_product_list_by_category.addView(line_layout); // } Log.v("--&gt;","GroupByCategoryProductSearchMainActivity ENDING createSingleRow()"); single_row_id++; } </code></pre> <p><strong>Problem in :</strong></p> <pre><code>class MyGroupByCategorySync extends AsyncTask { String bycategory_info[] = new String[9]; Drawable product_image = null; int no_of_rows = list_productname.size(); @Override protected Object doInBackground(Object... params) { Log.i("--: doInBackground :-- ", "no_of_rows = "+no_of_rows); for(int i=0;i&lt;no_of_rows;i++) { bycategory_info[0] = list_productid.get(i).toString(); bycategory_info[1] = list_productname.get(i).toString(); bycategory_info[2] = list_offername.get(i).toString(); bycategory_info[3] = list_offerid.get(i).toString(); bycategory_info[4] = list_location.get(i).toString(); bycategory_info[5] = list_price.get(i).toString(); bycategory_info[6] = list_prdescription.get(i).toString(); bycategory_info[7] = list_catname.get(i).toString(); bycategory_info[8] = list_categoryid.get(i).toString(); product_image = loadImageFromWebOperations(list_thumbnail.get(i).toString()); XMLData.group_by_category_product_image_list.add(product_image); if(!is_searched) XMLData.initial_list_of_product_by_category.add(new ByCategory(bycategory_info[0],bycategory_info[1],list_thumbnail.get(i).toString(),bycategory_info[2],bycategory_info[3],bycategory_info[4],bycategory_info[5],bycategory_info[6],bycategory_info[7],bycategory_info[8], product_image)); else XMLData.searched_list_of_product_by_category.add(new ByCategory(bycategory_info[0],bycategory_info[1],list_thumbnail.get(i).toString(),bycategory_info[2],bycategory_info[3],bycategory_info[4],bycategory_info[5],bycategory_info[6],bycategory_info[7],bycategory_info[8], product_image)); publishProgress(); SystemClock.sleep(15); } Log.v("--&gt;","ENDING doInBackground()"); XMLData.is_by_category_product_data_parsed = true; return null; } @Override protected void onPostExecute(Object result) { super.onPostExecute(result); pressed_once = false; single_row_id = 0; Log.i("--: VALUE AFTER onPostExecute:--","pressed_once = "+pressed_once); } @Override protected void onProgressUpdate(Object... values) { createSingleRow(bycategory_info, product_image); } } </code></pre>
1
4,464
Asp .net Show modal popup on click event linkbutton which is on Modal popup
<p>I shown Modal popup (Modal2) on this Modal popup I have grid contain link button. on click event of link button i have to show another modal popup having grid.</p> <p>My First Modal popup Showing </p> <pre><code>&lt;asp:Button ID="btnScholershipApp" runat="server" Text="Button" SkinID="SelectButton" /&gt; &lt;Ajax:ModalPopupExtender ID="Modal2" runat="server" PopupControlID="table2" CancelControlID="img1" TargetControlID="btnScholershipApp" OnCancelScript="javascript:__doPostBack('clearfields2')"&gt; &lt;/Ajax:ModalPopupExtender&gt; </code></pre> <p>First Modal popup</p> <pre><code> &lt;table id="table2" runat="server" border="0" cellpadding="0" cellspacing="0" height="100%" style="border-collapse: collapse; height: auto; margin: 0px; padding: 0px; display: none;" width="1000" class="popupheading"&gt; &lt;tr&gt; &lt;td&gt; &lt;div style="width: 1000px; height: auto;"&gt; &lt;div style="width: 1000px; height: 40px; background-image: url('../../../PopU/top.png'); background-repeat: no-repeat;"&gt; &lt;img id="img1" runat="server" height="40" src="~/Images/close1.png" style="float: right;" width="40" /&gt; &lt;/div&gt; &lt;div style="width: 980px; height: auto; min-height: 100px; background-image: url('../../../PopU/center_bg.png'); background-repeat: repeat-y; padding: 0 10px 0 10px;"&gt; &lt;asp:Panel ID="modal_panel2" runat="server" Height="550" Width="980"&gt; &lt;table cellpadding="7px" cellspacing="7px" width="100%"&gt; &lt;tr&gt; &lt;td&gt; &lt;fieldset&gt; &lt;legend class="legend"&gt;Search &lt;/legend&gt; &lt;table border="0" cellpadding="0" cellspacing="0" width="100%"&gt; &lt;tr&gt; &lt;td&gt; &lt;asp:Label ID="Label5" runat="server" Text="Student Name"&gt;&lt;/asp:Label&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:TextBox ID="txtSAStudentName" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:Label ID="Label6" runat="server" Text="Student ID"&gt;&lt;/asp:Label&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:TextBox ID="txtSAStudentID" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:Label ID="Label4" runat="server" Text="Scholership Name"&gt;&lt;/asp:Label&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:TextBox ID="txtSAScholershipName" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;asp:Label ID="Label7" runat="server" Text="University PRN"&gt;&lt;/asp:Label&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:TextBox ID="txtSAScholershipPRN" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:Label ID="Label12" runat="server" Text="Date Of Birth"&gt;&lt;/asp:Label&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:TextBox ID="txtSADateOfBirth" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;ajaxtoolkit:CalendarExtender ID="CalendarExtender1" runat="server" Enabled="True" TargetControlID="txtSADateOfBirth"&gt; &lt;/ajaxtoolkit:CalendarExtender&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/fieldset&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;table width="100%"&gt; &lt;tr style="background-color: #F6F0DB;"&gt; &lt;td align="center" colspan="4"&gt; &lt;asp:UpdatePanel ID="UpdatePanel1" runat="server"&gt; &lt;ContentTemplate&gt; &lt;asp:HiddenField ID="hfScholershipName" runat="server" /&gt; &lt;asp:HiddenField ID="hfScholershipPRN" runat="server" /&gt; &lt;asp:HiddenField ID="hfScholershipApplicationID" runat="server" /&gt; &lt;asp:HiddenField ID="hfScholershipDocumentID" runat="server" /&gt; &lt;asp:GridView ID="grdScholershipApp" runat="server" AutoGenerateColumns="false" AllowPaging="True" OnPageIndexChanging="grdScholershipApp_PageIndexChanging" PageSize="10" Width="970px"&gt; &lt;Columns&gt; &lt;asp:BoundField DataField="StudentId" HeaderText="Student ID" /&gt; &lt;asp:BoundField DataField="FullName" HeaderText="Student Name"&gt; &lt;ItemStyle HorizontalAlign="Center" Width="250" /&gt; &lt;/asp:BoundField&gt; &lt;asp:BoundField DataField="ScholershipPRN" HeaderText="University PRN" /&gt; &lt;asp:BoundField DataField="DateOfBirth" HeaderText="Date of birth" /&gt; &lt;asp:BoundField DataField="ScholershipName" HeaderText="Scholership Name" /&gt; &lt;asp:TemplateField HeaderText="Options"&gt; &lt;ItemTemplate&gt; &lt;asp:UpdatePanel ID="pnlup2" runat="server"&gt; &lt;Triggers&gt; &lt;asp:PostBackTrigger ControlID="btnEditStudentApplication" /&gt; &lt;/Triggers&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="btnStudentDocumentIDShow" EventName="Click" /&gt; &lt;/Triggers&gt; &lt;ContentTemplate&gt; &lt;asp:ImageButton ID="btnEditStudentApplication" runat="server" CommandArgument='&lt;%#Eval("PanomtechServiceID")+";"+Eval("StudentID")+";"+Eval("ScholershipPRN")+";"+Eval("ScholershipName")%&gt;' SkinID="Select" OnClick="btnEditStudentApplication_Click" /&gt; &lt;%--&lt;asp:Panel ID="Panel12" runat="server" &gt; &lt;asp:UpdatePanel ID="UpdatePanel4" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional"&gt; &lt;ContentTemplate&gt; &lt;asp:Button ID="hfbtnStudentDocumentIDShow" runat="server" Style="display: none;" /&gt; &lt;/ContentTemplate&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="hfbtnStudentDocumentIDShow" EventName="Click" /&gt; &lt;/Triggers&gt; &lt;/asp:UpdatePanel&gt; &lt;/asp:Panel&gt;--%&gt; &lt;asp:LinkButton ID="btnStudentDocumentIDShow" runat="server" Text="Documents" CommandArgument='&lt;%#Eval("PanomtechServiceID")+";"+Eval("StudentID")+";"+Eval("StudentDocumentID")%&gt;' OkControlID="hfbtnStudentDocumentIDShow" /&gt; &lt;%-- OnClick="hfbtnStudentDocumentIDShow_Click" --%&gt; &lt;%--&lt;Ajax:ModalPopupExtender ID="modal4" runat="server" PopupControlID="table4" CancelControlID="img3" TargetControlID="btnStudentDocumentIDShow" OnCancelScript="javascript:__doPostBack('clearfields4')"&gt; &lt;/Ajax:ModalPopupExtender&gt;--%&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;EmptyDataTemplate&gt; no data....... &lt;/EmptyDataTemplate&gt; &lt;/asp:GridView&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/asp:Panel&gt; &lt;/div&gt; &lt;div style="width: 1000px; height: 40px; background-image: url('../../../PopU/bottom.png'); background-repeat: no-repeat;"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;Ajax:AnimationExtender ID="AnimationExtender2" runat="server" TargetControlID="btnScholershipApp"&gt; &lt;Animations&gt; &lt;OnClick&gt; &lt;Parallel AnimationTarget="table2" Duration=".9" Fps="50"&gt; &lt;FadeIn Duration=".9"/&gt; &lt;/Parallel&gt; &lt;/OnClick&gt; &lt;/Animations&gt; &lt;/Ajax:AnimationExtender&gt; </code></pre> <p>LinkButton Event</p> <pre><code>protected void hfbtnStudentDocumentIDShow_Click(object sender, EventArgs e) { modal4.Show(); } </code></pre> <p>Second Modal popup</p> <pre><code>&lt;table id="table4" runat="server" border="0" cellpadding="0" cellspacing="0" height="100%" style="border-collapse: collapse; height: auto; margin: 0px; padding: 0px;" width="1000" class="popupheading"&gt; &lt;tr&gt; &lt;td&gt; &lt;div style="width: 1000px; height: auto;"&gt; &lt;div style="width: 1000px; height: 40px; background-image: url('../../../PopU/top.png'); background-repeat: no-repeat;"&gt; &lt;img id="img4" runat="server" height="40" src="~/Images/close1.png" style="float: right;" width="40" /&gt; &lt;/div&gt; &lt;div style="width: 980px; height: auto; min-height: 100px; background-image: url('../../../PopU/center_bg.png'); background-repeat: repeat-y; padding: 0 10px 0 10px;"&gt; &lt;asp:Panel ID="modal_panel4" runat="server" Height="550" Width="980"&gt; &lt;table width="100%"&gt; &lt;tr style="background-color: #F6F0DB;"&gt; &lt;td align="center" colspan="4"&gt; &lt;asp:UpdatePanel ID="uppanel" runat="server"&gt; &lt;ContentTemplate&gt; &lt;asp:GridView ID="grdStudentDocuments" runat="server" AutoGenerateColumns="false" AllowPaging="True" OnPageIndexChanging="grdStudentDocuments_PageIndexChanging" PageSize="10" Width="970px"&gt; &lt;Columns&gt; &lt;asp:BoundField DataField="StudentId" HeaderText="Student ID" /&gt; &lt;asp:BoundField DataField="FullName" HeaderText="Student Name"&gt; &lt;ItemStyle HorizontalAlign="Center" Width="250" /&gt; &lt;/asp:BoundField&gt; &lt;asp:BoundField DataField="DocumentName" HeaderText="Document Name" /&gt; &lt;asp:BoundField DataField="ScholershipPRN" HeaderText="University PRN" /&gt; &lt;asp:BoundField DataField="ScholershipName" HeaderText="Scholership Name" /&gt; &lt;asp:TemplateField HeaderText="Select"&gt; &lt;ItemTemplate&gt; &lt;asp:UpdatePanel ID="pnlup3" runat="server"&gt; &lt;Triggers&gt; &lt;asp:PostBackTrigger ControlID="btnEditSStudentDocuments" /&gt; &lt;/Triggers&gt; &lt;ContentTemplate&gt; &lt;asp:ImageButton ID="btnEditSStudentDocuments" runat="server" CommandArgument='&lt;%#Eval("StudentDocumentID")%&gt;' SkinID="Select" OnClick="btnEditSStudentDocuments_Click" /&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;EmptyDataTemplate&gt; no data....... &lt;/EmptyDataTemplate&gt; &lt;/asp:GridView&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/asp:Panel&gt; &lt;/div&gt; &lt;div style="width: 1000px; height: 40px; background-image: url('../../../PopU/bottom.png'); background-repeat: no-repeat;"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;asp:Button ID="hfbtnStudentDocumentIDShow" runat="server" OnClick="hfbtnStudentDocumentIDShow_Click" Style="display: none;" /&gt; &lt;Ajax:ModalPopupExtender ID="modal4" runat="server" PopupControlID="table4" CancelControlID="img3" TargetControlID="hfbtnStudentDocumentIDShow" OnCancelScript="javascript:__doPostBack('clearfields4')"&gt; &lt;/Ajax:ModalPopupExtender&gt; &lt;Ajax:AnimationExtender ID="AnimationExtender4" runat="server" TargetControlID="hfbtnStudentDocumentIDShow"&gt; &lt;Animations&gt; &lt;OnClick&gt; &lt;Parallel AnimationTarget="table4" Duration=".9" Fps="50"&gt; &lt;FadeIn Duration=".9"/&gt; &lt;/Parallel&gt; &lt;/OnClick&gt; &lt;/Animations&gt; &lt;/Ajax:AnimationExtender&gt; </code></pre> <p>Problem </p> <p><strong>When I click on link button it does not display any thing Please help me</strong></p>
1
12,489
UIWebview remove padding / margin
<p>I am loading a PDF into a <code>UIWebview</code> and I changed the background color to clear and set opaque to false. However now there is a padding or margin in my <code>UIWebView</code> that I would like to remove so the <code>UIWebview</code> is the screen.</p> <p>I created a <code>UIWebview</code> like so:</p> <pre><code>let webview = UIWebView() webview.frame = self.view.bounds webview.scrollView.frame = webview.frame webview.userInteractionEnabled = true webview.scalesPageToFit = true webview.becomeFirstResponder() webview.delegate = self webview.scrollView.delegate = self webview.opaque = false webview.backgroundColor = UIColor.clearColor() self.view.addSubview(webview) webview.loadRequest(NSURLRequest(URL:url)) webview.gestureRecognizers = [pinchRecognizer, panRecognizer] </code></pre> <p>and I applied this to the webViewDidFinishLoad method</p> <pre><code>func webViewDidFinishLoad(webView: UIWebView) { let padding = "document.body.style.margin='0';document.body.style.padding = '0'" webView.stringByEvaluatingJavaScriptFromString(padding) } </code></pre> <p>but there is still a padding or margin, it looks like this:</p> <p><a href="https://i.stack.imgur.com/uc6tF.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/uc6tF.jpg" alt="enter image description here"></a></p> <p>How do I fix this?</p> <p>The Reason why I need this fixed is because I am going to be saving this UIWebView as a PDF and when I save it, that extra spacing is there also, here is my PDF generate code:</p> <pre><code>func drawPDFUsingPrintPageRenderer(printPageRenderer: UIPrintPageRenderer) -&gt; NSData! { let data = NSMutableData() UIGraphicsBeginPDFContextToData(data, CGRectZero, nil) UIGraphicsBeginPDFPage() printPageRenderer.drawPageAtIndex(0, inRect: UIGraphicsGetPDFContextBounds()) UIGraphicsEndPDFContext() return data } </code></pre> <p>and more</p> <pre><code>let screenHeight = appDelegate.webview!.scrollView.bounds.size.height let heightStr = appDelegate.webview!.scrollView.bounds.size.height let height = heightStr let pages = ceil(height / screenHeight) let pdfMutableData = NSMutableData() UIGraphicsBeginPDFContextToData(pdfMutableData, appDelegate.webview!.scrollView.bounds, nil) for i in 0..&lt;Int(pages) { if (CGFloat((i+1)) * screenHeight &gt; CGFloat(height)) { var f = appDelegate.webview!.scrollView.frame f.size.height -= ((CGFloat((i+1)) * screenHeight) - CGFloat(height)); appDelegate.webview!.scrollView.frame = f } UIGraphicsBeginPDFPage() let currentContext = UIGraphicsGetCurrentContext() appDelegate.webview!.scrollView.setContentOffset(CGPointMake(0, screenHeight * CGFloat(i)), animated: false) appDelegate.webview!.scrollView.layer.renderInContext(currentContext!) } UIGraphicsEndPDFContext() </code></pre>
1
1,184